PageRenderTime 39ms CodeModel.GetById 17ms app.highlight 17ms RepoModel.GetById 1ms app.codeStats 0ms

/php/extlib/adodb5/drivers/adodb-pdo.inc.php

http://github.com/movabletype/movabletype
PHP | 820 lines | 673 code | 74 blank | 73 comment | 64 complexity | 7d302f1d5c2d7af9daffd6ad56052dfb MD5 | raw file
  1<?php
  2/**
  3	@version   v5.20.14  06-Jan-2019
  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
  7	Released under both BSD license and Lesser GPL library license.
  8	Whenever there is any discrepancy between the two licenses,
  9	the BSD license will take precedence.
 10
 11	Set tabs to 4 for best viewing.
 12
 13	Latest version is available at http://adodb.org/
 14
 15	Requires ODBC. Works on Windows and Unix.
 16
 17	Problems:
 18		Where is float/decimal type in pdo_param_type
 19		LOB handling for CLOB/BLOB differs significantly
 20*/
 21
 22// security - hide paths
 23if (!defined('ADODB_DIR')) die();
 24
 25
 26/*
 27enum pdo_param_type {
 28PDO::PARAM_NULL, 0
 29
 30/* int as in long (the php native int type).
 31 * If you mark a column as an int, PDO expects get_col to return
 32 * a pointer to a long
 33PDO::PARAM_INT, 1
 34
 35/* get_col ptr should point to start of the string buffer
 36PDO::PARAM_STR, 2
 37
 38/* get_col: when len is 0 ptr should point to a php_stream *,
 39 * otherwise it should behave like a string. Indicate a NULL field
 40 * value by setting the ptr to NULL
 41PDO::PARAM_LOB, 3
 42
 43/* get_col: will expect the ptr to point to a new PDOStatement object handle,
 44 * but this isn't wired up yet
 45PDO::PARAM_STMT, 4 /* hierarchical result set
 46
 47/* get_col ptr should point to a zend_bool
 48PDO::PARAM_BOOL, 5
 49
 50
 51/* magic flag to denote a parameter as being input/output
 52PDO::PARAM_INPUT_OUTPUT = 0x80000000
 53};
 54*/
 55
 56function adodb_pdo_type($t)
 57{
 58	switch($t) {
 59	case 2: return 'VARCHAR';
 60	case 3: return 'BLOB';
 61	default: return 'NUMERIC';
 62	}
 63}
 64
 65/*----------------------------------------------------------------------------*/
 66
 67
 68class ADODB_pdo extends ADOConnection {
 69	var $databaseType = "pdo";
 70	var $dataProvider = "pdo";
 71	var $fmtDate = "'Y-m-d'";
 72	var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
 73	var $replaceQuote = "''"; // string to use to replace quotes
 74	var $hasAffectedRows = true;
 75	var $_bindInputArray = true;
 76	var $_genIDSQL;
 77	var $_genSeqSQL = "create table %s (id integer)";
 78	var $_dropSeqSQL;
 79	var $_autocommit = true;
 80	var $_haserrorfunctions = true;
 81	var $_lastAffectedRows = 0;
 82
 83	var $_errormsg = false;
 84	var $_errorno = false;
 85
 86	var $dsnType = '';
 87	var $stmt = false;
 88	var $_driver;
 89
 90	function __construct()
 91	{
 92	}
 93
 94	function _UpdatePDO()
 95	{
 96		$d = $this->_driver;
 97		$this->fmtDate = $d->fmtDate;
 98		$this->fmtTimeStamp = $d->fmtTimeStamp;
 99		$this->replaceQuote = $d->replaceQuote;
100		$this->sysDate = $d->sysDate;
101		$this->sysTimeStamp = $d->sysTimeStamp;
102		$this->random = $d->random;
103		$this->concat_operator = $d->concat_operator;
104		$this->nameQuote = $d->nameQuote;
105
106		$this->hasGenID = $d->hasGenID;
107		$this->_genIDSQL = $d->_genIDSQL;
108		$this->_genSeqSQL = $d->_genSeqSQL;
109		$this->_dropSeqSQL = $d->_dropSeqSQL;
110
111		$d->_init($this);
112	}
113
114	function Time()
115	{
116		if (!empty($this->_driver->_hasdual)) {
117			$sql = "select $this->sysTimeStamp from dual";
118		}
119		else {
120			$sql = "select $this->sysTimeStamp";
121		}
122
123		$rs = $this->_Execute($sql);
124		if ($rs && !$rs->EOF) {
125			return $this->UnixTimeStamp(reset($rs->fields));
126		}
127
128		return false;
129	}
130
131	// returns true or false
132	function _connect($argDSN, $argUsername, $argPassword, $argDatabasename, $persist=false)
133	{
134		$at = strpos($argDSN,':');
135		$this->dsnType = substr($argDSN,0,$at);
136
137		if ($argDatabasename) {
138			switch($this->dsnType){
139				case 'sqlsrv':
140					$argDSN .= ';database='.$argDatabasename;
141					break;
142				case 'mssql':
143				case 'mysql':
144				case 'oci':
145				case 'pgsql':
146				case 'sqlite':
147				default:
148					$argDSN .= ';dbname='.$argDatabasename;
149			}
150		}
151		if ( $this->port ) {
152			$argDSN .= ';port=' . $this->port;
153		}
154		try {
155			$this->_connectionID = new PDO($argDSN, $argUsername, $argPassword);
156		} catch (Exception $e) {
157			$this->_connectionID = false;
158			$this->_errorno = -1;
159			//var_dump($e);
160			$this->_errormsg = 'Connection attempt failed: '.$e->getMessage();
161			return false;
162		}
163
164		if ($this->_connectionID) {
165			switch(ADODB_ASSOC_CASE){
166				case ADODB_ASSOC_CASE_LOWER:
167					$m = PDO::CASE_LOWER;
168					break;
169				case ADODB_ASSOC_CASE_UPPER:
170					$m = PDO::CASE_UPPER;
171					break;
172				default:
173				case ADODB_ASSOC_CASE_NATIVE:
174					$m = PDO::CASE_NATURAL;
175					break;
176			}
177
178			//$this->_connectionID->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT );
179			$this->_connectionID->setAttribute(PDO::ATTR_CASE,$m);
180
181			$class = 'ADODB_pdo_'.$this->dsnType;
182			//$this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,true);
183			switch($this->dsnType) {
184				case 'mssql':
185				case 'mysql':
186				case 'oci':
187				case 'pgsql':
188				case 'sqlite':
189				case 'sqlsrv':
190					include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php');
191					break;
192			}
193			if (class_exists($class)) {
194				$this->_driver = new $class();
195			}
196			else {
197				$this->_driver = new ADODB_pdo_base();
198			}
199
200			$this->_driver->_connectionID = $this->_connectionID;
201			$this->_UpdatePDO();
202			$this->_driver->database = $this->database;
203			return true;
204		}
205		$this->_driver = new ADODB_pdo_base();
206		return false;
207	}
208
209	function Concat()
210	{
211		$args = func_get_args();
212		if(method_exists($this->_driver, 'Concat')) {
213			return call_user_func_array(array($this->_driver, 'Concat'), $args);
214		}
215
216		if (PHP_VERSION >= 5.3) {
217			return call_user_func_array('parent::Concat', $args);
218		}
219		return call_user_func_array(array($this,'parent::Concat'), $args);
220	}
221
222	// returns true or false
223	function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
224	{
225		return $this->_connect($argDSN, $argUsername, $argPassword, $argDatabasename, true);
226	}
227
228	/*------------------------------------------------------------------------------*/
229
230
231	function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
232	{
233		$save = $this->_driver->fetchMode;
234		$this->_driver->fetchMode = $this->fetchMode;
235		$this->_driver->debug = $this->debug;
236		$ret = $this->_driver->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
237		$this->_driver->fetchMode = $save;
238		return $ret;
239	}
240
241
242	function ServerInfo()
243	{
244		return $this->_driver->ServerInfo();
245	}
246
247	function MetaTables($ttype=false,$showSchema=false,$mask=false)
248	{
249		return $this->_driver->MetaTables($ttype,$showSchema,$mask);
250	}
251
252	function MetaColumns($table,$normalize=true)
253	{
254		return $this->_driver->MetaColumns($table,$normalize);
255	}
256
257	function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
258	{
259		$obj = $stmt[1];
260		if ($type) {
261			$obj->bindParam($name, $var, $type, $maxLen);
262		}
263		else {
264			$obj->bindParam($name, $var);
265		}
266	}
267
268	function OffsetDate($dayFraction,$date=false)
269	{
270		return $this->_driver->OffsetDate($dayFraction,$date);
271	}
272
273	function SelectDB($dbName)
274	{
275		return $this->_driver->SelectDB($dbName);
276	}
277
278	function SQLDate($fmt, $col=false)
279	{
280		return $this->_driver->SQLDate($fmt, $col);
281	}
282
283	function ErrorMsg()
284	{
285		if ($this->_errormsg !== false) {
286			return $this->_errormsg;
287		}
288		if (!empty($this->_stmt)) {
289			$arr = $this->_stmt->errorInfo();
290		}
291		else if (!empty($this->_connectionID)) {
292			$arr = $this->_connectionID->errorInfo();
293		}
294		else {
295			return 'No Connection Established';
296		}
297
298		if ($arr) {
299			if (sizeof($arr)<2) {
300				return '';
301			}
302			if ((integer)$arr[0]) {
303				return $arr[2];
304			}
305			else {
306				return '';
307			}
308		}
309		else {
310			return '-1';
311		}
312	}
313
314
315	function ErrorNo()
316	{
317		if ($this->_errorno !== false) {
318			return $this->_errorno;
319		}
320		if (!empty($this->_stmt)) {
321			$err = $this->_stmt->errorCode();
322		}
323		else if (!empty($this->_connectionID)) {
324			$arr = $this->_connectionID->errorInfo();
325			if (isset($arr[0])) {
326				$err = $arr[0];
327			}
328			else {
329				$err = -1;
330			}
331		} else {
332			return 0;
333		}
334
335		if ($err == '00000') {
336			return 0; // allows empty check
337		}
338		return $err;
339	}
340
341    /**
342     * @param bool $auto_commit
343     * @return void
344     */
345	function SetAutoCommit($auto_commit)
346    {
347        if(method_exists($this->_driver, 'SetAutoCommit')) {
348            $this->_driver->SetAutoCommit($auto_commit);
349        }
350    }
351
352	function SetTransactionMode($transaction_mode)
353	{
354		if(method_exists($this->_driver, 'SetTransactionMode')) {
355			return $this->_driver->SetTransactionMode($transaction_mode);
356		}
357
358		return parent::SetTransactionMode($seqname);
359	}
360
361	function BeginTrans()
362	{
363		if(method_exists($this->_driver, 'BeginTrans')) {
364			return $this->_driver->BeginTrans();
365		}
366
367		if (!$this->hasTransactions) {
368			return false;
369		}
370		if ($this->transOff) {
371			return true;
372		}
373		$this->transCnt += 1;
374		$this->_autocommit = false;
375		$this->SetAutoCommit(false);
376
377		return $this->_connectionID->beginTransaction();
378	}
379
380	function CommitTrans($ok=true)
381	{
382		if(method_exists($this->_driver, 'CommitTrans')) {
383			return $this->_driver->CommitTrans($ok);
384		}
385
386		if (!$this->hasTransactions) {
387			return false;
388		}
389		if ($this->transOff) {
390			return true;
391		}
392		if (!$ok) {
393			return $this->RollbackTrans();
394		}
395		if ($this->transCnt) {
396			$this->transCnt -= 1;
397		}
398		$this->_autocommit = true;
399
400		$ret = $this->_connectionID->commit();
401		$this->SetAutoCommit(true);
402		return $ret;
403	}
404
405	function RollbackTrans()
406	{
407		if(method_exists($this->_driver, 'RollbackTrans')) {
408			return $this->_driver->RollbackTrans();
409		}
410
411		if (!$this->hasTransactions) {
412			return false;
413		}
414		if ($this->transOff) {
415			return true;
416		}
417		if ($this->transCnt) {
418			$this->transCnt -= 1;
419		}
420		$this->_autocommit = true;
421
422		$ret = $this->_connectionID->rollback();
423		$this->SetAutoCommit(true);
424		return $ret;
425	}
426
427	function Prepare($sql)
428	{
429		$this->_stmt = $this->_connectionID->prepare($sql);
430		if ($this->_stmt) {
431			return array($sql,$this->_stmt);
432		}
433
434		return false;
435	}
436
437	function PrepareStmt($sql)
438	{
439		$stmt = $this->_connectionID->prepare($sql);
440		if (!$stmt) {
441			return false;
442		}
443		$obj = new ADOPDOStatement($stmt,$this);
444		return $obj;
445	}
446
447	function CreateSequence($seqname='adodbseq',$startID=1)
448	{
449		if(method_exists($this->_driver, 'CreateSequence')) {
450			return $this->_driver->CreateSequence($seqname, $startID);
451		}
452
453		return parent::CreateSequence($seqname, $startID);
454	}
455
456	function DropSequence($seqname='adodbseq')
457	{
458		if(method_exists($this->_driver, 'DropSequence')) {
459			return $this->_driver->DropSequence($seqname);
460		}
461
462		return parent::DropSequence($seqname);
463	}
464
465	function GenID($seqname='adodbseq',$startID=1)
466	{
467		if(method_exists($this->_driver, 'GenID')) {
468			return $this->_driver->GenID($seqname, $startID);
469		}
470
471		return parent::GenID($seqname, $startID);
472	}
473
474
475	/* returns queryID or false */
476	function _query($sql,$inputarr=false)
477	{
478		$ok = false;
479		if (is_array($sql)) {
480			$stmt = $sql[1];
481		} else {
482			$stmt = $this->_connectionID->prepare($sql);
483		}
484		#adodb_backtrace();
485		#var_dump($this->_bindInputArray);
486		if ($stmt) {
487			if (empty($this->_driver))
488				$this->_driver = new stdClass;
489			$this->_driver->debug = $this->debug;
490			if ($inputarr) {
491				$ok = $stmt->execute($inputarr);
492			}
493			else {
494				$ok = $stmt->execute();
495			}
496		}
497
498
499		$this->_errormsg = false;
500		$this->_errorno = false;
501
502		if ($ok) {
503			$this->_stmt = $stmt;
504			return $stmt;
505		}
506
507		if ($stmt) {
508
509			$arr = $stmt->errorinfo();
510			if ((integer)$arr[1]) {
511				$this->_errormsg = $arr[2];
512				$this->_errorno = $arr[1];
513			}
514
515		} else {
516			$this->_errormsg = false;
517			$this->_errorno = false;
518		}
519		return false;
520	}
521
522	// returns true or false
523	function _close()
524	{
525		$this->_stmt = false;
526		return true;
527	}
528
529	function _affectedrows()
530	{
531		return ($this->_stmt) ? $this->_stmt->rowCount() : 0;
532	}
533
534	function _insertid()
535	{
536		return ($this->_connectionID) ? $this->_connectionID->lastInsertId() : 0;
537	}
538
539	/**
540	 * Quotes a string to be sent to the database.
541	 * If we have an active connection, delegates quoting to the underlying
542	 * PDO object. Otherwise, replace "'" by the value of $replaceQuote (same
543	 * behavior as mysqli driver)
544	 * @param string  $s            The string to quote
545	 * @param boolean $magic_quotes If false, use PDO::quote().
546	 * @return string Quoted string
547	 */
548	function qstr($s, $magic_quotes = false)
549	{
550		if (!$magic_quotes) {
551			if ($this->_connectionID) {
552				return $this->_connectionID->quote($s);
553			}
554			return "'" . str_replace("'", $this->replaceQuote, $s) . "'";
555		}
556
557		// undo magic quotes for "
558		$s = str_replace('\\"', '"', $s);
559		return "'$s'";
560	}
561
562}
563
564class ADODB_pdo_base extends ADODB_pdo {
565
566	var $sysDate = "'?'";
567	var $sysTimeStamp = "'?'";
568
569
570	function _init($parentDriver)
571	{
572		$parentDriver->_bindInputArray = true;
573		#$parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
574	}
575
576	function ServerInfo()
577	{
578		return ADOConnection::ServerInfo();
579	}
580
581	function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0)
582	{
583		$ret = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
584		return $ret;
585	}
586
587	function MetaTables($ttype=false,$showSchema=false,$mask=false)
588	{
589		return false;
590	}
591
592	function MetaColumns($table,$normalize=true)
593	{
594		return false;
595	}
596}
597
598class ADOPDOStatement {
599
600	var $databaseType = "pdo";
601	var $dataProvider = "pdo";
602	var $_stmt;
603	var $_connectionID;
604
605	function __construct($stmt,$connection)
606	{
607		$this->_stmt = $stmt;
608		$this->_connectionID = $connection;
609	}
610
611	function Execute($inputArr=false)
612	{
613		$savestmt = $this->_connectionID->_stmt;
614		$rs = $this->_connectionID->Execute(array(false,$this->_stmt),$inputArr);
615		$this->_connectionID->_stmt = $savestmt;
616		return $rs;
617	}
618
619	function InParameter(&$var,$name,$maxLen=4000,$type=false)
620	{
621
622		if ($type) {
623			$this->_stmt->bindParam($name,$var,$type,$maxLen);
624		}
625		else {
626			$this->_stmt->bindParam($name, $var);
627		}
628	}
629
630	function Affected_Rows()
631	{
632		return ($this->_stmt) ? $this->_stmt->rowCount() : 0;
633	}
634
635	function ErrorMsg()
636	{
637		if ($this->_stmt) {
638			$arr = $this->_stmt->errorInfo();
639		}
640		else {
641			$arr = $this->_connectionID->errorInfo();
642		}
643
644		if (is_array($arr)) {
645			if ((integer) $arr[0] && isset($arr[2])) {
646				return $arr[2];
647			}
648			else {
649				return '';
650			}
651		} else {
652			return '-1';
653		}
654	}
655
656	function NumCols()
657	{
658		return ($this->_stmt) ? $this->_stmt->columnCount() : 0;
659	}
660
661	function ErrorNo()
662	{
663		if ($this->_stmt) {
664			return $this->_stmt->errorCode();
665		}
666		else {
667			return $this->_connectionID->errorInfo();
668		}
669	}
670}
671
672/*--------------------------------------------------------------------------------------
673	Class Name: Recordset
674--------------------------------------------------------------------------------------*/
675
676class ADORecordSet_pdo extends ADORecordSet {
677
678	var $bind = false;
679	var $databaseType = "pdo";
680	var $dataProvider = "pdo";
681
682	function __construct($id,$mode=false)
683	{
684		if ($mode === false) {
685			global $ADODB_FETCH_MODE;
686			$mode = $ADODB_FETCH_MODE;
687		}
688		$this->adodbFetchMode = $mode;
689		switch($mode) {
690		case ADODB_FETCH_NUM: $mode = PDO::FETCH_NUM; break;
691		case ADODB_FETCH_ASSOC:  $mode = PDO::FETCH_ASSOC; break;
692
693		case ADODB_FETCH_BOTH:
694		default: $mode = PDO::FETCH_BOTH; break;
695		}
696		$this->fetchMode = $mode;
697
698		$this->_queryID = $id;
699		parent::__construct($id);
700	}
701
702
703	function Init()
704	{
705		if ($this->_inited) {
706			return;
707		}
708		$this->_inited = true;
709		if ($this->_queryID) {
710			@$this->_initrs();
711		}
712		else {
713			$this->_numOfRows = 0;
714			$this->_numOfFields = 0;
715		}
716		if ($this->_numOfRows != 0 && $this->_currentRow == -1) {
717			$this->_currentRow = 0;
718			if ($this->EOF = ($this->_fetch() === false)) {
719				$this->_numOfRows = 0; // _numOfRows could be -1
720			}
721		} else {
722			$this->EOF = true;
723		}
724	}
725
726	function _initrs()
727	{
728	global $ADODB_COUNTRECS;
729
730		$this->_numOfRows = ($ADODB_COUNTRECS) ? @$this->_queryID->rowCount() : -1;
731		if (!$this->_numOfRows) {
732			$this->_numOfRows = -1;
733		}
734		$this->_numOfFields = $this->_queryID->columnCount();
735	}
736
737	// returns the field object
738	function FetchField($fieldOffset = -1)
739	{
740		$off=$fieldOffset+1; // offsets begin at 1
741
742		$o= new ADOFieldObject();
743		$arr = @$this->_queryID->getColumnMeta($fieldOffset);
744		if (!$arr) {
745			$o->name = 'bad getColumnMeta()';
746			$o->max_length = -1;
747			$o->type = 'VARCHAR';
748			$o->precision = 0;
749	#		$false = false;
750			return $o;
751		}
752		//adodb_pr($arr);
753		$o->name = $arr['name'];
754		if (isset($arr['sqlsrv:decl_type']) && $arr['sqlsrv:decl_type'] <> "null") 
755		{
756		    /*
757		    * If the database is SQL server, use the native built-ins
758		    */
759		    $o->type = $arr['sqlsrv:decl_type'];
760		}
761		elseif (isset($arr['native_type']) && $arr['native_type'] <> "null") 
762		{
763		    $o->type = $arr['native_type'];
764		}
765		else 
766		{
767		     $o->type = adodb_pdo_type($arr['pdo_type']);
768		}
769		
770		$o->max_length = $arr['len'];
771		$o->precision = $arr['precision'];
772
773		switch(ADODB_ASSOC_CASE) {
774			case ADODB_ASSOC_CASE_LOWER:
775				$o->name = strtolower($o->name);
776				break;
777			case ADODB_ASSOC_CASE_UPPER:
778				$o->name = strtoupper($o->name);
779				break;
780		}
781		return $o;
782	}
783
784	function _seek($row)
785	{
786		return false;
787	}
788
789	function _fetch()
790	{
791		if (!$this->_queryID) {
792			return false;
793		}
794
795		$this->fields = $this->_queryID->fetch($this->fetchMode);
796		return !empty($this->fields);
797	}
798
799	function _close()
800	{
801		$this->_queryID = false;
802	}
803
804	function Fields($colname)
805	{
806		if ($this->adodbFetchMode != ADODB_FETCH_NUM) {
807			return @$this->fields[$colname];
808		}
809
810		if (!$this->bind) {
811			$this->bind = array();
812			for ($i=0; $i < $this->_numOfFields; $i++) {
813				$o = $this->FetchField($i);
814				$this->bind[strtoupper($o->name)] = $i;
815			}
816		}
817		return $this->fields[$this->bind[strtoupper($colname)]];
818	}
819
820}