1<?php
2/*
3  @version   v5.20.20  01-Feb-2021
4  @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
5  @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
6  Released under both BSD license and Lesser GPL library license.
7  Whenever there is any discrepancy between the two licenses,
8  the BSD license will take precedence. See License.txt.
9  Set tabs to 4 for best viewing.
10  Latest version is available at http://adodb.org/
11*/
12// Code contributed by "stefan bogdan" <sbogdan#rsb.ro>
13
14// security - hide paths
15if (!defined('ADODB_DIR')) die();
16
17define("_ADODB_ODBTP_LAYER", 2 );
18
19class ADODB_odbtp extends ADOConnection{
20	var $databaseType = "odbtp";
21	var $dataProvider = "odbtp";
22	var $fmtDate = "'Y-m-d'";
23	var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
24	var $replaceQuote = "''"; // string to use to replace quotes
25	var $odbc_driver = 0;
26	var $hasAffectedRows = true;
27	var $hasInsertID = false;
28	var $hasGenID = true;
29	var $hasMoveFirst = true;
30
31	var $_genSeqSQL = "create table %s (seq_name char(30) not null unique , seq_value integer not null)";
32	var $_dropSeqSQL = "delete from adodb_seq where seq_name = '%s'";
33	var $_bindInputArray = false;
34	var $_useUnicodeSQL = false;
35	var $_canPrepareSP = false;
36	var $_dontPoolDBC = true;
37
38	function __construct()
39	{
40	}
41
42	function ServerInfo()
43	{
44		return array('description' => @odbtp_get_attr( ODB_ATTR_DBMSNAME, $this->_connectionID),
45		             'version' => @odbtp_get_attr( ODB_ATTR_DBMSVER, $this->_connectionID));
46	}
47
48	function ErrorMsg()
49	{
50		if ($this->_errorMsg !== false) return $this->_errorMsg;
51		if (empty($this->_connectionID)) return @odbtp_last_error();
52		return @odbtp_last_error($this->_connectionID);
53	}
54
55	function ErrorNo()
56	{
57		if ($this->_errorCode !== false) return $this->_errorCode;
58		if (empty($this->_connectionID)) return @odbtp_last_error_state();
59			return @odbtp_last_error_state($this->_connectionID);
60	}
61/*
62	function DBDate($d,$isfld=false)
63	{
64		if (empty($d) && $d !== 0) return 'null';
65		if ($isfld) return "convert(date, $d, 120)";
66
67		if (is_string($d)) $d = ADORecordSet::UnixDate($d);
68		$d = adodb_date($this->fmtDate,$d);
69		return "convert(date, $d, 120)";
70	}
71
72	function DBTimeStamp($d,$isfld=false)
73	{
74		if (empty($d) && $d !== 0) return 'null';
75		if ($isfld) return "convert(datetime, $d, 120)";
76
77		if (is_string($d)) $d = ADORecordSet::UnixDate($d);
78		$d = adodb_date($this->fmtDate,$d);
79		return "convert(datetime, $d, 120)";
80	}
81*/
82
83	function _insertid()
84	{
85	// SCOPE_IDENTITY()
86	// Returns the last IDENTITY value inserted into an IDENTITY column in
87	// the same scope. A scope is a module -- a stored procedure, trigger,
88	// function, or batch. Thus, two statements are in the same scope if
89	// they are in the same stored procedure, function, or batch.
90			return $this->GetOne($this->identitySQL);
91	}
92
93	function _affectedrows()
94	{
95		if ($this->_queryID) {
96			return @odbtp_affected_rows ($this->_queryID);
97	   } else
98		return 0;
99	}
100
101	function CreateSequence($seqname='adodbseq',$start=1)
102	{
103		//verify existence
104		$num = $this->GetOne("select seq_value from adodb_seq");
105		$seqtab='adodb_seq';
106		if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {
107			$path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID );
108			//if using vfp dbc file
109			if( !strcasecmp(strrchr($path, '.'), '.dbc') )
110                $path = substr($path,0,strrpos($path,'\/'));
111           	$seqtab = $path . '/' . $seqtab;
112        }
113		if($num == false) {
114			if (empty($this->_genSeqSQL)) return false;
115			$ok = $this->Execute(sprintf($this->_genSeqSQL ,$seqtab));
116		}
117		$num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seqname'");
118		if ($num) {
119			return false;
120		}
121		$start -= 1;
122		return $this->Execute("insert into adodb_seq values('$seqname',$start)");
123	}
124
125	function DropSequence($seqname = 'adodbseq')
126	{
127		if (empty($this->_dropSeqSQL)) return false;
128		return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
129	}
130
131	function GenID($seq='adodbseq',$start=1)
132	{
133		$seqtab='adodb_seq';
134		if( $this->odbc_driver == ODB_DRIVER_FOXPRO) {
135			$path = @odbtp_get_attr( ODB_ATTR_DATABASENAME, $this->_connectionID );
136			//if using vfp dbc file
137			if( !strcasecmp(strrchr($path, '.'), '.dbc') )
138                $path = substr($path,0,strrpos($path,'\/'));
139           	$seqtab = $path . '/' . $seqtab;
140        }
141		$MAXLOOPS = 100;
142		while (--$MAXLOOPS>=0) {
143			$num = $this->GetOne("select seq_value from adodb_seq where seq_name='$seq'");
144			if ($num === false) {
145				//verify if abodb_seq table exist
146				$ok = $this->GetOne("select seq_value from adodb_seq ");
147				if(!$ok) {
148					//creating the sequence table adodb_seq
149					$this->Execute(sprintf($this->_genSeqSQL ,$seqtab));
150				}
151				$start -= 1;
152				$num = '0';
153				$ok = $this->Execute("insert into adodb_seq values('$seq',$start)");
154				if (!$ok) return false;
155			}
156			$ok = $this->Execute("update adodb_seq set seq_value=seq_value+1 where seq_name='$seq'");
157			if($ok) {
158				$num += 1;
159				$this->genID = $num;
160				return $num;
161			}
162		}
163	if ($fn = $this->raiseErrorFn) {
164		$fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
165	}
166		return false;
167	}
168
169	//example for $UserOrDSN
170	//for visual fox : DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBF;SOURCEDB=c:\YourDbfFileDir;EXCLUSIVE=NO;
171	//for visual fox dbc: DRIVER={Microsoft Visual FoxPro Driver};SOURCETYPE=DBC;SOURCEDB=c:\YourDbcFileDir\mydb.dbc;EXCLUSIVE=NO;
172	//for access : DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\path_to_access_db\base_test.mdb;UID=root;PWD=;
173	//for mssql : DRIVER={SQL Server};SERVER=myserver;UID=myuid;PWD=mypwd;DATABASE=OdbtpTest;
174	//if uid & pwd can be separate
175    function _connect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
176	{
177		if ($argPassword && stripos($UserOrDSN,'DRIVER=') !== false) {
178			$this->_connectionID = odbtp_connect($HostOrInterface,$UserOrDSN.';PWD='.$argPassword);
179		} else
180			$this->_connectionID = odbtp_connect($HostOrInterface,$UserOrDSN,$argPassword,$argDatabase);
181		if ($this->_connectionID === false) {
182			$this->_errorMsg = $this->ErrorMsg() ;
183			return false;
184		}
185
186		odbtp_convert_datetime($this->_connectionID,true);
187
188		if ($this->_dontPoolDBC) {
189			if (function_exists('odbtp_dont_pool_dbc'))
190				@odbtp_dont_pool_dbc($this->_connectionID);
191		}
192		else {
193			$this->_dontPoolDBC = true;
194		}
195		$this->odbc_driver = @odbtp_get_attr(ODB_ATTR_DRIVER, $this->_connectionID);
196		$dbms = strtolower(@odbtp_get_attr(ODB_ATTR_DBMSNAME, $this->_connectionID));
197		$this->odbc_name = $dbms;
198
199		// Account for inconsistent DBMS names
200		if( $this->odbc_driver == ODB_DRIVER_ORACLE )
201			$dbms = 'oracle';
202		else if( $this->odbc_driver == ODB_DRIVER_SYBASE )
203			$dbms = 'sybase';
204
205		// Set DBMS specific attributes
206		switch( $dbms ) {
207			case 'microsoft sql server':
208				$this->databaseType = 'odbtp_mssql';
209				$this->fmtDate = "'Y-m-d'";
210				$this->fmtTimeStamp = "'Y-m-d h:i:sA'";
211				$this->sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
212				$this->sysTimeStamp = 'GetDate()';
213				$this->ansiOuter = true;
214				$this->leftOuter = '*=';
215				$this->rightOuter = '=*';
216                $this->hasTop = 'top';
217				$this->hasInsertID = true;
218				$this->hasTransactions = true;
219				$this->_bindInputArray = true;
220				$this->_canSelectDb = true;
221				$this->substr = "substring";
222				$this->length = 'len';
223				$this->identitySQL = 'select SCOPE_IDENTITY()';
224				$this->metaDatabasesSQL = "select name from master..sysdatabases where name <> 'master'";
225				$this->_canPrepareSP = true;
226				break;
227			case 'access':
228				$this->databaseType = 'odbtp_access';
229				$this->fmtDate = "#Y-m-d#";
230				$this->fmtTimeStamp = "#Y-m-d h:i:sA#";
231				$this->sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
232				$this->sysTimeStamp = 'NOW';
233                $this->hasTop = 'top';
234				$this->hasTransactions = false;
235				$this->_canPrepareSP = true;  // For MS Access only.
236				break;
237			case 'visual foxpro':
238				$this->databaseType = 'odbtp_vfp';
239				$this->fmtDate = "{^Y-m-d}";
240				$this->fmtTimeStamp = "{^Y-m-d, h:i:sA}";
241				$this->sysDate = 'date()';
242				$this->sysTimeStamp = 'datetime()';
243				$this->ansiOuter = true;
244                $this->hasTop = 'top';
245				$this->hasTransactions = false;
246				$this->replaceQuote = "'+chr(39)+'";
247				$this->true = '.T.';
248				$this->false = '.F.';
249
250				break;
251			case 'oracle':
252				$this->databaseType = 'odbtp_oci8';
253				$this->fmtDate = "'Y-m-d 00:00:00'";
254				$this->fmtTimeStamp = "'Y-m-d h:i:sA'";
255				$this->sysDate = 'TRUNC(SYSDATE)';
256				$this->sysTimeStamp = 'SYSDATE';
257				$this->hasTransactions = true;
258				$this->_bindInputArray = true;
259				$this->concat_operator = '||';
260				break;
261			case 'sybase':
262				$this->databaseType = 'odbtp_sybase';
263				$this->fmtDate = "'Y-m-d'";
264				$this->fmtTimeStamp = "'Y-m-d H:i:s'";
265				$this->sysDate = 'GetDate()';
266				$this->sysTimeStamp = 'GetDate()';
267				$this->leftOuter = '*=';
268				$this->rightOuter = '=*';
269				$this->hasInsertID = true;
270				$this->hasTransactions = true;
271				$this->identitySQL = 'select SCOPE_IDENTITY()';
272				break;
273			default:
274				$this->databaseType = 'odbtp';
275				if( @odbtp_get_attr(ODB_ATTR_TXNCAPABLE, $this->_connectionID) )
276					$this->hasTransactions = true;
277				else
278					$this->hasTransactions = false;
279		}
280        @odbtp_set_attr(ODB_ATTR_FULLCOLINFO, TRUE, $this->_connectionID );
281
282		if ($this->_useUnicodeSQL )
283			@odbtp_set_attr(ODB_ATTR_UNICODESQL, TRUE, $this->_connectionID);
284
285        return true;
286	}
287
288	function _pconnect($HostOrInterface, $UserOrDSN='', $argPassword='', $argDatabase='')
289	{
290		$this->_dontPoolDBC = false;
291  		return $this->_connect($HostOrInterface, $UserOrDSN, $argPassword, $argDatabase);
292	}
293
294	function SelectDB($dbName)
295	{
296		if (!@odbtp_select_db($dbName, $this->_connectionID)) {
297			return false;
298		}
299		$this->database = $dbName;
300		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
301		return true;
302	}
303
304	function MetaTables($ttype='',$showSchema=false,$mask=false)
305	{
306	global $ADODB_FETCH_MODE;
307
308		$savem = $ADODB_FETCH_MODE;
309		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
310		if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false);
311
312		$arr = $this->GetArray("||SQLTables||||$ttype");
313
314		if (isset($savefm)) $this->SetFetchMode($savefm);
315		$ADODB_FETCH_MODE = $savem;
316
317		$arr2 = array();
318		for ($i=0; $i < sizeof($arr); $i++) {
319			if ($arr[$i][3] == 'SYSTEM TABLE' )	continue;
320			if ($arr[$i][2])
321				$arr2[] = $showSchema && $arr[$i][1]? $arr[$i][1].'.'.$arr[$i][2] : $arr[$i][2];
322		}
323		return $arr2;
324	}
325
326	function MetaColumns($table,$upper=true)
327	{
328	global $ADODB_FETCH_MODE;
329
330		$schema = false;
331		$this->_findschema($table,$schema);
332		if ($upper) $table = strtoupper($table);
333
334		$savem = $ADODB_FETCH_MODE;
335		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
336		if ($this->fetchMode !== false) $savefm = $this->SetFetchMode(false);
337
338		$rs = $this->Execute( "||SQLColumns||$schema|$table" );
339
340		if (isset($savefm)) $this->SetFetchMode($savefm);
341		$ADODB_FETCH_MODE = $savem;
342
343		if (!$rs || $rs->EOF) {
344			$false = false;
345			return $false;
346		}
347		$retarr = array();
348		while (!$rs->EOF) {
349			//print_r($rs->fields);
350			if (strtoupper($rs->fields[2]) == $table) {
351				$fld = new ADOFieldObject();
352				$fld->name = $rs->fields[3];
353				$fld->type = $rs->fields[5];
354				$fld->max_length = $rs->fields[6];
355    			$fld->not_null = !empty($rs->fields[9]);
356 				$fld->scale = $rs->fields[7];
357				if (isset($rs->fields[12])) // vfp does not have field 12
358	 				if (!is_null($rs->fields[12])) {
359	 					$fld->has_default = true;
360	 					$fld->default_value = $rs->fields[12];
361					}
362				$retarr[strtoupper($fld->name)] = $fld;
363			} else if (!empty($retarr))
364				break;
365			$rs->MoveNext();
366		}
367		$rs->Close();
368
369		return $retarr;
370	}
371
372	function MetaPrimaryKeys($table, $owner='')
373	{
374	global $ADODB_FETCH_MODE;
375
376		$savem = $ADODB_FETCH_MODE;
377		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
378		$arr = $this->GetArray("||SQLPrimaryKeys||$owner|$table");
379		$ADODB_FETCH_MODE = $savem;
380
381		//print_r($arr);
382		$arr2 = array();
383		for ($i=0; $i < sizeof($arr); $i++) {
384			if ($arr[$i][3]) $arr2[] = $arr[$i][3];
385		}
386		return $arr2;
387	}
388
389	function MetaForeignKeys($table, $owner='', $upper=false)
390	{
391	global $ADODB_FETCH_MODE;
392
393		$savem = $ADODB_FETCH_MODE;
394		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
395		$constraints = $this->GetArray("||SQLForeignKeys|||||$owner|$table");
396		$ADODB_FETCH_MODE = $savem;
397
398		$arr = false;
399		foreach($constraints as $constr) {
400			//print_r($constr);
401			$arr[$constr[11]][$constr[2]][] = $constr[7].'='.$constr[3];
402		}
403		if (!$arr) {
404			$false = false;
405			return $false;
406		}
407
408		$arr2 = array();
409
410		foreach($arr as $k => $v) {
411			foreach($v as $a => $b) {
412				if ($upper) $a = strtoupper($a);
413				$arr2[$a] = $b;
414			}
415		}
416		return $arr2;
417	}
418
419	function BeginTrans()
420	{
421		if (!$this->hasTransactions) return false;
422		if ($this->transOff) return true;
423		$this->transCnt += 1;
424		$this->autoCommit = false;
425		if (defined('ODB_TXN_DEFAULT'))
426			$txn = ODB_TXN_DEFAULT;
427		else
428			$txn = ODB_TXN_READUNCOMMITTED;
429		$rs = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS,$txn,$this->_connectionID);
430		if(!$rs) return false;
431		return true;
432	}
433
434	function CommitTrans($ok=true)
435	{
436		if ($this->transOff) return true;
437		if (!$ok) return $this->RollbackTrans();
438		if ($this->transCnt) $this->transCnt -= 1;
439		$this->autoCommit = true;
440		if( ($ret = @odbtp_commit($this->_connectionID)) )
441			$ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off
442		return $ret;
443	}
444
445	function RollbackTrans()
446	{
447		if ($this->transOff) return true;
448		if ($this->transCnt) $this->transCnt -= 1;
449		$this->autoCommit = true;
450		if( ($ret = @odbtp_rollback($this->_connectionID)) )
451			$ret = @odbtp_set_attr(ODB_ATTR_TRANSACTIONS, ODB_TXN_NONE, $this->_connectionID);//set transaction off
452		return $ret;
453	}
454
455	function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
456	{
457		// TOP requires ORDER BY for Visual FoxPro
458		if( $this->odbc_driver == ODB_DRIVER_FOXPRO ) {
459			if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
460		}
461		$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
462		return $ret;
463	}
464
465	function Prepare($sql)
466	{
467		if (! $this->_bindInputArray) return $sql; // no binding
468
469        $this->_errorMsg = false;
470		$this->_errorCode = false;
471
472		$stmt = @odbtp_prepare($sql,$this->_connectionID);
473		if (!$stmt) {
474		//	print "Prepare Error for ($sql) ".$this->ErrorMsg()."<br>";
475			return $sql;
476		}
477		return array($sql,$stmt,false);
478	}
479
480	function PrepareSP($sql, $param = true)
481	{
482		if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures
483
484        $this->_errorMsg = false;
485		$this->_errorCode = false;
486
487		$stmt = @odbtp_prepare_proc($sql,$this->_connectionID);
488		if (!$stmt) return false;
489		return array($sql,$stmt);
490	}
491
492	/*
493	Usage:
494		$stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
495
496		# note that the parameter does not have @ in front!
497		$db->Parameter($stmt,$id,'myid');
498		$db->Parameter($stmt,$group,'group',false,64);
499		$db->Parameter($stmt,$group,'photo',false,100000,ODB_BINARY);
500		$db->Execute($stmt);
501
502		@param $stmt Statement returned by Prepare() or PrepareSP().
503		@param $var PHP variable to bind to. Can set to null (for isNull support).
504		@param $name Name of stored procedure variable name to bind to.
505		@param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in odbtp.
506		@param [$maxLen] Holds an maximum length of the variable.
507		@param [$type] The data type of $var. Legal values depend on driver.
508
509		See odbtp_attach_param documentation at http://odbtp.sourceforge.net.
510	*/
511	function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=0, $type=0)
512	{
513		if ( $this->odbc_driver == ODB_DRIVER_JET ) {
514			$name = '['.$name.']';
515			if( !$type && $this->_useUnicodeSQL
516				&& @odbtp_param_bindtype($stmt[1], $name) == ODB_CHAR )
517			{
518				$type = ODB_WCHAR;
519			}
520		}
521		else {
522			$name = '@'.$name;
523		}
524		return @odbtp_attach_param($stmt[1], $name, $var, $type, $maxLen);
525	}
526
527	/*
528		Insert a null into the blob field of the table first.
529		Then use UpdateBlob to store the blob.
530
531		Usage:
532
533		$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
534		$conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
535	*/
536
537	function UpdateBlob($table,$column,$val,$where,$blobtype='image')
538	{
539		$sql = "UPDATE $table SET $column = ? WHERE $where";
540		if( !($stmt = @odbtp_prepare($sql, $this->_connectionID)) )
541			return false;
542		if( !@odbtp_input( $stmt, 1, ODB_BINARY, 1000000, $blobtype ) )
543			return false;
544		if( !@odbtp_set( $stmt, 1, $val ) )
545			return false;
546		return @odbtp_execute( $stmt ) != false;
547	}
548
549	function MetaIndexes($table,$primary=false, $owner=false)
550	{
551		switch ( $this->odbc_driver) {
552			case ODB_DRIVER_MSSQL:
553				return $this->MetaIndexes_mssql($table, $primary);
554			default:
555				return array();
556		}
557	}
558
559	function MetaIndexes_mssql($table,$primary=false, $owner = false)
560	{
561		$table = strtolower($this->qstr($table));
562
563		$sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno,
564			CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
565			CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
566			FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id
567			INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid
568			INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
569			WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND lower(O.Name) = $table
570			ORDER BY O.name, I.Name, K.keyno";
571
572		global $ADODB_FETCH_MODE;
573		$save = $ADODB_FETCH_MODE;
574        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
575        if ($this->fetchMode !== FALSE) {
576        	$savem = $this->SetFetchMode(FALSE);
577        }
578
579        $rs = $this->Execute($sql);
580        if (isset($savem)) {
581        	$this->SetFetchMode($savem);
582        }
583        $ADODB_FETCH_MODE = $save;
584
585        if (!is_object($rs)) {
586        	return FALSE;
587        }
588
589		$indexes = array();
590		while ($row = $rs->FetchRow()) {
591			if ($primary && !$row[5]) continue;
592
593            $indexes[$row[0]]['unique'] = $row[6];
594            $indexes[$row[0]]['columns'][] = $row[1];
595    	}
596        return $indexes;
597	}
598
599	function IfNull( $field, $ifNull )
600	{
601		switch( $this->odbc_driver ) {
602			case ODB_DRIVER_MSSQL:
603				return " ISNULL($field, $ifNull) ";
604			case ODB_DRIVER_JET:
605				return " IIF(IsNull($field), $ifNull, $field) ";
606		}
607		return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
608	}
609
610	function _query($sql,$inputarr=false)
611	{
612		$last_php_error = $this->resetLastError();
613		$this->_errorMsg = false;
614		$this->_errorCode = false;
615
616 		if ($inputarr) {
617			if (is_array($sql)) {
618				$stmtid = $sql[1];
619			} else {
620				$stmtid = @odbtp_prepare($sql,$this->_connectionID);
621				if ($stmtid == false) {
622					$this->_errorMsg = $this->getChangedErrorMsg($last_php_error);
623					return false;
624				}
625			}
626			$num_params = @odbtp_num_params( $stmtid );
627			/*
628			for( $param = 1; $param <= $num_params; $param++ ) {
629				@odbtp_input( $stmtid, $param );
630				@odbtp_set( $stmtid, $param, $inputarr[$param-1] );
631			}*/
632
633			$param = 1;
634			foreach($inputarr as $v) {
635				@odbtp_input( $stmtid, $param );
636				@odbtp_set( $stmtid, $param, $v );
637				$param += 1;
638				if ($param > $num_params) break;
639			}
640
641			if (!@odbtp_execute($stmtid) ) {
642				return false;
643			}
644		} else if (is_array($sql)) {
645			$stmtid = $sql[1];
646			if (!@odbtp_execute($stmtid)) {
647				return false;
648			}
649		} else {
650			$stmtid = odbtp_query($sql,$this->_connectionID);
651   		}
652		$this->_lastAffectedRows = 0;
653		if ($stmtid) {
654				$this->_lastAffectedRows = @odbtp_affected_rows($stmtid);
655		}
656        return $stmtid;
657	}
658
659	function _close()
660	{
661		$ret = @odbtp_close($this->_connectionID);
662		$this->_connectionID = false;
663		return $ret;
664	}
665}
666
667class ADORecordSet_odbtp extends ADORecordSet {
668
669	var $databaseType = 'odbtp';
670	var $canSeek = true;
671
672	function __construct($queryID,$mode=false)
673	{
674		if ($mode === false) {
675			global $ADODB_FETCH_MODE;
676			$mode = $ADODB_FETCH_MODE;
677		}
678		$this->fetchMode = $mode;
679		parent::__construct($queryID);
680	}
681
682	function _initrs()
683	{
684		$this->_numOfFields = @odbtp_num_fields($this->_queryID);
685		if (!($this->_numOfRows = @odbtp_num_rows($this->_queryID)))
686			$this->_numOfRows = -1;
687
688		if (!$this->connection->_useUnicodeSQL) return;
689
690		if ($this->connection->odbc_driver == ODB_DRIVER_JET) {
691			if (!@odbtp_get_attr(ODB_ATTR_MAPCHARTOWCHAR,
692			                     $this->connection->_connectionID))
693			{
694				for ($f = 0; $f < $this->_numOfFields; $f++) {
695					if (@odbtp_field_bindtype($this->_queryID, $f) == ODB_CHAR)
696						@odbtp_bind_field($this->_queryID, $f, ODB_WCHAR);
697				}
698			}
699		}
700	}
701
702	function FetchField($fieldOffset = 0)
703	{
704		$off=$fieldOffset; // offsets begin at 0
705		$o= new ADOFieldObject();
706		$o->name = @odbtp_field_name($this->_queryID,$off);
707		$o->type = @odbtp_field_type($this->_queryID,$off);
708        $o->max_length = @odbtp_field_length($this->_queryID,$off);
709		if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name);
710		else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name);
711		return $o;
712	}
713
714	function _seek($row)
715	{
716		return @odbtp_data_seek($this->_queryID, $row);
717	}
718
719	function fields($colname)
720	{
721		if ($this->fetchMode & ADODB_FETCH_ASSOC) return $this->fields[$colname];
722
723		if (!$this->bind) {
724			$this->bind = array();
725			for ($i=0; $i < $this->_numOfFields; $i++) {
726				$name = @odbtp_field_name( $this->_queryID, $i );
727				$this->bind[strtoupper($name)] = $i;
728			}
729		}
730		return $this->fields[$this->bind[strtoupper($colname)]];
731	}
732
733	function _fetch_odbtp($type=0)
734	{
735		switch ($this->fetchMode) {
736			case ADODB_FETCH_NUM:
737				$this->fields = @odbtp_fetch_row($this->_queryID, $type);
738				break;
739			case ADODB_FETCH_ASSOC:
740				$this->fields = @odbtp_fetch_assoc($this->_queryID, $type);
741				break;
742            default:
743				$this->fields = @odbtp_fetch_array($this->_queryID, $type);
744		}
745		if ($this->databaseType = 'odbtp_vfp') {
746			if ($this->fields)
747			foreach($this->fields as $k => $v) {
748				if (strncmp($v,'1899-12-30',10) == 0) $this->fields[$k] = '';
749			}
750		}
751		return is_array($this->fields);
752	}
753
754	function _fetch()
755	{
756		return $this->_fetch_odbtp();
757	}
758
759	function MoveFirst()
760	{
761		if (!$this->_fetch_odbtp(ODB_FETCH_FIRST)) return false;
762		$this->EOF = false;
763		$this->_currentRow = 0;
764		return true;
765    }
766
767	function MoveLast()
768	{
769		if (!$this->_fetch_odbtp(ODB_FETCH_LAST)) return false;
770		$this->EOF = false;
771		$this->_currentRow = $this->_numOfRows - 1;
772		return true;
773	}
774
775	function NextRecordSet()
776	{
777		if (!@odbtp_next_result($this->_queryID)) return false;
778		$this->_inited = false;
779		$this->bind = false;
780		$this->_currentRow = -1;
781		$this->Init();
782		return true;
783	}
784
785	function _close()
786	{
787		return @odbtp_free_query($this->_queryID);
788	}
789}
790
791class ADORecordSet_odbtp_mssql extends ADORecordSet_odbtp {
792
793	var $databaseType = 'odbtp_mssql';
794
795	function __construct($id,$mode=false)
796	{
797		return parent::__construct($id,$mode);
798	}
799}
800
801class ADORecordSet_odbtp_access extends ADORecordSet_odbtp {
802
803	var $databaseType = 'odbtp_access';
804
805	function __construct($id,$mode=false)
806	{
807		return parent::__construct($id,$mode);
808	}
809}
810
811class ADORecordSet_odbtp_vfp extends ADORecordSet_odbtp {
812
813	var $databaseType = 'odbtp_vfp';
814
815	function __construct($id,$mode=false)
816	{
817		return parent::__construct($id,$mode);
818	}
819}
820
821class ADORecordSet_odbtp_oci8 extends ADORecordSet_odbtp {
822
823	var $databaseType = 'odbtp_oci8';
824
825	function __construct($id,$mode=false)
826	{
827		return parent::__construct($id,$mode);
828	}
829}
830
831class ADORecordSet_odbtp_sybase extends ADORecordSet_odbtp {
832
833	var $databaseType = 'odbtp_sybase';
834
835	function __construct($id,$mode=false)
836	{
837		return parent::__construct($id,$mode);
838	}
839}
840