PageRenderTime 40ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/rdfapi-php/api/util/adodb/adodb.inc.php

https://github.com/komagata/plnet
PHP | 3690 lines | 2342 code | 393 blank | 955 comment | 487 complexity | 1c8445d39907104a1bca845f12821267 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /*
  3. * Set tabs to 4 for best viewing.
  4. *
  5. * Latest version is available at http://adodb.sourceforge.net
  6. *
  7. * This is the main include file for ADOdb.
  8. * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
  9. *
  10. * The ADOdb files are formatted so that doxygen can be used to generate documentation.
  11. * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
  12. */
  13. /**
  14. \mainpage
  15. @version V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). 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://php.weblogs.com/adodb<br>
  26. Manual is at http://php.weblogs.com/adodb_manual
  27. */
  28. if (!defined('_ADODB_LAYER')) {
  29. define('_ADODB_LAYER',1);
  30. //==============================================================================================
  31. // CONSTANT DEFINITIONS
  32. //==============================================================================================
  33. /**
  34. * Set ADODB_DIR to the directory where this file resides...
  35. * This constant was formerly called $ADODB_RootPath
  36. */
  37. if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
  38. //==============================================================================================
  39. // GLOBAL VARIABLES
  40. //==============================================================================================
  41. GLOBAL
  42. $ADODB_vers, // database version
  43. $ADODB_COUNTRECS, // count number of records returned - slows down query
  44. $ADODB_CACHE_DIR, // directory to cache recordsets
  45. $ADODB_EXTENSION, // ADODB extension installed
  46. $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
  47. $ADODB_FETCH_MODE; // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
  48. //==============================================================================================
  49. // GLOBAL SETUP
  50. //==============================================================================================
  51. $ADODB_EXTENSION = defined('ADODB_EXTENSION');
  52. //********************************************************//
  53. /*
  54. Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
  55. Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
  56. 0 = ignore empty fields. All empty fields in array are ignored.
  57. 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
  58. 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
  59. 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values.
  60. */
  61. define('ADODB_FORCE_IGNORE',0);
  62. define('ADODB_FORCE_NULL',1);
  63. define('ADODB_FORCE_EMPTY',2);
  64. define('ADODB_FORCE_VALUE',3);
  65. //********************************************************//
  66. if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
  67. define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
  68. // allow [ ] @ ` " and . in table names
  69. define('ADODB_TABLE_REGEX','([]0-9a-z_\"\`\.\@\[-]*)');
  70. // prefetching used by oracle
  71. if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
  72. /*
  73. Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
  74. This currently works only with mssql, odbc, oci8po and ibase derived drivers.
  75. 0 = assoc lowercase field names. $rs->fields['orderid']
  76. 1 = assoc uppercase field names. $rs->fields['ORDERID']
  77. 2 = use native-case field names. $rs->fields['OrderID']
  78. */
  79. define('ADODB_FETCH_DEFAULT',0);
  80. define('ADODB_FETCH_NUM',1);
  81. define('ADODB_FETCH_ASSOC',2);
  82. define('ADODB_FETCH_BOTH',3);
  83. if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
  84. // PHP's version scheme makes converting to numbers difficult - workaround
  85. $_adodb_ver = (float) PHP_VERSION;
  86. if ($_adodb_ver >= 5.0) {
  87. define('ADODB_PHPVER',0x5000);
  88. } else if ($_adodb_ver > 4.299999) { # 4.3
  89. define('ADODB_PHPVER',0x4300);
  90. } else if ($_adodb_ver > 4.199999) { # 4.2
  91. define('ADODB_PHPVER',0x4200);
  92. } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
  93. define('ADODB_PHPVER',0x4050);
  94. } else {
  95. define('ADODB_PHPVER',0x4000);
  96. }
  97. }
  98. //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  99. /**
  100. Accepts $src and $dest arrays, replacing string $data
  101. */
  102. function ADODB_str_replace($src, $dest, $data)
  103. {
  104. if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
  105. $s = reset($src);
  106. $d = reset($dest);
  107. while ($s !== false) {
  108. $data = str_replace($s,$d,$data);
  109. $s = next($src);
  110. $d = next($dest);
  111. }
  112. return $data;
  113. }
  114. function ADODB_Setup()
  115. {
  116. GLOBAL
  117. $ADODB_vers, // database version
  118. $ADODB_COUNTRECS, // count number of records returned - slows down query
  119. $ADODB_CACHE_DIR, // directory to cache recordsets
  120. $ADODB_FETCH_MODE,
  121. $ADODB_FORCE_TYPE;
  122. $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
  123. $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
  124. if (!isset($ADODB_CACHE_DIR)) {
  125. $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
  126. } else {
  127. // do not accept url based paths, eg. http:/ or ftp:/
  128. if (strpos($ADODB_CACHE_DIR,'://') !== false)
  129. die("Illegal path http:// or ftp://");
  130. }
  131. // Initialize random number generator for randomizing cache flushes
  132. srand(((double)microtime())*1000000);
  133. /**
  134. * ADODB version as a string.
  135. */
  136. $ADODB_vers = 'V4.52 10 Aug 2004 (c) 2000-2004 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
  137. /**
  138. * Determines whether recordset->RecordCount() is used.
  139. * Set to false for highest performance -- RecordCount() will always return -1 then
  140. * for databases that provide "virtual" recordcounts...
  141. */
  142. if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
  143. }
  144. //==============================================================================================
  145. // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
  146. //==============================================================================================
  147. ADODB_Setup();
  148. //==============================================================================================
  149. // CLASS ADOFieldObject
  150. //==============================================================================================
  151. /**
  152. * Helper class for FetchFields -- holds info on a column
  153. */
  154. class ADOFieldObject {
  155. var $name = '';
  156. var $max_length=0;
  157. var $type="";
  158. // additional fields by dannym... (danny_milo@yahoo.com)
  159. var $not_null = false;
  160. // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
  161. // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
  162. var $has_default = false; // this one I have done only in mysql and postgres for now ...
  163. // others to come (dannym)
  164. var $default_value; // default, if any, and supported. Check has_default first.
  165. }
  166. function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
  167. {
  168. //print "Errorno ($fn errno=$errno m=$errmsg) ";
  169. $thisConnection->_transOK = false;
  170. if ($thisConnection->_oldRaiseFn) {
  171. $fn = $thisConnection->_oldRaiseFn;
  172. $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
  173. }
  174. }
  175. //==============================================================================================
  176. // CLASS ADOConnection
  177. //==============================================================================================
  178. /**
  179. * Connection object. For connecting to databases, and executing queries.
  180. */
  181. class ADOConnection {
  182. //
  183. // PUBLIC VARS
  184. //
  185. var $dataProvider = 'native';
  186. var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
  187. var $database = ''; /// Name of database to be used.
  188. var $host = ''; /// The hostname of the database server
  189. var $user = ''; /// The username which is used to connect to the database server.
  190. var $password = ''; /// Password for the username. For security, we no longer store it.
  191. var $debug = false; /// if set to true will output sql statements
  192. var $maxblobsize = 256000; /// maximum size of blobs or large text fields -- some databases die otherwise like foxpro
  193. var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
  194. var $substr = 'substr'; /// substring operator
  195. var $length = 'length'; /// string length operator
  196. var $random = 'rand()'; /// random function
  197. var $upperCase = 'upper'; /// uppercase function
  198. var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
  199. var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
  200. var $true = '1'; /// string that represents TRUE for a database
  201. var $false = '0'; /// string that represents FALSE for a database
  202. var $replaceQuote = "\\'"; /// string to use to replace quotes
  203. var $nameQuote = '"'; /// string to use to quote identifiers and names
  204. var $charSet=false; /// character set to use - only for interbase
  205. var $metaDatabasesSQL = '';
  206. var $metaTablesSQL = '';
  207. var $uniqueOrderBy = false; /// All order by columns have to be unique
  208. var $emptyDate = '&nbsp;';
  209. var $emptyTimeStamp = '&nbsp;';
  210. var $lastInsID = false;
  211. //--
  212. var $hasInsertID = false; /// supports autoincrement ID?
  213. var $hasAffectedRows = false; /// supports affected rows for update/delete?
  214. var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
  215. var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
  216. var $readOnly = false; /// this is a readonly database - used by phpLens
  217. var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
  218. var $hasGenID = false; /// can generate sequences using GenID();
  219. var $hasTransactions = true; /// has transactions
  220. //--
  221. var $genID = 0; /// sequence id used by GenID();
  222. var $raiseErrorFn = false; /// error function to call
  223. var $isoDates = false; /// accepts dates in ISO format
  224. var $cacheSecs = 3600; /// cache for 1 hour
  225. var $sysDate = false; /// name of function that returns the current date
  226. var $sysTimeStamp = false; /// name of function that returns the current timestamp
  227. var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
  228. var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
  229. var $numCacheHits = 0;
  230. var $numCacheMisses = 0;
  231. var $pageExecuteCountRows = true;
  232. var $uniqueSort = false; /// indicates that all fields in order by must be unique
  233. var $leftOuter = false; /// operator to use for left outer join in WHERE clause
  234. var $rightOuter = false; /// operator to use for right outer join in WHERE clause
  235. var $ansiOuter = false; /// whether ansi outer join syntax supported
  236. var $autoRollback = false; // autoRollback on PConnect().
  237. var $poorAffectedRows = false; // affectedRows not working or unreliable
  238. var $fnExecute = false;
  239. var $fnCacheExecute = false;
  240. var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
  241. var $rsPrefix = "ADORecordSet_";
  242. var $autoCommit = true; /// do not modify this yourself - actually private
  243. var $transOff = 0; /// temporarily disable transactions
  244. var $transCnt = 0; /// count of nested transactions
  245. var $fetchMode=false;
  246. //
  247. // PRIVATE VARS
  248. //
  249. var $_oldRaiseFn = false;
  250. var $_transOK = null;
  251. var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
  252. var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
  253. /// then returned by the errorMsg() function
  254. var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
  255. var $_queryID = false; /// This variable keeps the last created result link identifier
  256. var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
  257. var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
  258. var $_evalAll = false;
  259. var $_affected = false;
  260. var $_logsql = false;
  261. /**
  262. * Constructor
  263. */
  264. function ADOConnection()
  265. {
  266. die('Virtual Class -- cannot instantiate');
  267. }
  268. function Version()
  269. {
  270. global $ADODB_vers;
  271. return (float) substr($ADODB_vers,1);
  272. }
  273. /**
  274. Get server version info...
  275. @returns An array with 2 elements: $arr['string'] is the description string,
  276. and $arr[version] is the version (also a string).
  277. */
  278. function ServerInfo()
  279. {
  280. return array('description' => '', 'version' => '');
  281. }
  282. function _findvers($str)
  283. {
  284. if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
  285. else return '';
  286. }
  287. /**
  288. * All error messages go through this bottleneck function.
  289. * You can define your own handler by defining the function name in ADODB_OUTP.
  290. */
  291. function outp($msg,$newline=true)
  292. {
  293. global $HTTP_SERVER_VARS,$ADODB_FLUSH,$ADODB_OUTP;
  294. if (defined('ADODB_OUTP')) {
  295. $fn = ADODB_OUTP;
  296. $fn($msg,$newline);
  297. return;
  298. } else if (isset($ADODB_OUTP)) {
  299. $fn = $ADODB_OUTP;
  300. $fn($msg,$newline);
  301. return;
  302. }
  303. if ($newline) $msg .= "<br>\n";
  304. if (isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']) || !$newline) echo $msg;
  305. else echo strip_tags($msg);
  306. if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
  307. }
  308. function Time()
  309. {
  310. $rs =& $this->_Execute("select $this->sysTimeStamp");
  311. if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
  312. return false;
  313. }
  314. /**
  315. * Connect to database
  316. *
  317. * @param [argHostname] Host to connect to
  318. * @param [argUsername] Userid to login
  319. * @param [argPassword] Associated password
  320. * @param [argDatabaseName] database
  321. * @param [forceNew] force new connection
  322. *
  323. * @return true or false
  324. */
  325. function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
  326. {
  327. if ($argHostname != "") $this->host = $argHostname;
  328. if ($argUsername != "") $this->user = $argUsername;
  329. if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
  330. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  331. $this->_isPersistentConnection = false;
  332. if ($forceNew) {
  333. if ($this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
  334. } else {
  335. if ($this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
  336. }
  337. $err = $this->ErrorMsg();
  338. if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  339. if ($fn = $this->raiseErrorFn)
  340. $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  341. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  342. return false;
  343. }
  344. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  345. {
  346. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
  347. }
  348. /**
  349. * Always force a new connection to database - currently only works with oracle
  350. *
  351. * @param [argHostname] Host to connect to
  352. * @param [argUsername] Userid to login
  353. * @param [argPassword] Associated password
  354. * @param [argDatabaseName] database
  355. *
  356. * @return true or false
  357. */
  358. function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  359. {
  360. return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
  361. }
  362. /**
  363. * Establish persistent connect to database
  364. *
  365. * @param [argHostname] Host to connect to
  366. * @param [argUsername] Userid to login
  367. * @param [argPassword] Associated password
  368. * @param [argDatabaseName] database
  369. *
  370. * @return return true or false
  371. */
  372. function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  373. {
  374. if (defined('ADODB_NEVER_PERSIST'))
  375. return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
  376. if ($argHostname != "") $this->host = $argHostname;
  377. if ($argUsername != "") $this->user = $argUsername;
  378. if ($argPassword != "") $this->password = $argPassword;
  379. if ($argDatabaseName != "") $this->database = $argDatabaseName;
  380. $this->_isPersistentConnection = true;
  381. if ($this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
  382. $err = $this->ErrorMsg();
  383. if (empty($err)) {
  384. $err = "Connection error to server '$argHostname' with user '$argUsername'";
  385. }
  386. if ($fn = $this->raiseErrorFn) {
  387. $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  388. }
  389. if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  390. return false;
  391. }
  392. // Format date column in sql string given an input format that understands Y M D
  393. function SQLDate($fmt, $col=false)
  394. {
  395. if (!$col) $col = $this->sysDate;
  396. return $col; // child class implement
  397. }
  398. /**
  399. * Should prepare the sql statement and return the stmt resource.
  400. * For databases that do not support this, we return the $sql. To ensure
  401. * compatibility with databases that do not support prepare:
  402. *
  403. * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
  404. * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
  405. * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
  406. *
  407. * @param sql SQL to send to database
  408. *
  409. * @return return FALSE, or the prepared statement, or the original sql if
  410. * if the database does not support prepare.
  411. *
  412. */
  413. function Prepare($sql)
  414. {
  415. return $sql;
  416. }
  417. /**
  418. * Some databases, eg. mssql require a different function for preparing
  419. * stored procedures. So we cannot use Prepare().
  420. *
  421. * Should prepare the stored procedure and return the stmt resource.
  422. * For databases that do not support this, we return the $sql. To ensure
  423. * compatibility with databases that do not support prepare:
  424. *
  425. * @param sql SQL to send to database
  426. *
  427. * @return return FALSE, or the prepared statement, or the original sql if
  428. * if the database does not support prepare.
  429. *
  430. */
  431. function PrepareSP($sql,$param=true)
  432. {
  433. return $this->Prepare($sql,$param);
  434. }
  435. /**
  436. * PEAR DB Compat
  437. */
  438. function Quote($s)
  439. {
  440. return $this->qstr($s,false);
  441. }
  442. /**
  443. Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
  444. */
  445. function QMagic($s)
  446. {
  447. return $this->qstr($s,get_magic_quotes_gpc());
  448. }
  449. function q(&$s)
  450. {
  451. $s = $this->qstr($s,false);
  452. }
  453. /**
  454. * PEAR DB Compat - do not use internally.
  455. */
  456. function ErrorNative()
  457. {
  458. return $this->ErrorNo();
  459. }
  460. /**
  461. * PEAR DB Compat - do not use internally.
  462. */
  463. function nextId($seq_name)
  464. {
  465. return $this->GenID($seq_name);
  466. }
  467. /**
  468. * Lock a row, will escalate and lock the table if row locking not supported
  469. * will normally free the lock at the end of the transaction
  470. *
  471. * @param $table name of table to lock
  472. * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
  473. */
  474. function RowLock($table,$where)
  475. {
  476. return false;
  477. }
  478. function CommitLock($table)
  479. {
  480. return $this->CommitTrans();
  481. }
  482. function RollbackLock($table)
  483. {
  484. return $this->RollbackTrans();
  485. }
  486. /**
  487. * PEAR DB Compat - do not use internally.
  488. *
  489. * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
  490. * for easy porting :-)
  491. *
  492. * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
  493. * @returns The previous fetch mode
  494. */
  495. function SetFetchMode($mode)
  496. {
  497. $old = $this->fetchMode;
  498. $this->fetchMode = $mode;
  499. if ($old === false) {
  500. global $ADODB_FETCH_MODE;
  501. return $ADODB_FETCH_MODE;
  502. }
  503. return $old;
  504. }
  505. /**
  506. * PEAR DB Compat - do not use internally.
  507. */
  508. function &Query($sql, $inputarr=false)
  509. {
  510. $rs = &$this->Execute($sql, $inputarr);
  511. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  512. return $rs;
  513. }
  514. /**
  515. * PEAR DB Compat - do not use internally
  516. */
  517. function &LimitQuery($sql, $offset, $count, $params=false)
  518. {
  519. $rs = &$this->SelectLimit($sql, $count, $offset, $params);
  520. if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  521. return $rs;
  522. }
  523. /**
  524. * PEAR DB Compat - do not use internally
  525. */
  526. function Disconnect()
  527. {
  528. return $this->Close();
  529. }
  530. /*
  531. Returns placeholder for parameter, eg.
  532. $DB->Param('a')
  533. will return ':a' for Oracle, and '?' for most other databases...
  534. For databases that require positioned params, eg $1, $2, $3 for postgresql,
  535. pass in Param(false) before setting the first parameter.
  536. */
  537. function Param($name,$type='C')
  538. {
  539. return '?';
  540. }
  541. /*
  542. InParameter and OutParameter are self-documenting versions of Parameter().
  543. */
  544. function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  545. {
  546. return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
  547. }
  548. /*
  549. */
  550. function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  551. {
  552. return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
  553. }
  554. /*
  555. Usage in oracle
  556. $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  557. $db->Parameter($stmt,$id,'myid');
  558. $db->Parameter($stmt,$group,'group',64);
  559. $db->Execute();
  560. @param $stmt Statement returned by Prepare() or PrepareSP().
  561. @param $var PHP variable to bind to
  562. @param $name Name of stored procedure variable name to bind to.
  563. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  564. @param [$maxLen] Holds an maximum length of the variable.
  565. @param [$type] The data type of $var. Legal values depend on driver.
  566. */
  567. function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  568. {
  569. return false;
  570. }
  571. /**
  572. Improved method of initiating a transaction. Used together with CompleteTrans().
  573. Advantages include:
  574. a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
  575. Only the outermost block is treated as a transaction.<br>
  576. b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
  577. c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
  578. are disabled, making it backward compatible.
  579. */
  580. function StartTrans($errfn = 'ADODB_TransMonitor')
  581. {
  582. if ($this->transOff > 0) {
  583. $this->transOff += 1;
  584. return;
  585. }
  586. $this->_oldRaiseFn = $this->raiseErrorFn;
  587. $this->raiseErrorFn = $errfn;
  588. $this->_transOK = true;
  589. if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
  590. $this->BeginTrans();
  591. $this->transOff = 1;
  592. }
  593. /**
  594. Used together with StartTrans() to end a transaction. Monitors connection
  595. for sql errors, and will commit or rollback as appropriate.
  596. @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
  597. and if set to false force rollback even if no SQL error detected.
  598. @returns true on commit, false on rollback.
  599. */
  600. function CompleteTrans($autoComplete = true)
  601. {
  602. if ($this->transOff > 1) {
  603. $this->transOff -= 1;
  604. return true;
  605. }
  606. $this->raiseErrorFn = $this->_oldRaiseFn;
  607. $this->transOff = 0;
  608. if ($this->_transOK && $autoComplete) {
  609. if (!$this->CommitTrans()) {
  610. $this->_transOK = false;
  611. if ($this->debug) ADOConnection::outp("Smart Commit failed");
  612. } else
  613. if ($this->debug) ADOConnection::outp("Smart Commit occurred");
  614. } else {
  615. $this->RollbackTrans();
  616. if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
  617. }
  618. return $this->_transOK;
  619. }
  620. /*
  621. At the end of a StartTrans/CompleteTrans block, perform a rollback.
  622. */
  623. function FailTrans()
  624. {
  625. if ($this->debug)
  626. if ($this->transOff == 0) {
  627. ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
  628. } else {
  629. ADOConnection::outp("FailTrans was called");
  630. adodb_backtrace();
  631. }
  632. $this->_transOK = false;
  633. }
  634. /**
  635. Check if transaction has failed, only for Smart Transactions.
  636. */
  637. function HasFailedTrans()
  638. {
  639. if ($this->transOff > 0) return $this->_transOK == false;
  640. return false;
  641. }
  642. /**
  643. * Execute SQL
  644. *
  645. * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
  646. * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
  647. * @return RecordSet or false
  648. */
  649. function &Execute($sql,$inputarr=false)
  650. {
  651. if ($this->fnExecute) {
  652. $fn = $this->fnExecute;
  653. $ret =& $fn($this,$sql,$inputarr);
  654. if (isset($ret)) return $ret;
  655. }
  656. if ($inputarr) {
  657. if (!is_array($inputarr)) $inputarr = array($inputarr);
  658. $element0 = reset($inputarr);
  659. # is_object check because oci8 descriptors can be passed in
  660. $array_2d = is_array($element0) && !is_object(reset($element0));
  661. if (!is_array($sql) && !$this->_bindInputArray) {
  662. $sqlarr = explode('?',$sql);
  663. if (!$array_2d) $inputarr = array($inputarr);
  664. foreach($inputarr as $arr) {
  665. $sql = ''; $i = 0;
  666. foreach($arr as $v) {
  667. $sql .= $sqlarr[$i];
  668. // from Ron Baldwin <ron.baldwin@sourceprose.com>
  669. // Only quote string types
  670. if (gettype($v) == 'string')
  671. $sql .= $this->qstr($v);
  672. else if ($v === null)
  673. $sql .= 'NULL';
  674. else
  675. $sql .= $v;
  676. $i += 1;
  677. }
  678. $sql .= $sqlarr[$i];
  679. if ($i+1 != sizeof($sqlarr))
  680. ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
  681. $ret =& $this->_Execute($sql);
  682. if (!$ret) return $ret;
  683. }
  684. } else {
  685. if ($array_2d) {
  686. $stmt = $this->Prepare($sql);
  687. foreach($inputarr as $arr) {
  688. $ret =& $this->_Execute($stmt,$arr);
  689. if (!$ret) return $ret;
  690. }
  691. } else {
  692. $ret =& $this->_Execute($sql,$inputarr);
  693. }
  694. }
  695. } else {
  696. $ret =& $this->_Execute($sql,false);
  697. }
  698. return $ret;
  699. }
  700. function& _Execute($sql,$inputarr=false)
  701. {
  702. if ($this->debug) {
  703. global $ADODB_INCLUDED_LIB;
  704. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  705. $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
  706. } else {
  707. $this->_queryID = @$this->_query($sql,$inputarr);
  708. }
  709. /************************
  710. // OK, query executed
  711. *************************/
  712. if ($this->_queryID === false) { // error handling if query fails
  713. if ($this->debug == 99) adodb_backtrace(true,5);
  714. $fn = $this->raiseErrorFn;
  715. if ($fn) {
  716. $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
  717. }
  718. return false;
  719. }
  720. if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
  721. $rs =& new ADORecordSet_empty();
  722. return $rs;
  723. }
  724. // return real recordset from select statement
  725. $rsclass = $this->rsPrefix.$this->databaseType;
  726. $rs =& new $rsclass($this->_queryID,$this->fetchMode);
  727. $rs->connection = &$this; // Pablo suggestion
  728. $rs->Init();
  729. if (is_array($sql)) $rs->sql = $sql[0];
  730. else $rs->sql = $sql;
  731. if ($rs->_numOfRows <= 0) {
  732. global $ADODB_COUNTRECS;
  733. if ($ADODB_COUNTRECS) {
  734. if (!$rs->EOF) {
  735. $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
  736. $rs->_queryID = $this->_queryID;
  737. } else
  738. $rs->_numOfRows = 0;
  739. }
  740. }
  741. return $rs;
  742. }
  743. function CreateSequence($seqname='adodbseq',$startID=1)
  744. {
  745. if (empty($this->_genSeqSQL)) return false;
  746. return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  747. }
  748. function DropSequence($seqname)
  749. {
  750. if (empty($this->_dropSeqSQL)) return false;
  751. return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  752. }
  753. /**
  754. * Generates a sequence id and stores it in $this->genID;
  755. * GenID is only available if $this->hasGenID = true;
  756. *
  757. * @param seqname name of sequence to use
  758. * @param startID if sequence does not exist, start at this ID
  759. * @return 0 if not supported, otherwise a sequence id
  760. */
  761. function GenID($seqname='adodbseq',$startID=1)
  762. {
  763. if (!$this->hasGenID) {
  764. return 0; // formerly returns false pre 1.60
  765. }
  766. $getnext = sprintf($this->_genIDSQL,$seqname);
  767. $holdtransOK = $this->_transOK;
  768. $rs = @$this->Execute($getnext);
  769. if (!$rs) {
  770. $this->_transOK = $holdtransOK; //if the status was ok before reset
  771. $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  772. $rs = $this->Execute($getnext);
  773. }
  774. if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
  775. else $this->genID = 0; // false
  776. if ($rs) $rs->Close();
  777. return $this->genID;
  778. }
  779. /**
  780. * @return the last inserted ID. Not all databases support this.
  781. */
  782. function Insert_ID()
  783. {
  784. if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
  785. if ($this->hasInsertID) return $this->_insertid();
  786. if ($this->debug) {
  787. ADOConnection::outp( '<p>Insert_ID error</p>');
  788. adodb_backtrace();
  789. }
  790. return false;
  791. }
  792. /**
  793. * Portable Insert ID. Pablo Roca <pabloroca@mvps.org>
  794. *
  795. * @return the last inserted ID. All databases support this. But aware possible
  796. * problems in multiuser environments. Heavy test this before deploying.
  797. */
  798. function PO_Insert_ID($table="", $id="")
  799. {
  800. if ($this->hasInsertID){
  801. return $this->Insert_ID();
  802. } else {
  803. return $this->GetOne("SELECT MAX($id) FROM $table");
  804. }
  805. }
  806. /**
  807. * @return # rows affected by UPDATE/DELETE
  808. */
  809. function Affected_Rows()
  810. {
  811. if ($this->hasAffectedRows) {
  812. if ($this->fnExecute === 'adodb_log_sql') {
  813. if ($this->_logsql && $this->_affected !== false) return $this->_affected;
  814. }
  815. $val = $this->_affectedrows();
  816. return ($val < 0) ? false : $val;
  817. }
  818. if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
  819. return false;
  820. }
  821. /**
  822. * @return the last error message
  823. */
  824. function ErrorMsg()
  825. {
  826. return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
  827. }
  828. /**
  829. * @return the last error number. Normally 0 means no error.
  830. */
  831. function ErrorNo()
  832. {
  833. return ($this->_errorMsg) ? -1 : 0;
  834. }
  835. function MetaError($err=false)
  836. {
  837. include_once(ADODB_DIR."/adodb-error.inc.php");
  838. if ($err === false) $err = $this->ErrorNo();
  839. return adodb_error($this->dataProvider,$this->databaseType,$err);
  840. }
  841. function MetaErrorMsg($errno)
  842. {
  843. include_once(ADODB_DIR."/adodb-error.inc.php");
  844. return adodb_errormsg($errno);
  845. }
  846. /**
  847. * @returns an array with the primary key columns in it.
  848. */
  849. function MetaPrimaryKeys($table, $owner=false)
  850. {
  851. // owner not used in base class - see oci8
  852. $p = array();
  853. $objs =& $this->MetaColumns($table);
  854. if ($objs) {
  855. foreach($objs as $v) {
  856. if (!empty($v->primary_key))
  857. $p[] = $v->name;
  858. }
  859. }
  860. if (sizeof($p)) return $p;
  861. if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
  862. return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
  863. return false;
  864. }
  865. /**
  866. * @returns assoc array where keys are tables, and values are foreign keys
  867. */
  868. function MetaForeignKeys($table, $owner=false, $upper=false)
  869. {
  870. return false;
  871. }
  872. /**
  873. * Choose a database to connect to. Many databases do not support this.
  874. *
  875. * @param dbName is the name of the database to select
  876. * @return true or false
  877. */
  878. function SelectDB($dbName)
  879. {return false;}
  880. /**
  881. * Will select, getting rows from $offset (1-based), for $nrows.
  882. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  883. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  884. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  885. * eg.
  886. * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
  887. * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
  888. *
  889. * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
  890. * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
  891. *
  892. * @param sql
  893. * @param [offset] is the row to start calculations from (1-based)
  894. * @param [nrows] is the number of rows to get
  895. * @param [inputarr] array of bind variables
  896. * @param [secs2cache] is a private parameter only used by jlim
  897. * @return the recordset ($rs->databaseType == 'array')
  898. */
  899. function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  900. {
  901. if ($this->hasTop && $nrows > 0) {
  902. // suggested by Reinhard Balling. Access requires top after distinct
  903. // Informix requires first before distinct - F Riosa
  904. $ismssql = (strpos($this->databaseType,'mssql') !== false);
  905. if ($ismssql) $isaccess = false;
  906. else $isaccess = (strpos($this->databaseType,'access') !== false);
  907. if ($offset <= 0) {
  908. // access includes ties in result
  909. if ($isaccess) {
  910. $sql = preg_replace(
  911. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
  912. if ($secs2cache>0) {
  913. $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
  914. } else {
  915. $ret =& $this->Execute($sql,$inputarr);
  916. }
  917. return $ret; // PHP5 fix
  918. } else if ($ismssql){
  919. $sql = preg_replace(
  920. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
  921. } else {
  922. $sql = preg_replace(
  923. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nrows.' ',$sql);
  924. }
  925. } else {
  926. $nn = $nrows + $offset;
  927. if ($isaccess || $ismssql) {
  928. $sql = preg_replace(
  929. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  930. } else {
  931. $sql = preg_replace(
  932. '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  933. }
  934. }
  935. }
  936. // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows
  937. // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
  938. global $ADODB_COUNTRECS;
  939. $savec = $ADODB_COUNTRECS;
  940. $ADODB_COUNTRECS = false;
  941. if ($offset>0){
  942. if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  943. else $rs = &$this->Execute($sql,$inputarr);
  944. } else {
  945. if ($secs2cache>0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  946. else $rs = &$this->Execute($sql,$inputarr);
  947. }
  948. $ADODB_COUNTRECS = $savec;
  949. if ($rs && !$rs->EOF) {
  950. $rs =& $this->_rs2rs($rs,$nrows,$offset);
  951. }
  952. //print_r($rs);
  953. return $rs;
  954. }
  955. /**
  956. * Create serializable recordset. Breaks rs link to connection.
  957. *
  958. * @param rs the recordset to serialize
  959. */
  960. function &SerializableRS(&$rs)
  961. {
  962. $rs2 =& $this->_rs2rs($rs);
  963. $ignore = false;
  964. $rs2->connection =& $ignore;
  965. return $rs2;
  966. }
  967. /**
  968. * Convert database recordset to an array recordset
  969. * input recordset's cursor should be at beginning, and
  970. * old $rs will be closed.
  971. *
  972. * @param rs the recordset to copy
  973. * @param [nrows] number of rows to retrieve (optional)
  974. * @param [offset] offset by number of rows (optional)
  975. * @return the new recordset
  976. */
  977. function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
  978. {
  979. if (! $rs) return false;
  980. $dbtype = $rs->databaseType;
  981. if (!$dbtype) {
  982. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
  983. return $rs;
  984. }
  985. if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
  986. $rs->MoveFirst();
  987. $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
  988. return $rs;
  989. }
  990. $flds = array();
  991. for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  992. $flds[] = $rs->FetchField($i);
  993. }
  994. $arr =& $rs->GetArrayLimit($nrows,$offset);
  995. //print_r($arr);
  996. if ($close) $rs->Close();
  997. $arrayClass = $this->arrayClass;
  998. $rs2 =& new $arrayClass();
  999. $rs2->connection = &$this;
  1000. $rs2->sql = $rs->sql;
  1001. $rs2->dataProvider = $this->dataProvider;
  1002. $rs2->InitArrayFields($arr,$flds);
  1003. return $rs2;
  1004. }
  1005. /*
  1006. * Return all rows. Compat with PEAR DB
  1007. */
  1008. function &GetAll($sql, $inputarr=false)
  1009. {
  1010. $arr =& $this->GetArray($sql,$inputarr);
  1011. return $arr;
  1012. }
  1013. function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
  1014. {
  1015. $rs =& $this->Execute($sql, $inputarr);
  1016. if (!$rs) return false;
  1017. $arr =& $rs->GetAssoc($force_array,$first2cols);
  1018. return $arr;
  1019. }
  1020. function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
  1021. {
  1022. if (!is_numeric($secs2cache)) {
  1023. $first2cols = $force_array;
  1024. $force_array = $inputarr;
  1025. }
  1026. $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
  1027. if (!$rs) return false;
  1028. $arr =& $rs->GetAssoc($force_array,$first2cols);
  1029. return $arr;
  1030. }
  1031. /**
  1032. * Return first element of first row of sql statement. Recordset is disposed
  1033. * for you.
  1034. *
  1035. * @param sql SQL statement
  1036. * @param [inputarr] input bind array
  1037. */
  1038. function GetOne($sql,$inputarr=false)
  1039. {
  1040. global $ADODB_COUNTRECS;
  1041. $crecs = $ADODB_COUNTRECS;
  1042. $ADODB_COUNTRECS = false;
  1043. $ret = false;
  1044. $rs = &$this->Execute($sql,$inputarr);
  1045. if ($rs) {
  1046. if (!$rs->EOF) $ret = reset($rs->fields);
  1047. $rs->Close();
  1048. }
  1049. $ADODB_COUNTRECS = $crecs;
  1050. return $ret;
  1051. }
  1052. function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
  1053. {
  1054. $ret = false;
  1055. $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1056. if ($rs) {
  1057. if (!$rs->EOF) $ret = reset($rs->fields);
  1058. $rs->Close();
  1059. }
  1060. return $ret;
  1061. }
  1062. function GetCol($sql, $inputarr = false, $trim = false)
  1063. {
  1064. $rv = false;
  1065. $rs = &$this->Execute($sql, $inputarr);
  1066. if ($rs) {
  1067. $rv = array();
  1068. if ($trim) {
  1069. while (!$rs->EOF) {
  1070. $rv[] = trim(reset($rs->fields));
  1071. $rs->MoveNext();
  1072. }
  1073. } else {
  1074. while (!$rs->EOF) {
  1075. $rv[] = reset($rs->fields);
  1076. $rs->MoveNext();
  1077. }
  1078. }
  1079. $rs->Close();
  1080. }
  1081. return $rv;
  1082. }
  1083. function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
  1084. {
  1085. $rv = false;
  1086. $rs = &$this->CacheExecute($secs, $sql, $inputarr);
  1087. if ($rs) {
  1088. if ($trim) {
  1089. while (!$rs->EOF) {
  1090. $rv[] = trim(reset($rs->fields));
  1091. $rs->MoveNext();
  1092. }
  1093. } else {
  1094. while (!$rs->EOF) {
  1095. $rv[] = reset($rs->fields);
  1096. $rs->MoveNext();
  1097. }
  1098. }
  1099. $rs->Close();
  1100. }
  1101. return $rv;
  1102. }
  1103. /*
  1104. Calculate the offset of a date for a particular database and generate
  1105. appropriate SQL. Useful for calculating future/past dates and storing
  1106. in a database.
  1107. If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
  1108. */
  1109. function OffsetDate($dayFraction,$date=false)
  1110. {
  1111. if (!$date) $date = $this->sysDate;
  1112. return '('.$date.'+'.$dayFraction.')';
  1113. }
  1114. /**
  1115. *
  1116. * @param sql SQL statement
  1117. * @param [inputarr] input bind array
  1118. */
  1119. function &GetArray($sql,$inputarr=false)
  1120. {
  1121. global $ADODB_COUNTRECS;
  1122. $savec = $ADODB_COUNTRECS;
  1123. $ADODB_COUNTRECS = false;
  1124. $rs =& $this->Execute($sql,$inputarr);
  1125. $ADODB_COUNTRECS = $savec;
  1126. if (!$rs)
  1127. if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  1128. else return false;
  1129. $arr =& $rs->GetArray();
  1130. $rs->Close();
  1131. return $arr;
  1132. }
  1133. function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
  1134. {
  1135. return $this->CacheGetArray($secs2cache,$sql,$inputarr);
  1136. }
  1137. function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
  1138. {
  1139. global $ADODB_COUNTRECS;
  1140. $savec = $ADODB_COUNTRECS;
  1141. $ADODB_COUNTRECS = false;
  1142. $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
  1143. $ADODB_COUNTRECS = $savec;
  1144. if (!$rs)
  1145. if (defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  1146. else return false;
  1147. $arr =& $rs->GetArray();
  1148. $rs->Close();
  1149. return $arr;
  1150. }
  1151. /**
  1152. * Return one row of sql statement. Recordset is disposed for you.
  1153. *
  1154. * @param sql SQL statement
  1155. * @param [inputarr] input bind array
  1156. */
  1157. function &GetRow($sql,$inputarr=false)
  1158. {
  1159. global $ADODB_COUNTRECS;
  1160. $crecs = $ADODB_COUNTRECS;
  1161. $ADODB_COUNTRECS = false;
  1162. $rs =& $this->Execute($sql,$inputarr);
  1163. $ADODB_COUNTRECS = $crecs;
  1164. if ($rs) {
  1165. if (!$rs->EOF) $arr = $rs->fields;
  1166. else $arr = array();
  1167. $rs->Close();
  1168. return $arr;
  1169. }
  1170. return false;
  1171. }
  1172. function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
  1173. {
  1174. $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
  1175. if ($rs) {
  1176. $arr = false;
  1177. if (!$rs->EOF) $arr = $rs->fields;
  1178. $rs->Close();
  1179. return $arr;
  1180. }
  1181. return false;
  1182. }
  1183. /**
  1184. * Insert or replace a single record. Note: this is not the same as MySQL's replace.
  1185. * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
  1186. * Also note that no table locking is done currently, so it is possible that the
  1187. * record be inserted twice by two programs...
  1188. *
  1189. * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
  1190. *
  1191. * $table table name
  1192. * $fieldArray associative array of data (you must quote strings yourself).
  1193. * $keyCol the primary key field name or if compound key, array of field names
  1194. * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers
  1195. * but does not work with dates nor SQL functions.
  1196. * has_autoinc the primary key is an auto-inc field, so skip in insert.
  1197. *
  1198. * Currently blob replace not supported
  1199. *
  1200. * returns 0 = fail, 1 = update, 2 = insert
  1201. */
  1202. function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
  1203. {
  1204. global $ADODB_INCLUDED_LIB;
  1205. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1206. return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
  1207. }
  1208. /**
  1209. * Will select, getting rows from $offset (1-based), for $nrows.
  1210. * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1211. * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1212. * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1213. * eg.
  1214. * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
  1215. * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
  1216. *
  1217. * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
  1218. *
  1219. * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional
  1220. * @param sql
  1221. * @param [offset] is the row to start calculations from (1-based)
  1222. * @param [nrows] is the number of rows to get
  1223. * @param [inputarr] array of bind variables
  1224. * @return the recordset ($rs->databaseType == 'array')
  1225. */
  1226. function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
  1227. {
  1228. if (!is_numeric($secs2cache)) {
  1229. if ($sql === false) $sql = -1;
  1230. if ($offset == -1) $offset = false;
  1231. // sql, nrows, offset,inputarr
  1232. $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
  1233. } else {
  1234. if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
  1235. $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  1236. }
  1237. return $rs;
  1238. }
  1239. /**
  1240. * Flush cached recordsets that match a particular $sql statement.
  1241. * If $sql == false, then we purge all files in the cache.
  1242. */
  1243. function CacheFlush($sql=false,$inputarr=false)
  1244. {
  1245. global $ADODB_CACHE_DIR;
  1246. if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1247. if (strncmp(PHP_OS,'WIN',3) === 0) {
  1248. $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
  1249. } else {
  1250. $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/??/adodb_*.cache';
  1251. // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
  1252. }
  1253. if ($this->debug) {
  1254. ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
  1255. } else {
  1256. exec($cmd);
  1257. }
  1258. return;
  1259. }
  1260. global $ADODB_INCLUDED_CSV;
  1261. if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
  1262. $f = $this->_gencachename($sql.serialize($inputarr),false);
  1263. adodb_write_file($f,''); // is adodb_write_file needed?
  1264. if (!@unlink($f)) {
  1265. if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1266. }
  1267. }
  1268. /**
  1269. * Private function to generate filename for caching.
  1270. * Filename is generated based on:
  1271. *
  1272. * - sql statement
  1273. * - database type (oci8, ibase, ifx, etc)
  1274. * - database name
  1275. * - userid
  1276. * - setFetchMode (adodb 4.23)
  1277. *
  1278. * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
  1279. * Assuming that we can have 50,000 files per directory with good performance,
  1280. * then we can scale to 12.8 million unique cached recordsets. Wow!
  1281. */
  1282. function _gencachename($sql,$createdir)
  1283. {
  1284. global $ADODB_CACHE_DIR;
  1285. static $notSafeMode;
  1286. if ($this->fetchMode === false) {
  1287. global $ADODB_FETCH_MODE;
  1288. $mode = $ADODB_FETCH_MODE;
  1289. } else {
  1290. $mode = $this->fetchMode;
  1291. }
  1292. $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
  1293. if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
  1294. $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
  1295. if ($createdir && $notSafeMode && !file_exists($dir)) {
  1296. $oldu = umask(0);
  1297. if (!mkdir($dir,0771))
  1298. if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
  1299. umask($oldu);
  1300. }
  1301. return $dir.'/adodb_'.$m.'.cache';
  1302. }
  1303. /**
  1304. * Execute SQL, caching recordsets.
  1305. *
  1306. * @param [secs2cache] seconds to cache data, set to 0 to force query.
  1307. * This is an optional parameter.
  1308. * @param sql SQL statement to execute
  1309. * @param [inputarr] holds the input data to bind to
  1310. * @return RecordSet or false
  1311. */
  1312. function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
  1313. {
  1314. if (!is_numeric($secs2cache)) {
  1315. $inputarr = $sql;
  1316. $sql = $secs2cache;
  1317. $secs2cache = $this->cacheSecs;
  1318. }
  1319. global $ADODB_INCLUDED_CSV;
  1320. if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
  1321. if (is_array($sql)) $sql = $sql[0];
  1322. $md5file = $this->_gencachename($sql.serialize($inputarr),true);
  1323. $err = '';
  1324. if ($secs2cache > 0){
  1325. $rs = &csv2rs($md5file,$err,$secs2cache);
  1326. $this->numCacheHits += 1;
  1327. } else {
  1328. $err='Timeout 1';
  1329. $rs = false;
  1330. $this->numCacheMisses += 1;
  1331. }
  1332. if (!$rs) {
  1333. // no cached rs found
  1334. if ($this->debug) {
  1335. if (get_magic_quotes_runtime()) {
  1336. ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
  1337. }
  1338. if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
  1339. }
  1340. $rs = &$this->Execute($sql,$inputarr);
  1341. if ($rs) {
  1342. $eof = $rs->EOF;
  1343. $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
  1344. $txt = _rs2serialize($rs,false,$sql); // serialize
  1345. if (!adodb_write_file($md5file,$txt,$this->debug)) {
  1346. if ($fn = $this->raiseErrorFn) {
  1347. $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
  1348. }
  1349. if ($this->debug) ADOConnection::outp( " Cache write error");
  1350. }
  1351. if ($rs->EOF && !$eof) {
  1352. $rs->MoveFirst();
  1353. //$rs = &csv2rs($md5file,$err);
  1354. $rs->connection = &$this; // Pablo suggestion
  1355. }
  1356. } else
  1357. @unlink($md5file);
  1358. } else {
  1359. $this->_errorMsg = '';
  1360. $this->_errorCode = 0;
  1361. if ($this->fnCacheExecute) {
  1362. $fn = $this->fnCacheExecute;
  1363. $fn($this, $secs2cache, $sql, $inputarr);
  1364. }
  1365. // ok, set cached object found
  1366. $rs->connection = &$this; // Pablo suggestion
  1367. if ($this->debug){
  1368. global $HTTP_SERVER_VARS;
  1369. $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
  1370. $ttl = $rs->timeCreated + $secs2cache - time();
  1371. $s = is_array($sql) ? $sql[0] : $sql;
  1372. if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
  1373. ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
  1374. }
  1375. }
  1376. return $rs;
  1377. }
  1378. /**
  1379. * Generates an Update Query based on an existing recordset.
  1380. * $arrFields is an associative array of fields with the value
  1381. * that should be assigned.
  1382. *
  1383. * Note: This function should only be used on a recordset
  1384. * that is run against a single table and sql should only
  1385. * be a simple select stmt with no groupby/orderby/limit
  1386. *
  1387. * "Jonathan Younger" <jyounger@unilab.com>
  1388. */
  1389. function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
  1390. {
  1391. global $ADODB_INCLUDED_LIB;
  1392. //********************************************************//
  1393. //This is here to maintain compatibility
  1394. //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
  1395. if (!isset($force)) {
  1396. global $ADODB_FORCE_TYPE;
  1397. $force = $ADODB_FORCE_TYPE;
  1398. }
  1399. //********************************************************//
  1400. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1401. return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
  1402. }
  1403. /**
  1404. * Generates an Insert Query based on an existing recordset.
  1405. * $arrFields is an associative array of fields with the value
  1406. * that should be assigned.
  1407. *
  1408. * Note: This function should only be used on a recordset
  1409. * that is run against a single table.
  1410. */
  1411. function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
  1412. {
  1413. global $ADODB_INCLUDED_LIB;
  1414. if (!isset($force)) {
  1415. global $ADODB_FORCE_TYPE;
  1416. $force = $ADODB_FORCE_TYPE;
  1417. }
  1418. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1419. return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
  1420. }
  1421. /**
  1422. * Update a blob column, given a where clause. There are more sophisticated
  1423. * blob handling functions that we could have implemented, but all require
  1424. * a very complex API. Instead we have chosen something that is extremely
  1425. * simple to understand and use.
  1426. *
  1427. * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
  1428. *
  1429. * Usage to update a $blobvalue which has a primary key blob_id=1 into a
  1430. * field blobtable.blobcolumn:
  1431. *
  1432. * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
  1433. *
  1434. * Insert example:
  1435. *
  1436. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1437. * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
  1438. */
  1439. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  1440. {
  1441. return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
  1442. }
  1443. /**
  1444. * Usage:
  1445. * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
  1446. *
  1447. * $blobtype supports 'BLOB' and 'CLOB'
  1448. *
  1449. * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1450. * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
  1451. */
  1452. function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  1453. {
  1454. $fd = fopen($path,'rb');
  1455. if ($fd === false) return false;
  1456. $val = fread($fd,filesize($path));
  1457. fclose($fd);
  1458. return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
  1459. }
  1460. function BlobDecode($blob)
  1461. {
  1462. return $blob;
  1463. }
  1464. function BlobEncode($blob)
  1465. {
  1466. return $blob;
  1467. }
  1468. function SetCharSet($charset)
  1469. {
  1470. return false;
  1471. }
  1472. function IfNull( $field, $ifNull )
  1473. {
  1474. return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
  1475. }
  1476. function LogSQL($enable=true)
  1477. {
  1478. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  1479. if ($enable) $this->fnExecute = 'adodb_log_sql';
  1480. else $this->fnExecute = false;
  1481. $old = $this->_logsql;
  1482. $this->_logsql = $enable;
  1483. if ($enable && !$old) $this->_affected = false;
  1484. return $old;
  1485. }
  1486. function GetCharSet()
  1487. {
  1488. return false;
  1489. }
  1490. /**
  1491. * Usage:
  1492. * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
  1493. *
  1494. * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
  1495. * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
  1496. */
  1497. function UpdateClob($table,$column,$val,$where)
  1498. {
  1499. return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
  1500. }
  1501. /**
  1502. * Change the SQL connection locale to a specified locale.
  1503. * This is used to get the date formats written depending on the client locale.
  1504. */
  1505. function SetDateLocale($locale = 'En')
  1506. {
  1507. $this->locale = $locale;
  1508. switch ($locale)
  1509. {
  1510. default:
  1511. case 'En':
  1512. $this->fmtDate="Y-m-d";
  1513. $this->fmtTimeStamp = "Y-m-d H:i:s";
  1514. break;
  1515. case 'Fr':
  1516. case 'Ro':
  1517. case 'It':
  1518. $this->fmtDate="d-m-Y";
  1519. $this->fmtTimeStamp = "d-m-Y H:i:s";
  1520. break;
  1521. case 'Ge':
  1522. $this->fmtDate="d.m.Y";
  1523. $this->fmtTimeStamp = "d.m.Y H:i:s";
  1524. break;
  1525. }
  1526. }
  1527. /**
  1528. * Close Connection
  1529. */
  1530. function Close()
  1531. {
  1532. return $this->_close();
  1533. // "Simon Lee" <simon@mediaroad.com> reports that persistent connections need
  1534. // to be closed too!
  1535. //if ($this->_isPersistentConnection != true) return $this->_close();
  1536. //else return true;
  1537. }
  1538. /**
  1539. * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
  1540. *
  1541. * @return true if succeeded or false if database does not support transactions
  1542. */
  1543. function BeginTrans() {return false;}
  1544. /**
  1545. * If database does not support transactions, always return true as data always commited
  1546. *
  1547. * @param $ok set to false to rollback transaction, true to commit
  1548. *
  1549. * @return true/false.
  1550. */
  1551. function CommitTrans($ok=true)
  1552. { return true;}
  1553. /**
  1554. * If database does not support transactions, rollbacks always fail, so return false
  1555. *
  1556. * @return true/false.
  1557. */
  1558. function RollbackTrans()
  1559. { return false;}
  1560. /**
  1561. * return the databases that the driver can connect to.
  1562. * Some databases will return an empty array.
  1563. *
  1564. * @return an array of database names.
  1565. */
  1566. function MetaDatabases()
  1567. {
  1568. global $ADODB_FETCH_MODE;
  1569. if ($this->metaDatabasesSQL) {
  1570. $save = $ADODB_FETCH_MODE;
  1571. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1572. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1573. $arr = $this->GetCol($this->metaDatabasesSQL);
  1574. if (isset($savem)) $this->SetFetchMode($savem);
  1575. $ADODB_FETCH_MODE = $save;
  1576. return $arr;
  1577. }
  1578. return false;
  1579. }
  1580. /**
  1581. * @param ttype can either be 'VIEW' or 'TABLE' or false.
  1582. * If false, both views and tables are returned.
  1583. * "VIEW" returns only views
  1584. * "TABLE" returns only tables
  1585. * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
  1586. * @param mask is the input mask - only supported by oci8 and postgresql
  1587. *
  1588. * @return array of tables for current database.
  1589. */
  1590. function &MetaTables($ttype=false,$showSchema=false,$mask=false)
  1591. {
  1592. global $ADODB_FETCH_MODE;
  1593. if ($mask) return false;
  1594. if ($this->metaTablesSQL) {
  1595. // complicated state saving by the need for backward compat
  1596. $save = $ADODB_FETCH_MODE;
  1597. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1598. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1599. $rs = $this->Execute($this->metaTablesSQL);
  1600. if (isset($savem)) $this->SetFetchMode($savem);
  1601. $ADODB_FETCH_MODE = $save;
  1602. if ($rs === false) return false;
  1603. $arr =& $rs->GetArray();
  1604. $arr2 = array();
  1605. if ($hast = ($ttype && isset($arr[0][1]))) {
  1606. $showt = strncmp($ttype,'T',1);
  1607. }
  1608. for ($i=0; $i < sizeof($arr); $i++) {
  1609. if ($hast) {
  1610. if ($showt == 0) {
  1611. if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
  1612. } else {
  1613. if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
  1614. }
  1615. } else
  1616. $arr2[] = trim($arr[$i][0]);
  1617. }
  1618. $rs->Close();
  1619. return $arr2;
  1620. }
  1621. return false;
  1622. }
  1623. function _findschema(&$table,&$schema)
  1624. {
  1625. if (!$schema && ($at = strpos($table,'.')) !== false) {
  1626. $schema = substr($table,0,$at);
  1627. $table = substr($table,$at+1);
  1628. }
  1629. }
  1630. /**
  1631. * List columns in a database as an array of ADOFieldObjects.
  1632. * See top of file for definition of object.
  1633. *
  1634. * @param table table name to query
  1635. * @param upper uppercase table name (required by some databases)
  1636. * @schema is optional database schema to use - not supported by all databases.
  1637. *
  1638. * @return array of ADOFieldObjects for current table.
  1639. */
  1640. function &MetaColumns($table,$upper=true)
  1641. {
  1642. global $ADODB_FETCH_MODE;
  1643. if (!empty($this->metaColumnsSQL)) {
  1644. $schema = false;
  1645. $this->_findschema($table,$schema);
  1646. $save = $ADODB_FETCH_MODE;
  1647. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  1648. if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  1649. $rs = $this->Execute(sprintf($this->metaColumnsSQL,($upper)?strtoupper($table):$table));
  1650. if (isset($savem)) $this->SetFetchMode($savem);
  1651. $ADODB_FETCH_MODE = $save;
  1652. if ($rs === false) return false;
  1653. $retarr = array();
  1654. while (!$rs->EOF) { //print_r($rs->fields);
  1655. $fld =& new ADOFieldObject();
  1656. $fld->name = $rs->fields[0];
  1657. $fld->type = $rs->fields[1];
  1658. if (isset($rs->fields[3]) && $rs->fields[3]) {
  1659. if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
  1660. $fld->scale = $rs->fields[4];
  1661. if ($fld->scale>0) $fld->max_length += 1;
  1662. } else
  1663. $fld->max_length = $rs->fields[2];
  1664. if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
  1665. else $retarr[strtoupper($fld->name)] = $fld;
  1666. $rs->MoveNext();
  1667. }
  1668. $rs->Close();
  1669. return $retarr;
  1670. }
  1671. return false;
  1672. }
  1673. /**
  1674. * List indexes on a table as an array.
  1675. * @param table table name to query
  1676. * @param primary include primary keys.
  1677. *
  1678. * @return array of indexes on current table.
  1679. */
  1680. function &MetaIndexes($table, $primary = false, $owner = false)
  1681. {
  1682. return FALSE;
  1683. }
  1684. /**
  1685. * List columns names in a table as an array.
  1686. * @param table table name to query
  1687. *
  1688. * @return array of column names for current table.
  1689. */
  1690. function &MetaColumnNames($table, $numIndexes=false)
  1691. {
  1692. $objarr =& $this->MetaColumns($table);
  1693. if (!is_array($objarr)) return false;
  1694. $arr = array();
  1695. if ($numIndexes) {
  1696. $i = 0;
  1697. foreach($objarr as $v) $arr[$i++] = $v->name;
  1698. } else
  1699. foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
  1700. return $arr;
  1701. }
  1702. /**
  1703. * Different SQL databases used different methods to combine strings together.
  1704. * This function provides a wrapper.
  1705. *
  1706. * param s variable number of string parameters
  1707. *
  1708. * Usage: $db->Concat($str1,$str2);
  1709. *
  1710. * @return concatenated string
  1711. */
  1712. function Concat()
  1713. {
  1714. $arr = func_get_args();
  1715. return implode($this->concat_operator, $arr);
  1716. }
  1717. /**
  1718. * Converts a date "d" to a string that the database can understand.
  1719. *
  1720. * @param d a date in Unix date time format.
  1721. *
  1722. * @return date string in database date format
  1723. */
  1724. function DBDate($d)
  1725. {
  1726. if (empty($d) && $d !== 0) return 'null';
  1727. if (is_string($d) && !is_numeric($d)) {
  1728. if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
  1729. if ($this->isoDates) return "'$d'";
  1730. $d = ADOConnection::UnixDate($d);
  1731. }
  1732. return adodb_date($this->fmtDate,$d);
  1733. }
  1734. /**
  1735. * Converts a timestamp "ts" to a string that the database can understand.
  1736. *
  1737. * @param ts a timestamp in Unix date time format.
  1738. *
  1739. * @return timestamp string in database timestamp format
  1740. */
  1741. function DBTimeStamp($ts)
  1742. {
  1743. if (empty($ts) && $ts !== 0) return 'null';
  1744. # strlen(14) allows YYYYMMDDHHMMSS format
  1745. if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
  1746. return adodb_date($this->fmtTimeStamp,$ts);
  1747. if ($ts === 'null') return $ts;
  1748. if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
  1749. $ts = ADOConnection::UnixTimeStamp($ts);
  1750. return adodb_date($this->fmtTimeStamp,$ts);
  1751. }
  1752. /**
  1753. * Also in ADORecordSet.
  1754. * @param $v is a date string in YYYY-MM-DD format
  1755. *
  1756. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  1757. */
  1758. function UnixDate($v)
  1759. {
  1760. if (is_numeric($v) && strlen($v) !== 8) return $v;
  1761. if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
  1762. ($v), $rr)) return false;
  1763. if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
  1764. // h-m-s-MM-DD-YY
  1765. return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  1766. }
  1767. /**
  1768. * Also in ADORecordSet.
  1769. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  1770. *
  1771. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  1772. */
  1773. function UnixTimeStamp($v)
  1774. {
  1775. if (!preg_match(
  1776. "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
  1777. ($v), $rr)) return false;
  1778. if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
  1779. // h-m-s-MM-DD-YY
  1780. if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  1781. return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
  1782. }
  1783. /**
  1784. * Also in ADORecordSet.
  1785. *
  1786. * Format database date based on user defined format.
  1787. *
  1788. * @param v is the character date in YYYY-MM-DD format, returned by database
  1789. * @param fmt is the format to apply to it, using date()
  1790. *
  1791. * @return a date formated as user desires
  1792. */
  1793. function UserDate($v,$fmt='Y-m-d',$gmt=false)
  1794. {
  1795. $tt = $this->UnixDate($v);
  1796. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  1797. if (($tt === false || $tt == -1) && $v != false) return $v;
  1798. else if ($tt == 0) return $this->emptyDate;
  1799. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  1800. }
  1801. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  1802. }
  1803. /**
  1804. *
  1805. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  1806. * @param fmt is the format to apply to it, using date()
  1807. *
  1808. * @return a timestamp formated as user desires
  1809. */
  1810. function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
  1811. {
  1812. # strlen(14) allows YYYYMMDDHHMMSS format
  1813. if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
  1814. $tt = $this->UnixTimeStamp($v);
  1815. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  1816. if (($tt === false || $tt == -1) && $v != false) return $v;
  1817. if ($tt == 0) return $this->emptyTimeStamp;
  1818. return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  1819. }
  1820. /**
  1821. * Quotes a string, without prefixing nor appending quotes.
  1822. */
  1823. function addq($s,$magic_quotes=false)
  1824. {
  1825. if (!$magic_quotes) {
  1826. if ($this->replaceQuote[0] == '\\'){
  1827. // only since php 4.0.5
  1828. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  1829. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  1830. }
  1831. return str_replace("'",$this->replaceQuote,$s);
  1832. }
  1833. // undo magic quotes for "
  1834. $s = str_replace('\\"','"',$s);
  1835. if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
  1836. return $s;
  1837. else {// change \' to '' for sybase/mssql
  1838. $s = str_replace('\\\\','\\',$s);
  1839. return str_replace("\\'",$this->replaceQuote,$s);
  1840. }
  1841. }
  1842. /**
  1843. * Correctly quotes a string so that all strings are escaped. We prefix and append
  1844. * to the string single-quotes.
  1845. * An example is $db->qstr("Don't bother",magic_quotes_runtime());
  1846. *
  1847. * @param s the string to quote
  1848. * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
  1849. * This undoes the stupidity of magic quotes for GPC.
  1850. *
  1851. * @return quoted string to be sent back to database
  1852. */
  1853. function qstr($s,$magic_quotes=false)
  1854. {
  1855. if (!$magic_quotes) {
  1856. if ($this->replaceQuote[0] == '\\'){
  1857. // only since php 4.0.5
  1858. $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  1859. //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  1860. }
  1861. return "'".str_replace("'",$this->replaceQuote,$s)."'";
  1862. }
  1863. // undo magic quotes for "
  1864. $s = str_replace('\\"','"',$s);
  1865. if ($this->replaceQuote == "\\'") // ' already quoted, no need to change anything
  1866. return "'$s'";
  1867. else {// change \' to '' for sybase/mssql
  1868. $s = str_replace('\\\\','\\',$s);
  1869. return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
  1870. }
  1871. }
  1872. /**
  1873. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  1874. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  1875. * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
  1876. *
  1877. * See readme.htm#ex8 for an example of usage.
  1878. *
  1879. * @param sql
  1880. * @param nrows is the number of rows per page to get
  1881. * @param page is the page number to get (1-based)
  1882. * @param [inputarr] array of bind variables
  1883. * @param [secs2cache] is a private parameter only used by jlim
  1884. * @return the recordset ($rs->databaseType == 'array')
  1885. *
  1886. * NOTE: phpLens uses a different algorithm and does not use PageExecute().
  1887. *
  1888. */
  1889. function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
  1890. {
  1891. global $ADODB_INCLUDED_LIB;
  1892. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  1893. if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  1894. else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  1895. return $rs;
  1896. }
  1897. /**
  1898. * Will select the supplied $page number from a recordset, given that it is paginated in pages of
  1899. * $nrows rows per page. It also saves two boolean values saying if the given page is the first
  1900. * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
  1901. *
  1902. * @param secs2cache seconds to cache data, set to 0 to force query
  1903. * @param sql
  1904. * @param nrows is the number of rows per page to get
  1905. * @param page is the page number to get (1-based)
  1906. * @param [inputarr] array of bind variables
  1907. * @return the recordset ($rs->databaseType == 'array')
  1908. */
  1909. function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
  1910. {
  1911. /*switch($this->dataProvider) {
  1912. case 'postgres':
  1913. case 'mysql':
  1914. break;
  1915. default: $secs2cache = 0; break;
  1916. }*/
  1917. $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
  1918. return $rs;
  1919. }
  1920. } // end class ADOConnection
  1921. //==============================================================================================
  1922. // CLASS ADOFetchObj
  1923. //==============================================================================================
  1924. /**
  1925. * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
  1926. */
  1927. class ADOFetchObj {
  1928. };
  1929. //==============================================================================================
  1930. // CLASS ADORecordSet_empty
  1931. //==============================================================================================
  1932. /**
  1933. * Lightweight recordset when there are no records to be returned
  1934. */
  1935. class ADORecordSet_empty
  1936. {
  1937. var $dataProvider = 'empty';
  1938. var $databaseType = false;
  1939. var $EOF = true;
  1940. var $_numOfRows = 0;
  1941. var $fields = false;
  1942. var $connection = false;
  1943. function RowCount() {return 0;}
  1944. function RecordCount() {return 0;}
  1945. function PO_RecordCount(){return 0;}
  1946. function Close(){return true;}
  1947. function FetchRow() {return false;}
  1948. function FieldCount(){ return 0;}
  1949. function Init() {}
  1950. }
  1951. //==============================================================================================
  1952. // DATE AND TIME FUNCTIONS
  1953. //==============================================================================================
  1954. include_once(ADODB_DIR.'/adodb-time.inc.php');
  1955. //==============================================================================================
  1956. // CLASS ADORecordSet
  1957. //==============================================================================================
  1958. if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
  1959. else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
  1960. /**
  1961. * RecordSet class that represents the dataset returned by the database.
  1962. * To keep memory overhead low, this class holds only the current row in memory.
  1963. * No prefetching of data is done, so the RecordCount() can return -1 ( which
  1964. * means recordcount not known).
  1965. */
  1966. class ADORecordSet extends ADODB_BASE_RS {
  1967. /*
  1968. * public variables
  1969. */
  1970. var $dataProvider = "native";
  1971. var $fields = false; /// holds the current row data
  1972. var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
  1973. /// in other words, we use a text area for editing.
  1974. var $canSeek = false; /// indicates that seek is supported
  1975. var $sql; /// sql text
  1976. var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
  1977. var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
  1978. var $emptyDate = '&nbsp;'; /// what to display when $time==0
  1979. var $debug = false;
  1980. var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
  1981. var $bind = false; /// used by Fields() to hold array - should be private?
  1982. var $fetchMode; /// default fetch mode
  1983. var $connection = false; /// the parent connection
  1984. /*
  1985. * private variables
  1986. */
  1987. var $_numOfRows = -1; /** number of rows, or -1 */
  1988. var $_numOfFields = -1; /** number of fields in recordset */
  1989. var $_queryID = -1; /** This variable keeps the result link identifier. */
  1990. var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
  1991. var $_closed = false; /** has recordset been closed */
  1992. var $_inited = false; /** Init() should only be called once */
  1993. var $_obj; /** Used by FetchObj */
  1994. var $_names; /** Used by FetchObj */
  1995. var $_currentPage = -1; /** Added by Iv�n Oliva to implement recordset pagination */
  1996. var $_atFirstPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
  1997. var $_atLastPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
  1998. var $_lastPageNo = -1;
  1999. var $_maxRecordCount = 0;
  2000. var $datetime = false;
  2001. /**
  2002. * Constructor
  2003. *
  2004. * @param queryID this is the queryID returned by ADOConnection->_query()
  2005. *
  2006. */
  2007. function ADORecordSet($queryID)
  2008. {
  2009. $this->_queryID = $queryID;
  2010. }
  2011. function Init()
  2012. {
  2013. if ($this->_inited) return;
  2014. $this->_inited = true;
  2015. if ($this->_queryID) @$this->_initrs();
  2016. else {
  2017. $this->_numOfRows = 0;
  2018. $this->_numOfFields = 0;
  2019. }
  2020. if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
  2021. $this->_currentRow = 0;
  2022. if ($this->EOF = ($this->_fetch() === false)) {
  2023. $this->_numOfRows = 0; // _numOfRows could be -1
  2024. }
  2025. } else {
  2026. $this->EOF = true;
  2027. }
  2028. }
  2029. /**
  2030. * Generate a SELECT tag string from a recordset, and return the string.
  2031. * If the recordset has 2 cols, we treat the 1st col as the containing
  2032. * the text to display to the user, and 2nd col as the return value. Default
  2033. * strings are compared with the FIRST column.
  2034. *
  2035. * @param name name of SELECT tag
  2036. * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
  2037. * @param [blank1stItem] true to leave the 1st item in list empty
  2038. * @param [multiple] true for listbox, false for popup
  2039. * @param [size] #rows to show for listbox. not used by popup
  2040. * @param [selectAttr] additional attributes to defined for SELECT tag.
  2041. * useful for holding javascript onChange='...' handlers.
  2042. & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
  2043. * column 0 (1st col) if this is true. This is not documented.
  2044. *
  2045. * @return HTML
  2046. *
  2047. * changes by glen.davies@cce.ac.nz to support multiple hilited items
  2048. */
  2049. function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
  2050. $size=0, $selectAttr='',$compareFields0=true)
  2051. {
  2052. global $ADODB_INCLUDED_LIB;
  2053. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  2054. return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
  2055. $size, $selectAttr,$compareFields0);
  2056. }
  2057. /**
  2058. * Generate a SELECT tag string from a recordset, and return the string.
  2059. * If the recordset has 2 cols, we treat the 1st col as the containing
  2060. * the text to display to the user, and 2nd col as the return value. Default
  2061. * strings are compared with the SECOND column.
  2062. *
  2063. */
  2064. function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
  2065. {
  2066. global $ADODB_INCLUDED_LIB;
  2067. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  2068. return _adodb_getmenu($this,$name,$defstr,$blank1stItem,$multiple,
  2069. $size, $selectAttr,false);
  2070. }
  2071. /**
  2072. * return recordset as a 2-dimensional array.
  2073. *
  2074. * @param [nRows] is the number of rows to return. -1 means every row.
  2075. *
  2076. * @return an array indexed by the rows (0-based) from the recordset
  2077. */
  2078. function &GetArray($nRows = -1)
  2079. {
  2080. global $ADODB_EXTENSION; if ($ADODB_EXTENSION) return adodb_getall($this,$nRows);
  2081. $results = array();
  2082. $cnt = 0;
  2083. while (!$this->EOF && $nRows != $cnt) {
  2084. $results[] = $this->fields;
  2085. $this->MoveNext();
  2086. $cnt++;
  2087. }
  2088. return $results;
  2089. }
  2090. function &GetAll($nRows = -1)
  2091. {
  2092. $arr =& $this->GetArray($nRows);
  2093. return $arr;
  2094. }
  2095. /*
  2096. * Some databases allow multiple recordsets to be returned. This function
  2097. * will return true if there is a next recordset, or false if no more.
  2098. */
  2099. function NextRecordSet()
  2100. {
  2101. return false;
  2102. }
  2103. /**
  2104. * return recordset as a 2-dimensional array.
  2105. * Helper function for ADOConnection->SelectLimit()
  2106. *
  2107. * @param offset is the row to start calculations from (1-based)
  2108. * @param [nrows] is the number of rows to return
  2109. *
  2110. * @return an array indexed by the rows (0-based) from the recordset
  2111. */
  2112. function &GetArrayLimit($nrows,$offset=-1)
  2113. {
  2114. if ($offset <= 0) {
  2115. $arr =& $this->GetArray($nrows);
  2116. return $arr;
  2117. }
  2118. $this->Move($offset);
  2119. $results = array();
  2120. $cnt = 0;
  2121. while (!$this->EOF && $nrows != $cnt) {
  2122. $results[$cnt++] = $this->fields;
  2123. $this->MoveNext();
  2124. }
  2125. return $results;
  2126. }
  2127. /**
  2128. * Synonym for GetArray() for compatibility with ADO.
  2129. *
  2130. * @param [nRows] is the number of rows to return. -1 means every row.
  2131. *
  2132. * @return an array indexed by the rows (0-based) from the recordset
  2133. */
  2134. function &GetRows($nRows = -1)
  2135. {
  2136. $arr =& $this->GetArray($nRows);
  2137. return $arr;
  2138. }
  2139. /**
  2140. * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
  2141. * The first column is treated as the key and is not included in the array.
  2142. * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
  2143. * $force_array == true.
  2144. *
  2145. * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
  2146. * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
  2147. * read the source.
  2148. *
  2149. * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
  2150. * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
  2151. *
  2152. * @return an associative array indexed by the first column of the array,
  2153. * or false if the data has less than 2 cols.
  2154. */
  2155. function &GetAssoc($force_array = false, $first2cols = false)
  2156. {
  2157. global $ADODB_EXTENSION;
  2158. $cols = $this->_numOfFields;
  2159. if ($cols < 2) {
  2160. return false;
  2161. }
  2162. $numIndex = isset($this->fields[0]);
  2163. $results = array();
  2164. if (!$first2cols && ($cols > 2 || $force_array)) {
  2165. if ($ADODB_EXTENSION) {
  2166. if ($numIndex) {
  2167. while (!$this->EOF) {
  2168. $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2169. adodb_movenext($this);
  2170. }
  2171. } else {
  2172. while (!$this->EOF) {
  2173. $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2174. adodb_movenext($this);
  2175. }
  2176. }
  2177. } else {
  2178. if ($numIndex) {
  2179. while (!$this->EOF) {
  2180. $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2181. $this->MoveNext();
  2182. }
  2183. } else {
  2184. while (!$this->EOF) {
  2185. $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2186. $this->MoveNext();
  2187. }
  2188. }
  2189. }
  2190. } else {
  2191. if ($ADODB_EXTENSION) {
  2192. // return scalar values
  2193. if ($numIndex) {
  2194. while (!$this->EOF) {
  2195. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2196. $results[trim(($this->fields[0]))] = $this->fields[1];
  2197. adodb_movenext($this);
  2198. }
  2199. } else {
  2200. while (!$this->EOF) {
  2201. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2202. $v1 = trim(reset($this->fields));
  2203. $v2 = ''.next($this->fields);
  2204. $results[$v1] = $v2;
  2205. adodb_movenext($this);
  2206. }
  2207. }
  2208. } else {
  2209. if ($numIndex) {
  2210. while (!$this->EOF) {
  2211. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2212. $results[trim(($this->fields[0]))] = $this->fields[1];
  2213. $this->MoveNext();
  2214. }
  2215. } else {
  2216. while (!$this->EOF) {
  2217. // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2218. $v1 = trim(reset($this->fields));
  2219. $v2 = ''.next($this->fields);
  2220. $results[$v1] = $v2;
  2221. $this->MoveNext();
  2222. }
  2223. }
  2224. }
  2225. }
  2226. return $results;
  2227. }
  2228. /**
  2229. *
  2230. * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2231. * @param fmt is the format to apply to it, using date()
  2232. *
  2233. * @return a timestamp formated as user desires
  2234. */
  2235. function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
  2236. {
  2237. if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
  2238. $tt = $this->UnixTimeStamp($v);
  2239. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2240. if (($tt === false || $tt == -1) && $v != false) return $v;
  2241. if ($tt === 0) return $this->emptyTimeStamp;
  2242. return adodb_date($fmt,$tt);
  2243. }
  2244. /**
  2245. * @param v is the character date in YYYY-MM-DD format, returned by database
  2246. * @param fmt is the format to apply to it, using date()
  2247. *
  2248. * @return a date formated as user desires
  2249. */
  2250. function UserDate($v,$fmt='Y-m-d')
  2251. {
  2252. $tt = $this->UnixDate($v);
  2253. // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2254. if (($tt === false || $tt == -1) && $v != false) return $v;
  2255. else if ($tt == 0) return $this->emptyDate;
  2256. else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2257. }
  2258. return adodb_date($fmt,$tt);
  2259. }
  2260. /**
  2261. * @param $v is a date string in YYYY-MM-DD format
  2262. *
  2263. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2264. */
  2265. function UnixDate($v)
  2266. {
  2267. if (is_numeric($v) && strlen($v) !== 8) return $v;
  2268. if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
  2269. ($v), $rr)) return false;
  2270. if ($rr[1] <= TIMESTAMP_FIRST_YEAR || $rr[1] > 10000) return 0;
  2271. // h-m-s-MM-DD-YY
  2272. return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2273. }
  2274. /**
  2275. * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  2276. *
  2277. * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2278. */
  2279. function UnixTimeStamp($v)
  2280. {
  2281. if (!preg_match(
  2282. "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
  2283. ($v), $rr)) return false;
  2284. if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
  2285. // h-m-s-MM-DD-YY
  2286. if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2287. return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
  2288. }
  2289. /**
  2290. * PEAR DB Compat - do not use internally
  2291. */
  2292. function Free()
  2293. {
  2294. return $this->Close();
  2295. }
  2296. /**
  2297. * PEAR DB compat, number of rows
  2298. */
  2299. function NumRows()
  2300. {
  2301. return $this->_numOfRows;
  2302. }
  2303. /**
  2304. * PEAR DB compat, number of cols
  2305. */
  2306. function NumCols()
  2307. {
  2308. return $this->_numOfFields;
  2309. }
  2310. /**
  2311. * Fetch a row, returning false if no more rows.
  2312. * This is PEAR DB compat mode.
  2313. *
  2314. * @return false or array containing the current record
  2315. */
  2316. function &FetchRow()
  2317. {
  2318. if ($this->EOF) return false;
  2319. $arr = $this->fields;
  2320. $this->_currentRow++;
  2321. if (!$this->_fetch()) $this->EOF = true;
  2322. return $arr;
  2323. }
  2324. /**
  2325. * Fetch a row, returning PEAR_Error if no more rows.
  2326. * This is PEAR DB compat mode.
  2327. *
  2328. * @return DB_OK or error object
  2329. */
  2330. function FetchInto(&$arr)
  2331. {
  2332. if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
  2333. $arr = $this->fields;
  2334. $this->MoveNext();
  2335. return 1; // DB_OK
  2336. }
  2337. /**
  2338. * Move to the first row in the recordset. Many databases do NOT support this.
  2339. *
  2340. * @return true or false
  2341. */
  2342. function MoveFirst()
  2343. {
  2344. if ($this->_currentRow == 0) return true;
  2345. return $this->Move(0);
  2346. }
  2347. /**
  2348. * Move to the last row in the recordset.
  2349. *
  2350. * @return true or false
  2351. */
  2352. function MoveLast()
  2353. {
  2354. if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
  2355. if ($this->EOF) return false;
  2356. while (!$this->EOF) {
  2357. $f = $this->fields;
  2358. $this->MoveNext();
  2359. }
  2360. $this->fields = $f;
  2361. $this->EOF = false;
  2362. return true;
  2363. }
  2364. /**
  2365. * Move to next record in the recordset.
  2366. *
  2367. * @return true if there still rows available, or false if there are no more rows (EOF).
  2368. */
  2369. function MoveNext()
  2370. {
  2371. if (!$this->EOF) {
  2372. $this->_currentRow++;
  2373. if ($this->_fetch()) return true;
  2374. }
  2375. $this->EOF = true;
  2376. /* -- tested error handling when scrolling cursor -- seems useless.
  2377. $conn = $this->connection;
  2378. if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
  2379. $fn = $conn->raiseErrorFn;
  2380. $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
  2381. }
  2382. */
  2383. return false;
  2384. }
  2385. /**
  2386. * Random access to a specific row in the recordset. Some databases do not support
  2387. * access to previous rows in the databases (no scrolling backwards).
  2388. *
  2389. * @param rowNumber is the row to move to (0-based)
  2390. *
  2391. * @return true if there still rows available, or false if there are no more rows (EOF).
  2392. */
  2393. function Move($rowNumber = 0)
  2394. {
  2395. $this->EOF = false;
  2396. if ($rowNumber == $this->_currentRow) return true;
  2397. if ($rowNumber >= $this->_numOfRows)
  2398. if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
  2399. if ($this->canSeek) {
  2400. if ($this->_seek($rowNumber)) {
  2401. $this->_currentRow = $rowNumber;
  2402. if ($this->_fetch()) {
  2403. return true;
  2404. }
  2405. } else {
  2406. $this->EOF = true;
  2407. return false;
  2408. }
  2409. } else {
  2410. if ($rowNumber < $this->_currentRow) return false;
  2411. global $ADODB_EXTENSION;
  2412. if ($ADODB_EXTENSION) {
  2413. while (!$this->EOF && $this->_currentRow < $rowNumber) {
  2414. adodb_movenext($this);
  2415. }
  2416. } else {
  2417. while (! $this->EOF && $this->_currentRow < $rowNumber) {
  2418. $this->_currentRow++;
  2419. if (!$this->_fetch()) $this->EOF = true;
  2420. }
  2421. }
  2422. return !($this->EOF);
  2423. }
  2424. $this->fields = false;
  2425. $this->EOF = true;
  2426. return false;
  2427. }
  2428. /**
  2429. * Get the value of a field in the current row by column name.
  2430. * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
  2431. *
  2432. * @param colname is the field to access
  2433. *
  2434. * @return the value of $colname column
  2435. */
  2436. function Fields($colname)
  2437. {
  2438. return $this->fields[$colname];
  2439. }
  2440. function GetAssocKeys($upper=true)
  2441. {
  2442. $this->bind = array();
  2443. for ($i=0; $i < $this->_numOfFields; $i++) {
  2444. $o =& $this->FetchField($i);
  2445. if ($upper === 2) $this->bind[$o->name] = $i;
  2446. else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
  2447. }
  2448. }
  2449. /**
  2450. * Use associative array to get fields array for databases that do not support
  2451. * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
  2452. *
  2453. * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
  2454. * before you execute your SQL statement, and access $rs->fields['col'] directly.
  2455. *
  2456. * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
  2457. */
  2458. function &GetRowAssoc($upper=1)
  2459. {
  2460. $record = array();
  2461. // if (!$this->fields) return $record;
  2462. if (!$this->bind) {
  2463. $this->GetAssocKeys($upper);
  2464. }
  2465. foreach($this->bind as $k => $v) {
  2466. $record[$k] = $this->fields[$v];
  2467. }
  2468. return $record;
  2469. }
  2470. /**
  2471. * Clean up recordset
  2472. *
  2473. * @return true or false
  2474. */
  2475. function Close()
  2476. {
  2477. // free connection object - this seems to globally free the object
  2478. // and not merely the reference, so don't do this...
  2479. // $this->connection = false;
  2480. if (!$this->_closed) {
  2481. $this->_closed = true;
  2482. return $this->_close();
  2483. } else
  2484. return true;
  2485. }
  2486. /**
  2487. * synonyms RecordCount and RowCount
  2488. *
  2489. * @return the number of rows or -1 if this is not supported
  2490. */
  2491. function RecordCount() {return $this->_numOfRows;}
  2492. /*
  2493. * If we are using PageExecute(), this will return the maximum possible rows
  2494. * that can be returned when paging a recordset.
  2495. */
  2496. function MaxRecordCount()
  2497. {
  2498. return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
  2499. }
  2500. /**
  2501. * synonyms RecordCount and RowCount
  2502. *
  2503. * @return the number of rows or -1 if this is not supported
  2504. */
  2505. function RowCount() {return $this->_numOfRows;}
  2506. /**
  2507. * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
  2508. *
  2509. * @return the number of records from a previous SELECT. All databases support this.
  2510. *
  2511. * But aware possible problems in multiuser environments. For better speed the table
  2512. * must be indexed by the condition. Heavy test this before deploying.
  2513. */
  2514. function PO_RecordCount($table="", $condition="") {
  2515. $lnumrows = $this->_numOfRows;
  2516. // the database doesn't support native recordcount, so we do a workaround
  2517. if ($lnumrows == -1 && $this->connection) {
  2518. IF ($table) {
  2519. if ($condition) $condition = " WHERE " . $condition;
  2520. $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
  2521. if ($resultrows) $lnumrows = reset($resultrows->fields);
  2522. }
  2523. }
  2524. return $lnumrows;
  2525. }
  2526. /**
  2527. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  2528. */
  2529. function CurrentRow() {return $this->_currentRow;}
  2530. /**
  2531. * synonym for CurrentRow -- for ADO compat
  2532. *
  2533. * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  2534. */
  2535. function AbsolutePosition() {return $this->_currentRow;}
  2536. /**
  2537. * @return the number of columns in the recordset. Some databases will set this to 0
  2538. * if no records are returned, others will return the number of columns in the query.
  2539. */
  2540. function FieldCount() {return $this->_numOfFields;}
  2541. /**
  2542. * Get the ADOFieldObject of a specific column.
  2543. *
  2544. * @param fieldoffset is the column position to access(0-based).
  2545. *
  2546. * @return the ADOFieldObject for that column, or false.
  2547. */
  2548. function &FetchField($fieldoffset)
  2549. {
  2550. // must be defined by child class
  2551. }
  2552. /**
  2553. * Get the ADOFieldObjects of all columns in an array.
  2554. *
  2555. */
  2556. function& FieldTypesArray()
  2557. {
  2558. $arr = array();
  2559. for ($i=0, $max=$this->_numOfFields; $i < $max; $i++)
  2560. $arr[] = $this->FetchField($i);
  2561. return $arr;
  2562. }
  2563. /**
  2564. * Return the fields array of the current row as an object for convenience.
  2565. * The default case is lowercase field names.
  2566. *
  2567. * @return the object with the properties set to the fields of the current row
  2568. */
  2569. function &FetchObj()
  2570. {
  2571. $o =& $this->FetchObject(false);
  2572. return $o;
  2573. }
  2574. /**
  2575. * Return the fields array of the current row as an object for convenience.
  2576. * The default case is uppercase.
  2577. *
  2578. * @param $isupper to set the object property names to uppercase
  2579. *
  2580. * @return the object with the properties set to the fields of the current row
  2581. */
  2582. function &FetchObject($isupper=true)
  2583. {
  2584. if (empty($this->_obj)) {
  2585. $this->_obj =& new ADOFetchObj();
  2586. $this->_names = array();
  2587. for ($i=0; $i <$this->_numOfFields; $i++) {
  2588. $f = $this->FetchField($i);
  2589. $this->_names[] = $f->name;
  2590. }
  2591. }
  2592. $i = 0;
  2593. $o = &$this->_obj;
  2594. for ($i=0; $i <$this->_numOfFields; $i++) {
  2595. $name = $this->_names[$i];
  2596. if ($isupper) $n = strtoupper($name);
  2597. else $n = $name;
  2598. $o->$n = $this->Fields($name);
  2599. }
  2600. return $o;
  2601. }
  2602. /**
  2603. * Return the fields array of the current row as an object for convenience.
  2604. * The default is lower-case field names.
  2605. *
  2606. * @return the object with the properties set to the fields of the current row,
  2607. * or false if EOF
  2608. *
  2609. * Fixed bug reported by tim@orotech.net
  2610. */
  2611. function &FetchNextObj()
  2612. {
  2613. $o = $this->FetchNextObject(false);
  2614. return $o;
  2615. }
  2616. /**
  2617. * Return the fields array of the current row as an object for convenience.
  2618. * The default is upper case field names.
  2619. *
  2620. * @param $isupper to set the object property names to uppercase
  2621. *
  2622. * @return the object with the properties set to the fields of the current row,
  2623. * or false if EOF
  2624. *
  2625. * Fixed bug reported by tim@orotech.net
  2626. */
  2627. function &FetchNextObject($isupper=true)
  2628. {
  2629. $o = false;
  2630. if ($this->_numOfRows != 0 && !$this->EOF) {
  2631. $o = $this->FetchObject($isupper);
  2632. $this->_currentRow++;
  2633. if ($this->_fetch()) return $o;
  2634. }
  2635. $this->EOF = true;
  2636. return $o;
  2637. }
  2638. /**
  2639. * Get the metatype of the column. This is used for formatting. This is because
  2640. * many databases use different names for the same type, so we transform the original
  2641. * type to our standardised version which uses 1 character codes:
  2642. *
  2643. * @param t is the type passed in. Normally is ADOFieldObject->type.
  2644. * @param len is the maximum length of that field. This is because we treat character
  2645. * fields bigger than a certain size as a 'B' (blob).
  2646. * @param fieldobj is the field object returned by the database driver. Can hold
  2647. * additional info (eg. primary_key for mysql).
  2648. *
  2649. * @return the general type of the data:
  2650. * C for character < 250 chars
  2651. * X for teXt (>= 250 chars)
  2652. * B for Binary
  2653. * N for numeric or floating point
  2654. * D for date
  2655. * T for timestamp
  2656. * L for logical/Boolean
  2657. * I for integer
  2658. * R for autoincrement counter/integer
  2659. *
  2660. *
  2661. */
  2662. function MetaType($t,$len=-1,$fieldobj=false)
  2663. {
  2664. if (is_object($t)) {
  2665. $fieldobj = $t;
  2666. $t = $fieldobj->type;
  2667. $len = $fieldobj->max_length;
  2668. }
  2669. // changed in 2.32 to hashing instead of switch stmt for speed...
  2670. static $typeMap = array(
  2671. 'VARCHAR' => 'C',
  2672. 'VARCHAR2' => 'C',
  2673. 'CHAR' => 'C',
  2674. 'C' => 'C',
  2675. 'STRING' => 'C',
  2676. 'NCHAR' => 'C',
  2677. 'NVARCHAR' => 'C',
  2678. 'VARYING' => 'C',
  2679. 'BPCHAR' => 'C',
  2680. 'CHARACTER' => 'C',
  2681. 'INTERVAL' => 'C', # Postgres
  2682. ##
  2683. 'LONGCHAR' => 'X',
  2684. 'TEXT' => 'X',
  2685. 'NTEXT' => 'X',
  2686. 'M' => 'X',
  2687. 'X' => 'X',
  2688. 'CLOB' => 'X',
  2689. 'NCLOB' => 'X',
  2690. 'LVARCHAR' => 'X',
  2691. ##
  2692. 'BLOB' => 'B',
  2693. 'IMAGE' => 'B',
  2694. 'BINARY' => 'B',
  2695. 'VARBINARY' => 'B',
  2696. 'LONGBINARY' => 'B',
  2697. 'B' => 'B',
  2698. ##
  2699. 'YEAR' => 'D', // mysql
  2700. 'DATE' => 'D',
  2701. 'D' => 'D',
  2702. ##
  2703. 'TIME' => 'T',
  2704. 'TIMESTAMP' => 'T',
  2705. 'DATETIME' => 'T',
  2706. 'TIMESTAMPTZ' => 'T',
  2707. 'T' => 'T',
  2708. ##
  2709. 'BOOL' => 'L',
  2710. 'BOOLEAN' => 'L',
  2711. 'BIT' => 'L',
  2712. 'L' => 'L',
  2713. ##
  2714. 'COUNTER' => 'R',
  2715. 'R' => 'R',
  2716. 'SERIAL' => 'R', // ifx
  2717. 'INT IDENTITY' => 'R',
  2718. ##
  2719. 'INT' => 'I',
  2720. 'INTEGER' => 'I',
  2721. 'INTEGER UNSIGNED' => 'I',
  2722. 'SHORT' => 'I',
  2723. 'TINYINT' => 'I',
  2724. 'SMALLINT' => 'I',
  2725. 'I' => 'I',
  2726. ##
  2727. 'LONG' => 'N', // interbase is numeric, oci8 is blob
  2728. 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
  2729. 'DECIMAL' => 'N',
  2730. 'DEC' => 'N',
  2731. 'REAL' => 'N',
  2732. 'DOUBLE' => 'N',
  2733. 'DOUBLE PRECISION' => 'N',
  2734. 'SMALLFLOAT' => 'N',
  2735. 'FLOAT' => 'N',
  2736. 'NUMBER' => 'N',
  2737. 'NUM' => 'N',
  2738. 'NUMERIC' => 'N',
  2739. 'MONEY' => 'N',
  2740. ## informix 9.2
  2741. 'SQLINT' => 'I',
  2742. 'SQLSERIAL' => 'I',
  2743. 'SQLSMINT' => 'I',
  2744. 'SQLSMFLOAT' => 'N',
  2745. 'SQLFLOAT' => 'N',
  2746. 'SQLMONEY' => 'N',
  2747. 'SQLDECIMAL' => 'N',
  2748. 'SQLDATE' => 'D',
  2749. 'SQLVCHAR' => 'C',
  2750. 'SQLCHAR' => 'C',
  2751. 'SQLDTIME' => 'T',
  2752. 'SQLINTERVAL' => 'N',
  2753. 'SQLBYTES' => 'B',
  2754. 'SQLTEXT' => 'X'
  2755. );
  2756. $tmap = false;
  2757. $t = strtoupper($t);
  2758. $tmap = @$typeMap[$t];
  2759. switch ($tmap) {
  2760. case 'C':
  2761. // is the char field is too long, return as text field...
  2762. if ($this->blobSize >= 0) {
  2763. if ($len > $this->blobSize) return 'X';
  2764. } else if ($len > 250) {
  2765. return 'X';
  2766. }
  2767. return 'C';
  2768. case 'I':
  2769. if (!empty($fieldobj->primary_key)) return 'R';
  2770. return 'I';
  2771. case false:
  2772. return 'N';
  2773. case 'B':
  2774. if (isset($fieldobj->binary))
  2775. return ($fieldobj->binary) ? 'B' : 'X';
  2776. return 'B';
  2777. case 'D':
  2778. if (!empty($this->datetime)) return 'T';
  2779. return 'D';
  2780. default:
  2781. if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
  2782. return $tmap;
  2783. }
  2784. }
  2785. function _close() {}
  2786. /**
  2787. * set/returns the current recordset page when paginating
  2788. */
  2789. function AbsolutePage($page=-1)
  2790. {
  2791. if ($page != -1) $this->_currentPage = $page;
  2792. return $this->_currentPage;
  2793. }
  2794. /**
  2795. * set/returns the status of the atFirstPage flag when paginating
  2796. */
  2797. function AtFirstPage($status=false)
  2798. {
  2799. if ($status != false) $this->_atFirstPage = $status;
  2800. return $this->_atFirstPage;
  2801. }
  2802. function LastPageNo($page = false)
  2803. {
  2804. if ($page != false) $this->_lastPageNo = $page;
  2805. return $this->_lastPageNo;
  2806. }
  2807. /**
  2808. * set/returns the status of the atLastPage flag when paginating
  2809. */
  2810. function AtLastPage($status=false)
  2811. {
  2812. if ($status != false) $this->_atLastPage = $status;
  2813. return $this->_atLastPage;
  2814. }
  2815. } // end class ADORecordSet
  2816. //==============================================================================================
  2817. // CLASS ADORecordSet_array
  2818. //==============================================================================================
  2819. /**
  2820. * This class encapsulates the concept of a recordset created in memory
  2821. * as an array. This is useful for the creation of cached recordsets.
  2822. *
  2823. * Note that the constructor is different from the standard ADORecordSet
  2824. */
  2825. class ADORecordSet_array extends ADORecordSet
  2826. {
  2827. var $databaseType = 'array';
  2828. var $_array; // holds the 2-dimensional data array
  2829. var $_types; // the array of types of each column (C B I L M)
  2830. var $_colnames; // names of each column in array
  2831. var $_skiprow1; // skip 1st row because it holds column names
  2832. var $_fieldarr; // holds array of field objects
  2833. var $canSeek = true;
  2834. var $affectedrows = false;
  2835. var $insertid = false;
  2836. var $sql = '';
  2837. var $compat = false;
  2838. /**
  2839. * Constructor
  2840. *
  2841. */
  2842. function ADORecordSet_array($fakeid=1)
  2843. {
  2844. global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
  2845. // fetch() on EOF does not delete $this->fields
  2846. $this->compat = !empty($ADODB_COMPAT_FETCH);
  2847. $this->ADORecordSet($fakeid); // fake queryID
  2848. $this->fetchMode = $ADODB_FETCH_MODE;
  2849. }
  2850. /**
  2851. * Setup the array.
  2852. *
  2853. * @param array is a 2-dimensional array holding the data.
  2854. * The first row should hold the column names
  2855. * unless paramter $colnames is used.
  2856. * @param typearr holds an array of types. These are the same types
  2857. * used in MetaTypes (C,B,L,I,N).
  2858. * @param [colnames] array of column names. If set, then the first row of
  2859. * $array should not hold the column names.
  2860. */
  2861. function InitArray($array,$typearr,$colnames=false)
  2862. {
  2863. $this->_array = $array;
  2864. $this->_types = $typearr;
  2865. if ($colnames) {
  2866. $this->_skiprow1 = false;
  2867. $this->_colnames = $colnames;
  2868. } else {
  2869. $this->_skiprow1 = true;
  2870. $this->_colnames = $array[0];
  2871. }
  2872. $this->Init();
  2873. }
  2874. /**
  2875. * Setup the Array and datatype file objects
  2876. *
  2877. * @param array is a 2-dimensional array holding the data.
  2878. * The first row should hold the column names
  2879. * unless paramter $colnames is used.
  2880. * @param fieldarr holds an array of ADOFieldObject's.
  2881. */
  2882. function InitArrayFields(&$array,&$fieldarr)
  2883. {
  2884. $this->_array =& $array;
  2885. $this->_skiprow1= false;
  2886. if ($fieldarr) {
  2887. $this->_fieldobjects =& $fieldarr;
  2888. }
  2889. $this->Init();
  2890. }
  2891. function &GetArray($nRows=-1)
  2892. {
  2893. if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
  2894. return $this->_array;
  2895. } else {
  2896. $arr =& ADORecordSet::GetArray($nRows);
  2897. return $arr;
  2898. }
  2899. }
  2900. function _initrs()
  2901. {
  2902. $this->_numOfRows = sizeof($this->_array);
  2903. if ($this->_skiprow1) $this->_numOfRows -= 1;
  2904. $this->_numOfFields =(isset($this->_fieldobjects)) ?
  2905. sizeof($this->_fieldobjects):sizeof($this->_types);
  2906. }
  2907. /* Use associative array to get fields array */
  2908. function Fields($colname)
  2909. {
  2910. if ($this->fetchMode & ADODB_FETCH_ASSOC) {
  2911. if (!isset($this->fields[$colname])) $colname = strtolower($colname);
  2912. return $this->fields[$colname];
  2913. }
  2914. if (!$this->bind) {
  2915. $this->bind = array();
  2916. for ($i=0; $i < $this->_numOfFields; $i++) {
  2917. $o = $this->FetchField($i);
  2918. $this->bind[strtoupper($o->name)] = $i;
  2919. }
  2920. }
  2921. return $this->fields[$this->bind[strtoupper($colname)]];
  2922. }
  2923. function &FetchField($fieldOffset = -1)
  2924. {
  2925. if (isset($this->_fieldobjects)) {
  2926. return $this->_fieldobjects[$fieldOffset];
  2927. }
  2928. $o = new ADOFieldObject();
  2929. $o->name = $this->_colnames[$fieldOffset];
  2930. $o->type = $this->_types[$fieldOffset];
  2931. $o->max_length = -1; // length not known
  2932. return $o;
  2933. }
  2934. function _seek($row)
  2935. {
  2936. if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
  2937. $this->_currentRow = $row;
  2938. if ($this->_skiprow1) $row += 1;
  2939. $this->fields = $this->_array[$row];
  2940. return true;
  2941. }
  2942. return false;
  2943. }
  2944. function MoveNext()
  2945. {
  2946. if (!$this->EOF) {
  2947. $this->_currentRow++;
  2948. $pos = $this->_currentRow;
  2949. if ($this->_numOfRows <= $pos) {
  2950. if (!$this->compat) $this->fields = false;
  2951. } else {
  2952. if ($this->_skiprow1) $pos += 1;
  2953. $this->fields = $this->_array[$pos];
  2954. return true;
  2955. }
  2956. $this->EOF = true;
  2957. }
  2958. return false;
  2959. }
  2960. function _fetch()
  2961. {
  2962. $pos = $this->_currentRow;
  2963. if ($this->_numOfRows <= $pos) {
  2964. if (!$this->compat) $this->fields = false;
  2965. return false;
  2966. }
  2967. if ($this->_skiprow1) $pos += 1;
  2968. $this->fields = $this->_array[$pos];
  2969. return true;
  2970. }
  2971. function _close()
  2972. {
  2973. return true;
  2974. }
  2975. } // ADORecordSet_array
  2976. //==============================================================================================
  2977. // HELPER FUNCTIONS
  2978. //==============================================================================================
  2979. /**
  2980. * Synonym for ADOLoadCode. Private function. Do not use.
  2981. *
  2982. * @deprecated
  2983. */
  2984. function ADOLoadDB($dbType)
  2985. {
  2986. return ADOLoadCode($dbType);
  2987. }
  2988. /**
  2989. * Load the code for a specific database driver. Private function. Do not use.
  2990. */
  2991. function ADOLoadCode($dbType)
  2992. {
  2993. global $ADODB_LASTDB;
  2994. if (!$dbType) return false;
  2995. $db = strtolower($dbType);
  2996. switch ($db) {
  2997. case 'ifx':
  2998. case 'maxsql': $db = 'mysqlt'; break;
  2999. case 'postgres':
  3000. case 'pgsql': $db = 'postgres7'; break;
  3001. }
  3002. @include_once(ADODB_DIR."/drivers/adodb-".$db.".inc.php");
  3003. $ADODB_LASTDB = $db;
  3004. $ok = class_exists("ADODB_" . $db);
  3005. if ($ok) return $db;
  3006. print_r(get_declared_classes());
  3007. $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
  3008. if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
  3009. else ADOConnection::outp("Syntax error in file: $file");
  3010. return false;
  3011. }
  3012. /**
  3013. * synonym for ADONewConnection for people like me who cannot remember the correct name
  3014. */
  3015. function &NewADOConnection($db='')
  3016. {
  3017. $tmp =& ADONewConnection($db);
  3018. return $tmp;
  3019. }
  3020. /**
  3021. * Instantiate a new Connection class for a specific database driver.
  3022. *
  3023. * @param [db] is the database Connection object to create. If undefined,
  3024. * use the last database driver that was loaded by ADOLoadCode().
  3025. *
  3026. * @return the freshly created instance of the Connection class.
  3027. */
  3028. function &ADONewConnection($db='')
  3029. {
  3030. GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
  3031. if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  3032. $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
  3033. if (strpos($db,'://')) {
  3034. $origdsn = $db;
  3035. $dsna = @parse_url($db);
  3036. if (!$dsna) {
  3037. // special handling of oracle, which might not have host
  3038. $db = str_replace('@/','@adodb-fakehost/',$db);
  3039. $dsna = parse_url($db);
  3040. if (!$dsna) return false;
  3041. $dsna['host'] = '';
  3042. }
  3043. $db = @$dsna['scheme'];
  3044. if (!$db) return false;
  3045. $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3046. $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
  3047. $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
  3048. $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : '';
  3049. if (isset($dsna['query'])) {
  3050. $opt1 = explode('&',$dsna['query']);
  3051. foreach($opt1 as $k => $v) {
  3052. $arr = explode('=',$v);
  3053. $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
  3054. }
  3055. } else $opt = array();
  3056. }
  3057. /*
  3058. * phptype: Database backend used in PHP (mysql, odbc etc.)
  3059. * dbsyntax: Database used with regards to SQL syntax etc.
  3060. * protocol: Communication protocol to use (tcp, unix etc.)
  3061. * hostspec: Host specification (hostname[:port])
  3062. * database: Database to use on the DBMS server
  3063. * username: User name for login
  3064. * password: Password for login
  3065. */
  3066. if (!empty($ADODB_NEWCONNECTION)) {
  3067. $obj = $ADODB_NEWCONNECTION($db);
  3068. } else {
  3069. if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
  3070. if (empty($db)) $db = $ADODB_LASTDB;
  3071. if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
  3072. if (!$db) {
  3073. if (isset($origdsn)) $db = $origdsn;
  3074. if ($errorfn) {
  3075. // raise an error
  3076. $ignore = false;
  3077. $errorfn('ADONewConnection', 'ADONewConnection', -998,
  3078. "could not load the database driver for '$db'",
  3079. $db,false,$ignore);
  3080. } else
  3081. ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
  3082. return false;
  3083. }
  3084. $cls = 'ADODB_'.$db;
  3085. if (!class_exists($cls)) {
  3086. adodb_backtrace();
  3087. return false;
  3088. }
  3089. $obj =& new $cls();
  3090. }
  3091. # constructor should not fail
  3092. if ($obj) {
  3093. if ($errorfn) $obj->raiseErrorFn = $errorfn;
  3094. if (isset($dsna)) {
  3095. foreach($opt as $k => $v) {
  3096. switch(strtolower($k)) {
  3097. case 'persist':
  3098. case 'persistent': $persist = $v; break;
  3099. case 'debug': $obj->debug = (integer) $v; break;
  3100. #ibase
  3101. case 'dialect': $obj->dialect = (integer) $v; break;
  3102. case 'charset': $obj->charset = $v; break;
  3103. case 'buffers': $obj->buffers = $v; break;
  3104. case 'fetchmode': $obj->SetFetchMode($v); break;
  3105. #ado
  3106. case 'charpage': $obj->charPage = $v; break;
  3107. #mysql, mysqli
  3108. case 'clientflags': $obj->clientFlags = $v; break;
  3109. #mysqli
  3110. case 'port': $obj->port = $v; break;
  3111. case 'socket': $obj->socket = $v; break;
  3112. }
  3113. }
  3114. if (empty($persist))
  3115. $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3116. else
  3117. $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3118. if (!$ok) return false;
  3119. }
  3120. }
  3121. return $obj;
  3122. }
  3123. // $perf == true means called by NewPerfMonitor()
  3124. function _adodb_getdriver($provider,$drivername,$perf=false)
  3125. {
  3126. if ($provider !== 'native' && $provider != 'odbc' && $provider != 'ado')
  3127. $drivername = $provider;
  3128. else {
  3129. if (substr($drivername,0,5) == 'odbc_') $drivername = substr($drivername,5);
  3130. else if (substr($drivername,0,4) == 'ado_') $drivername = substr($drivername,4);
  3131. else
  3132. switch($drivername) {
  3133. case 'oracle': $drivername = 'oci8';break;
  3134. //case 'sybase': $drivername = 'mssql';break;
  3135. case 'access':
  3136. if ($perf) $drivername = '';
  3137. break;
  3138. case 'db2':
  3139. break;
  3140. default:
  3141. $drivername = 'generic';
  3142. break;
  3143. }
  3144. }
  3145. return $drivername;
  3146. }
  3147. function &NewPerfMonitor(&$conn)
  3148. {
  3149. $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
  3150. if (!$drivername || $drivername == 'generic') return false;
  3151. include_once(ADODB_DIR.'/adodb-perf.inc.php');
  3152. @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
  3153. $class = "Perf_$drivername";
  3154. if (!class_exists($class)) return false;
  3155. $perf =& new $class($conn);
  3156. return $perf;
  3157. }
  3158. function &NewDataDictionary(&$conn)
  3159. {
  3160. $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
  3161. include_once(ADODB_DIR.'/adodb-lib.inc.php');
  3162. include_once(ADODB_DIR.'/adodb-datadict.inc.php');
  3163. $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
  3164. if (!file_exists($path)) {
  3165. ADOConnection::outp("Database driver '$path' not available");
  3166. return false;
  3167. }
  3168. include_once($path);
  3169. $class = "ADODB2_$drivername";
  3170. $dict =& new $class();
  3171. $dict->dataProvider = $conn->dataProvider;
  3172. $dict->connection = &$conn;
  3173. $dict->upperName = strtoupper($drivername);
  3174. $dict->quote = $conn->nameQuote;
  3175. if (!empty($conn->_connectionID))
  3176. $dict->serverInfo = $conn->ServerInfo();
  3177. return $dict;
  3178. }
  3179. /*
  3180. Perform a print_r, with pre tags for better formatting.
  3181. */
  3182. function adodb_pr($var)
  3183. {
  3184. if (isset($_SERVER['HTTP_USER_AGENT'])) {
  3185. echo " <pre>\n";print_r($var);echo "</pre>\n";
  3186. } else
  3187. print_r($var);
  3188. }
  3189. /*
  3190. Perform a stack-crawl and pretty print it.
  3191. @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
  3192. @param levels Number of levels to display
  3193. */
  3194. function adodb_backtrace($printOrArr=true,$levels=9999)
  3195. {
  3196. global $ADODB_INCLUDED_LIB;
  3197. if (empty($ADODB_INCLUDED_LIB)) include_once(ADODB_DIR.'/adodb-lib.inc.php');
  3198. return _adodb_backtrace($printOrArr,$levels);
  3199. }
  3200. } // defined
  3201. ?>