[ Index ]

PHP Cross Reference of Moodle 310

title

Body

[close]

/lib/adodb/drivers/ -> adodb-oci8.inc.php (source)

   1  <?php
   2  /*
   3  
   4    @version   v5.20.16  12-Jan-2020
   5    @copyright (c) 2000-2013 John Lim. All rights reserved.
   6    @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   7  
   8    Released under both BSD license and Lesser GPL library license.
   9    Whenever there is any discrepancy between the two licenses,
  10    the BSD license will take precedence.
  11  
  12    Latest version is available at http://adodb.org/
  13  
  14    Code contributed by George Fourlanos <fou@infomap.gr>
  15  
  16    13 Nov 2000 jlim - removed all ora_* references.
  17  */
  18  
  19  // security - hide paths
  20  if (!defined('ADODB_DIR')) die();
  21  
  22  /*
  23  NLS_Date_Format
  24  Allows you to use a date format other than the Oracle Lite default. When a literal
  25  character string appears where a date value is expected, the Oracle Lite database
  26  tests the string to see if it matches the formats of Oracle, SQL-92, or the value
  27  specified for this parameter in the POLITE.INI file. Setting this parameter also
  28  defines the default format used in the TO_CHAR or TO_DATE functions when no
  29  other format string is supplied.
  30  
  31  For Oracle the default is dd-mon-yy or dd-mon-yyyy, and for SQL-92 the default is
  32  yy-mm-dd or yyyy-mm-dd.
  33  
  34  Using 'RR' in the format forces two-digit years less than or equal to 49 to be
  35  interpreted as years in the 21st century (2000-2049), and years over 50 as years in
  36  the 20th century (1950-1999). Setting the RR format as the default for all two-digit
  37  year entries allows you to become year-2000 compliant. For example:
  38  NLS_DATE_FORMAT='RR-MM-DD'
  39  
  40  You can also modify the date format using the ALTER SESSION command.
  41  */
  42  
  43  # define the LOB descriptor type for the given type
  44  # returns false if no LOB descriptor
  45  function oci_lob_desc($type) {
  46      switch ($type) {
  47          case OCI_B_BFILE:  return OCI_D_FILE;
  48          case OCI_B_CFILEE: return OCI_D_FILE;
  49          case OCI_B_CLOB:   return OCI_D_LOB;
  50          case OCI_B_BLOB:   return OCI_D_LOB;
  51          case OCI_B_ROWID:  return OCI_D_ROWID;
  52      }
  53      return false;
  54  }
  55  
  56  class ADODB_oci8 extends ADOConnection {
  57      var $databaseType = 'oci8';
  58      var $dataProvider = 'oci8';
  59      var $replaceQuote = "''"; // string to use to replace quotes
  60      var $concat_operator='||';
  61      var $sysDate = "TRUNC(SYSDATE)";
  62      var $sysTimeStamp = 'SYSDATE'; // requires oracle 9 or later, otherwise use SYSDATE
  63      var $metaDatabasesSQL = "SELECT USERNAME FROM ALL_USERS WHERE USERNAME NOT IN ('SYS','SYSTEM','DBSNMP','OUTLN') ORDER BY 1";
  64      var $_stmt;
  65      var $_commit = OCI_COMMIT_ON_SUCCESS;
  66      var $_initdate = true; // init date to YYYY-MM-DD
  67      var $metaTablesSQL = "select table_name,table_type from cat where table_type in ('TABLE','VIEW') and table_name not like 'BIN\$%'"; // bin$ tables are recycle bin tables
  68      var $metaColumnsSQL = "select cname,coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; //changed by smondino@users.sourceforge. net
  69      var $metaColumnsSQL2 = "select column_name,data_type,data_length, data_scale, data_precision,
  70      case when nullable = 'Y' then 'NULL'
  71      else 'NOT NULL' end as nulls,
  72      data_default from all_tab_cols
  73    where owner='%s' and table_name='%s' order by column_id"; // when there is a schema
  74      var $_bindInputArray = true;
  75      var $hasGenID = true;
  76      var $_genIDSQL = "SELECT (%s.nextval) FROM DUAL";
  77      var $_genSeqSQL = "
  78  DECLARE
  79      PRAGMA AUTONOMOUS_TRANSACTION;
  80  BEGIN
  81      execute immediate 'CREATE SEQUENCE %s START WITH %s';
  82  END;
  83  ";
  84  
  85      var $_dropSeqSQL = "DROP SEQUENCE %s";
  86      var $hasAffectedRows = true;
  87      var $random = "abs(mod(DBMS_RANDOM.RANDOM,10000001)/10000000)";
  88      var $noNullStrings = false;
  89      var $connectSID = false;
  90      var $_bind = false;
  91      var $_nestedSQL = true;
  92      var $_hasOciFetchStatement = false;
  93      var $_getarray = false; // currently not working
  94      var $leftOuter = '';  // oracle wierdness, $col = $value (+) for LEFT OUTER, $col (+)= $value for RIGHT OUTER
  95      var $session_sharing_force_blob = false; // alter session on updateblob if set to true
  96      var $firstrows = true; // enable first rows optimization on SelectLimit()
  97      var $selectOffsetAlg1 = 1000; // when to use 1st algorithm of selectlimit.
  98      var $NLS_DATE_FORMAT = 'YYYY-MM-DD';  // To include time, use 'RRRR-MM-DD HH24:MI:SS'
  99      var $dateformat = 'YYYY-MM-DD'; // DBDate format
 100      var $useDBDateFormatForTextInput=false;
 101      var $datetime = false; // MetaType('DATE') returns 'D' (datetime==false) or 'T' (datetime == true)
 102      var $_refLOBs = array();
 103  
 104      // var $ansiOuter = true; // if oracle9
 105  
 106  	function __construct()
 107      {
 108          $this->_hasOciFetchStatement = ADODB_PHPVER >= 0x4200;
 109          if (defined('ADODB_EXTENSION')) {
 110              $this->rsPrefix .= 'ext_';
 111          }
 112      }
 113  
 114      /*  function MetaColumns($table, $normalize=true) added by smondino@users.sourceforge.net*/
 115  	function MetaColumns($table, $normalize=true)
 116      {
 117      global $ADODB_FETCH_MODE;
 118  
 119          $schema = '';
 120          $this->_findschema($table, $schema);
 121  
 122          $save = $ADODB_FETCH_MODE;
 123          $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
 124          if ($this->fetchMode !== false) {
 125              $savem = $this->SetFetchMode(false);
 126          }
 127  
 128          if ($schema){
 129              $rs = $this->Execute(sprintf($this->metaColumnsSQL2, strtoupper($schema), strtoupper($table)));
 130          }
 131          else {
 132              $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
 133          }
 134  
 135          if (isset($savem)) {
 136              $this->SetFetchMode($savem);
 137          }
 138          $ADODB_FETCH_MODE = $save;
 139          if (!$rs) {
 140              return false;
 141          }
 142          $retarr = array();
 143          while (!$rs->EOF) {
 144              $fld = new ADOFieldObject();
 145              $fld->name = $rs->fields[0];
 146              $fld->type = $rs->fields[1];
 147              $fld->max_length = $rs->fields[2];
 148              $fld->scale = $rs->fields[3];
 149              if ($rs->fields[1] == 'NUMBER') {
 150                  if ($rs->fields[3] == 0) {
 151                      $fld->type = 'INT';
 152                  }
 153                  $fld->max_length = $rs->fields[4];
 154              }
 155              $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0);
 156              $fld->binary = (strpos($fld->type,'BLOB') !== false);
 157              $fld->default_value = $rs->fields[6];
 158  
 159              if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) {
 160                  $retarr[] = $fld;
 161              }
 162              else {
 163                  $retarr[strtoupper($fld->name)] = $fld;
 164              }
 165              $rs->MoveNext();
 166          }
 167          $rs->Close();
 168          if (empty($retarr)) {
 169              return false;
 170          }
 171          return $retarr;
 172      }
 173  
 174  	function Time()
 175      {
 176          $rs = $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual");
 177          if ($rs && !$rs->EOF) {
 178              return $this->UnixTimeStamp(reset($rs->fields));
 179          }
 180  
 181          return false;
 182      }
 183  
 184      /**
 185       * Multiple modes of connection are supported:
 186       *
 187       * a. Local Database
 188       *    $conn->Connect(false,'scott','tiger');
 189       *
 190       * b. From tnsnames.ora
 191       *    $conn->Connect($tnsname,'scott','tiger');
 192       *    $conn->Connect(false,'scott','tiger',$tnsname);
 193       *
 194       * c. Server + service name
 195       *    $conn->Connect($serveraddress,'scott,'tiger',$service_name);
 196       *
 197       * d. Server + SID
 198       *    $conn->connectSID = true;
 199       *    $conn->Connect($serveraddress,'scott,'tiger',$SID);
 200       *
 201       * @param string|false $argHostname DB server hostname or TNS name
 202       * @param string $argUsername
 203       * @param string $argPassword
 204       * @param string $argDatabasename Service name, SID (defaults to null)
 205       * @param int $mode Connection mode, defaults to 0
 206       *                  (0 = non-persistent, 1 = persistent, 2 = force new connection)
 207       *
 208       * @return bool
 209       */
 210  	function _connect($argHostname, $argUsername, $argPassword, $argDatabasename=null, $mode=0)
 211      {
 212          if (!function_exists('oci_pconnect')) {
 213              return null;
 214          }
 215          #adodb_backtrace();
 216  
 217          $this->_errorMsg = false;
 218          $this->_errorCode = false;
 219  
 220          if($argHostname) { // added by Jorma Tuomainen <jorma.tuomainen@ppoy.fi>
 221              if (empty($argDatabasename)) {
 222                  $argDatabasename = $argHostname;
 223              }
 224              else {
 225                  if(strpos($argHostname,":")) {
 226                      $argHostinfo=explode(":",$argHostname);
 227                      $argHostname=$argHostinfo[0];
 228                      $argHostport=$argHostinfo[1];
 229                  } else {
 230                      $argHostport = empty($this->port)?  "1521" : $this->port;
 231                  }
 232  
 233                  if (strncasecmp($argDatabasename,'SID=',4) == 0) {
 234                      $argDatabasename = substr($argDatabasename,4);
 235                      $this->connectSID = true;
 236                  }
 237  
 238                  if ($this->connectSID) {
 239                      $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
 240                      .")(PORT=$argHostport))(CONNECT_DATA=(SID=$argDatabasename)))";
 241                  } else
 242                      $argDatabasename="(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=".$argHostname
 243                      .")(PORT=$argHostport))(CONNECT_DATA=(SERVICE_NAME=$argDatabasename)))";
 244              }
 245          }
 246  
 247          //if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
 248          if ($mode==1) {
 249              $this->_connectionID = ($this->charSet)
 250                  ? oci_pconnect($argUsername,$argPassword, $argDatabasename,$this->charSet)
 251                  : oci_pconnect($argUsername,$argPassword, $argDatabasename);
 252              if ($this->_connectionID && $this->autoRollback)  {
 253                  oci_rollback($this->_connectionID);
 254              }
 255          } else if ($mode==2) {
 256              $this->_connectionID = ($this->charSet)
 257                  ? oci_new_connect($argUsername,$argPassword, $argDatabasename,$this->charSet)
 258                  : oci_new_connect($argUsername,$argPassword, $argDatabasename);
 259          } else {
 260              $this->_connectionID = ($this->charSet)
 261                  ? oci_connect($argUsername,$argPassword, $argDatabasename,$this->charSet)
 262                  : oci_connect($argUsername,$argPassword, $argDatabasename);
 263          }
 264          if (!$this->_connectionID) {
 265              return false;
 266          }
 267  
 268          if ($this->_initdate) {
 269              $this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='".$this->NLS_DATE_FORMAT."'");
 270          }
 271  
 272          // looks like:
 273          // Oracle8i Enterprise Edition Release 8.1.7.0.0 - Production With the Partitioning option JServer Release 8.1.7.0.0 - Production
 274          // $vers = oci_server_version($this->_connectionID);
 275          // if (strpos($vers,'8i') !== false) $this->ansiOuter = true;
 276          return true;
 277      }
 278  
 279  	function ServerInfo()
 280      {
 281          $arr['compat'] = $this->GetOne('select value from sys.database_compatible_level');
 282          $arr['description'] = @oci_server_version($this->_connectionID);
 283          $arr['version'] = ADOConnection::_findvers($arr['description']);
 284          return $arr;
 285      }
 286          // returns true or false
 287  	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
 288      {
 289          return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,1);
 290      }
 291  
 292      // returns true or false
 293  	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
 294      {
 295          return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,2);
 296      }
 297  
 298  	function _affectedrows()
 299      {
 300          if (is_resource($this->_stmt)) {
 301              return @oci_num_rows($this->_stmt);
 302          }
 303          return 0;
 304      }
 305  
 306  	function IfNull( $field, $ifNull )
 307      {
 308          return " NVL($field, $ifNull) "; // if Oracle
 309      }
 310  
 311      // format and return date string in database date format
 312  	function DBDate($d,$isfld=false)
 313      {
 314          if (empty($d) && $d !== 0) {
 315              return 'null';
 316          }
 317  
 318          if ($isfld) {
 319              $d = _adodb_safedate($d);
 320              return 'TO_DATE('.$d.",'".$this->dateformat."')";
 321          }
 322  
 323          if (is_string($d)) {
 324              $d = ADORecordSet::UnixDate($d);
 325          }
 326  
 327          if (is_object($d)) {
 328              $ds = $d->format($this->fmtDate);
 329          }
 330          else {
 331              $ds = adodb_date($this->fmtDate,$d);
 332          }
 333  
 334          return "TO_DATE(".$ds.",'".$this->dateformat."')";
 335      }
 336  
 337  	function BindDate($d)
 338      {
 339          $d = ADOConnection::DBDate($d);
 340          if (strncmp($d, "'", 1)) {
 341              return $d;
 342          }
 343  
 344          return substr($d, 1, strlen($d)-2);
 345      }
 346  
 347  	function BindTimeStamp($ts)
 348      {
 349          if (empty($ts) && $ts !== 0) {
 350              return 'null';
 351          }
 352          if (is_string($ts)) {
 353              $ts = ADORecordSet::UnixTimeStamp($ts);
 354          }
 355  
 356          if (is_object($ts)) {
 357              $tss = $ts->format("'Y-m-d H:i:s'");
 358          }
 359          else {
 360              $tss = adodb_date("'Y-m-d H:i:s'",$ts);
 361          }
 362  
 363          return $tss;
 364      }
 365  
 366      // format and return date string in database timestamp format
 367  	function DBTimeStamp($ts,$isfld=false)
 368      {
 369          if (empty($ts) && $ts !== 0) {
 370              return 'null';
 371          }
 372          if ($isfld) {
 373              return 'TO_DATE(substr('.$ts.",1,19),'RRRR-MM-DD, HH24:MI:SS')";
 374          }
 375          if (is_string($ts)) {
 376              $ts = ADORecordSet::UnixTimeStamp($ts);
 377          }
 378  
 379          if (is_object($ts)) {
 380              $tss = $ts->format("'Y-m-d H:i:s'");
 381          }
 382          else {
 383              $tss = date("'Y-m-d H:i:s'",$ts);
 384          }
 385  
 386          return 'TO_DATE('.$tss.",'RRRR-MM-DD, HH24:MI:SS')";
 387      }
 388  
 389  	function RowLock($tables,$where,$col='1 as adodbignore')
 390      {
 391          if ($this->autoCommit) {
 392              $this->BeginTrans();
 393          }
 394          return $this->GetOne("select $col from $tables where $where for update");
 395      }
 396  
 397  	function MetaTables($ttype=false,$showSchema=false,$mask=false)
 398      {
 399          if ($mask) {
 400              $save = $this->metaTablesSQL;
 401              $mask = $this->qstr(strtoupper($mask));
 402              $this->metaTablesSQL .= " AND upper(table_name) like $mask";
 403          }
 404          $ret = ADOConnection::MetaTables($ttype,$showSchema);
 405  
 406          if ($mask) {
 407              $this->metaTablesSQL = $save;
 408          }
 409          return $ret;
 410      }
 411  
 412      // Mark Newnham
 413  	function MetaIndexes ($table, $primary = FALSE, $owner=false)
 414      {
 415          // save old fetch mode
 416          global $ADODB_FETCH_MODE;
 417  
 418          $save = $ADODB_FETCH_MODE;
 419          $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
 420  
 421          if ($this->fetchMode !== FALSE) {
 422              $savem = $this->SetFetchMode(FALSE);
 423          }
 424  
 425          // get index details
 426          $table = strtoupper($table);
 427  
 428          // get Primary index
 429          $primary_key = '';
 430  
 431          $rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table));
 432          if (!is_object($rs)) {
 433              if (isset($savem)) {
 434                  $this->SetFetchMode($savem);
 435              }
 436              $ADODB_FETCH_MODE = $save;
 437              return false;
 438          }
 439  
 440          if ($row = $rs->FetchRow()) {
 441              $primary_key = $row[1]; //constraint_name
 442          }
 443  
 444          if ($primary==TRUE && $primary_key=='') {
 445              if (isset($savem)) {
 446                  $this->SetFetchMode($savem);
 447              }
 448              $ADODB_FETCH_MODE = $save;
 449              return false; //There is no primary key
 450          }
 451  
 452          $rs = $this->Execute(sprintf("SELECT ALL_INDEXES.INDEX_NAME, ALL_INDEXES.UNIQUENESS, ALL_IND_COLUMNS.COLUMN_POSITION, ALL_IND_COLUMNS.COLUMN_NAME FROM ALL_INDEXES,ALL_IND_COLUMNS WHERE UPPER(ALL_INDEXES.TABLE_NAME)='%s' AND ALL_IND_COLUMNS.INDEX_NAME=ALL_INDEXES.INDEX_NAME",$table));
 453  
 454  
 455          if (!is_object($rs)) {
 456              if (isset($savem)) {
 457                  $this->SetFetchMode($savem);
 458              }
 459              $ADODB_FETCH_MODE = $save;
 460              return false;
 461          }
 462  
 463          $indexes = array ();
 464          // parse index data into array
 465  
 466          while ($row = $rs->FetchRow()) {
 467              if ($primary && $row[0] != $primary_key) {
 468                  continue;
 469              }
 470              if (!isset($indexes[$row[0]])) {
 471                  $indexes[$row[0]] = array(
 472                      'unique' => ($row[1] == 'UNIQUE'),
 473                      'columns' => array()
 474                  );
 475              }
 476              $indexes[$row[0]]['columns'][$row[2] - 1] = $row[3];
 477          }
 478  
 479          // sort columns by order in the index
 480          foreach ( array_keys ($indexes) as $index ) {
 481              ksort ($indexes[$index]['columns']);
 482          }
 483  
 484          if (isset($savem)) {
 485              $this->SetFetchMode($savem);
 486              $ADODB_FETCH_MODE = $save;
 487          }
 488          return $indexes;
 489      }
 490  
 491  	function BeginTrans()
 492      {
 493          if ($this->transOff) {
 494              return true;
 495          }
 496          $this->transCnt += 1;
 497          $this->autoCommit = false;
 498          $this->_commit = OCI_DEFAULT;
 499  
 500          if ($this->_transmode) {
 501              $ok = $this->Execute("SET TRANSACTION ".$this->_transmode);
 502          }
 503          else {
 504              $ok = true;
 505          }
 506  
 507          return $ok ? true : false;
 508      }
 509  
 510  	function CommitTrans($ok=true)
 511      {
 512          if ($this->transOff) {
 513              return true;
 514          }
 515          if (!$ok) {
 516              return $this->RollbackTrans();
 517          }
 518  
 519          if ($this->transCnt) {
 520              $this->transCnt -= 1;
 521          }
 522          $ret = oci_commit($this->_connectionID);
 523          $this->_commit = OCI_COMMIT_ON_SUCCESS;
 524          $this->autoCommit = true;
 525          return $ret;
 526      }
 527  
 528  	function RollbackTrans()
 529      {
 530          if ($this->transOff) {
 531              return true;
 532          }
 533          if ($this->transCnt) {
 534              $this->transCnt -= 1;
 535          }
 536          $ret = oci_rollback($this->_connectionID);
 537          $this->_commit = OCI_COMMIT_ON_SUCCESS;
 538          $this->autoCommit = true;
 539          return $ret;
 540      }
 541  
 542  
 543  	function SelectDB($dbName)
 544      {
 545          return false;
 546      }
 547  
 548  	function ErrorMsg()
 549      {
 550          if ($this->_errorMsg !== false) {
 551              return $this->_errorMsg;
 552          }
 553  
 554          if (is_resource($this->_stmt)) {
 555              $arr = @oci_error($this->_stmt);
 556          }
 557          if (empty($arr)) {
 558              if (is_resource($this->_connectionID)) {
 559                  $arr = @oci_error($this->_connectionID);
 560              }
 561              else {
 562                  $arr = @oci_error();
 563              }
 564              if ($arr === false) {
 565                  return '';
 566              }
 567          }
 568          $this->_errorMsg = $arr['message'];
 569          $this->_errorCode = $arr['code'];
 570          return $this->_errorMsg;
 571      }
 572  
 573  	function ErrorNo()
 574      {
 575          if ($this->_errorCode !== false) {
 576              return $this->_errorCode;
 577          }
 578  
 579          if (is_resource($this->_stmt)) {
 580              $arr = @oci_error($this->_stmt);
 581          }
 582          if (empty($arr)) {
 583              $arr = @oci_error($this->_connectionID);
 584              if ($arr == false) {
 585                  $arr = @oci_error();
 586              }
 587              if ($arr == false) {
 588                  return '';
 589              }
 590          }
 591  
 592          $this->_errorMsg = $arr['message'];
 593          $this->_errorCode = $arr['code'];
 594  
 595          return $arr['code'];
 596      }
 597  
 598      /**
 599       * Format date column in sql string given an input format that understands Y M D
 600       */
 601  	function SQLDate($fmt, $col=false)
 602      {
 603          if (!$col) {
 604              $col = $this->sysTimeStamp;
 605          }
 606          $s = 'TO_CHAR('.$col.",'";
 607  
 608          $len = strlen($fmt);
 609          for ($i=0; $i < $len; $i++) {
 610              $ch = $fmt[$i];
 611              switch($ch) {
 612              case 'Y':
 613              case 'y':
 614                  $s .= 'YYYY';
 615                  break;
 616              case 'Q':
 617              case 'q':
 618                  $s .= 'Q';
 619                  break;
 620  
 621              case 'M':
 622                  $s .= 'Mon';
 623                  break;
 624  
 625              case 'm':
 626                  $s .= 'MM';
 627                  break;
 628              case 'D':
 629              case 'd':
 630                  $s .= 'DD';
 631                  break;
 632  
 633              case 'H':
 634                  $s.= 'HH24';
 635                  break;
 636  
 637              case 'h':
 638                  $s .= 'HH';
 639                  break;
 640  
 641              case 'i':
 642                  $s .= 'MI';
 643                  break;
 644  
 645              case 's':
 646                  $s .= 'SS';
 647                  break;
 648  
 649              case 'a':
 650              case 'A':
 651                  $s .= 'AM';
 652                  break;
 653  
 654              case 'w':
 655                  $s .= 'D';
 656                  break;
 657  
 658              case 'l':
 659                  $s .= 'DAY';
 660                  break;
 661  
 662              case 'W':
 663                  $s .= 'WW';
 664                  break;
 665  
 666              default:
 667                  // handle escape characters...
 668                  if ($ch == '\\') {
 669                      $i++;
 670                      $ch = substr($fmt,$i,1);
 671                  }
 672                  if (strpos('-/.:;, ',$ch) !== false) {
 673                      $s .= $ch;
 674                  }
 675                  else {
 676                      $s .= '"'.$ch.'"';
 677                  }
 678  
 679              }
 680          }
 681          return $s. "')";
 682      }
 683  
 684  	function GetRandRow($sql, $arr = false)
 685      {
 686          $sql = "SELECT * FROM ($sql ORDER BY dbms_random.value) WHERE rownum = 1";
 687  
 688          return $this->GetRow($sql,$arr);
 689      }
 690  
 691      /**
 692       * This algorithm makes use of
 693       *
 694       * a. FIRST_ROWS hint
 695       * The FIRST_ROWS hint explicitly chooses the approach to optimize response
 696       * time, that is, minimum resource usage to return the first row. Results
 697       * will be returned as soon as they are identified.
 698       *
 699       * b. Uses rownum tricks to obtain only the required rows from a given offset.
 700       * As this uses complicated sql statements, we only use this if $offset >= 100.
 701       * This idea by Tomas V V Cox.
 702       *
 703       * This implementation does not appear to work with oracle 8.0.5 or earlier.
 704       * Comment out this function then, and the slower SelectLimit() in the base
 705       * class will be used.
 706       *
 707       * Note: FIRST_ROWS hinting is only used if $sql is a string; when
 708       * processing a prepared statement's handle, no hinting is performed.
 709       */
 710  	function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
 711      {
 712          $nrows = (int) $nrows;
 713          $offset = (int) $offset;
 714          // Since the methods used to limit the number of returned rows rely
 715          // on modifying the provided SQL query, we can't work with prepared
 716          // statements so we just extract the SQL string.
 717          if(is_array($sql)) {
 718              $sql = $sql[0];
 719          }
 720  
 721          // seems that oracle only supports 1 hint comment in 8i
 722          if ($this->firstrows) {
 723              if ($nrows > 500 && $nrows < 1000) {
 724                  $hint = "FIRST_ROWS($nrows)";
 725              }
 726              else {
 727                  $hint = 'FIRST_ROWS';
 728              }
 729  
 730              if (strpos($sql,'/*+') !== false) {
 731                  $sql = str_replace('/*+ ',"/*+$hint ",$sql);
 732              }
 733              else {
 734                  $sql = preg_replace('/^[ \t\n]*select/i',"SELECT /*+$hint*/",$sql);
 735              }
 736              $hint = "/*+ $hint */";
 737          } else {
 738              $hint = '';
 739          }
 740  
 741          if ($offset == -1 || ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000)) {
 742              if ($nrows > 0) {
 743                  if ($offset > 0) {
 744                      $nrows += $offset;
 745                  }
 746                  $sql = "select * from (".$sql.") where rownum <= :adodb_offset";
 747                  $inputarr['adodb_offset'] = $nrows;
 748                  $nrows = -1;
 749              }
 750              // note that $nrows = 0 still has to work ==> no rows returned
 751  
 752              return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
 753          } else {
 754              // Algorithm by Tomas V V Cox, from PEAR DB oci8.php
 755  
 756              // Let Oracle return the name of the columns
 757              $q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL";
 758  
 759              if (! $stmt_arr = $this->Prepare($q_fields)) {
 760                  return false;
 761              }
 762              $stmt = $stmt_arr[1];
 763  
 764              if (is_array($inputarr)) {
 765                  foreach($inputarr as $k => $v) {
 766                      $i=0;
 767                      if ($this->databaseType == 'oci8po') {
 768                          $bv_name = ":".$i++;
 769                      } else {
 770                          $bv_name = ":".$k;
 771                      }
 772                      if (is_array($v)) {
 773                          // suggested by g.giunta@libero.
 774                          if (sizeof($v) == 2) {
 775                              oci_bind_by_name($stmt,$bv_name,$inputarr[$k][0],$v[1]);
 776                          }
 777                          else {
 778                              oci_bind_by_name($stmt,$bv_name,$inputarr[$k][0],$v[1],$v[2]);
 779                          }
 780                      } else {
 781                          $len = -1;
 782                          if ($v === ' ') {
 783                              $len = 1;
 784                          }
 785                          if (isset($bindarr)) {    // is prepared sql, so no need to oci_bind_by_name again
 786                              $bindarr[$k] = $v;
 787                          } else {                 // dynamic sql, so rebind every time
 788                              oci_bind_by_name($stmt,$bv_name,$inputarr[$k],$len);
 789                          }
 790                      }
 791                  }
 792              }
 793  
 794              if (!oci_execute($stmt, OCI_DEFAULT)) {
 795                  oci_free_statement($stmt);
 796                  return false;
 797              }
 798  
 799              $ncols = oci_num_fields($stmt);
 800              for ( $i = 1; $i <= $ncols; $i++ ) {
 801                  $cols[] = '"'.oci_field_name($stmt, $i).'"';
 802              }
 803              $result = false;
 804  
 805              oci_free_statement($stmt);
 806              $fields = implode(',', $cols);
 807              if ($nrows <= 0) {
 808                  $nrows = 999999999999;
 809              }
 810              else {
 811                  $nrows += $offset;
 812              }
 813              $offset += 1; // in Oracle rownum starts at 1
 814  
 815              $sql = "SELECT $hint $fields FROM".
 816                  "(SELECT rownum as adodb_rownum, $fields FROM".
 817                  " ($sql) WHERE rownum <= :adodb_nrows".
 818                  ") WHERE adodb_rownum >= :adodb_offset";
 819              $inputarr['adodb_nrows'] = $nrows;
 820              $inputarr['adodb_offset'] = $offset;
 821  
 822              if ($secs2cache > 0) {
 823                  $rs = $this->CacheExecute($secs2cache, $sql,$inputarr);
 824              }
 825              else {
 826                  $rs = $this->Execute($sql, $inputarr);
 827              }
 828              return $rs;
 829          }
 830      }
 831  
 832      /**
 833       * Usage:
 834       * Store BLOBs and CLOBs
 835       *
 836       * Example: to store $var in a blob
 837       *    $conn->Execute('insert into TABLE (id,ablob) values(12,empty_blob())');
 838       *    $conn->UpdateBlob('TABLE', 'ablob', $varHoldingBlob, 'ID=12', 'BLOB');
 839       *
 840       * $blobtype supports 'BLOB' and 'CLOB', but you need to change to 'empty_clob()'.
 841       *
 842       * to get length of LOB:
 843       *    select DBMS_LOB.GETLENGTH(ablob) from TABLE
 844       *
 845       * If you are using CURSOR_SHARING = force, it appears this will case a segfault
 846       * under oracle 8.1.7.0. Run:
 847       *    $db->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
 848       * before UpdateBlob() then...
 849       */
 850  	function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
 851      {
 852  
 853          //if (strlen($val) < 4000) return $this->Execute("UPDATE $table SET $column=:blob WHERE $where",array('blob'=>$val)) != false;
 854  
 855          switch(strtoupper($blobtype)) {
 856          default: ADOConnection::outp("<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
 857          case 'BLOB': $type = OCI_B_BLOB; break;
 858          case 'CLOB': $type = OCI_B_CLOB; break;
 859          }
 860  
 861          if ($this->databaseType == 'oci8po')
 862              $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
 863          else
 864              $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
 865  
 866          $desc = oci_new_descriptor($this->_connectionID, OCI_D_LOB);
 867          $arr['blob'] = array($desc,-1,$type);
 868          if ($this->session_sharing_force_blob) {
 869              $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT');
 870          }
 871          $commit = $this->autoCommit;
 872          if ($commit) {
 873              $this->BeginTrans();
 874          }
 875          $rs = $this->_Execute($sql,$arr);
 876          if ($rez = !empty($rs)) {
 877              $desc->save($val);
 878          }
 879          $desc->free();
 880          if ($commit) {
 881              $this->CommitTrans();
 882          }
 883          if ($this->session_sharing_force_blob) {
 884              $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE');
 885          }
 886  
 887          if ($rez) {
 888              $rs->Close();
 889          }
 890          return $rez;
 891      }
 892  
 893      /**
 894       * Usage:  store file pointed to by $val in a blob
 895       */
 896  	function UpdateBlobFile($table,$column,$val,$where,$blobtype='BLOB')
 897      {
 898          switch(strtoupper($blobtype)) {
 899          default: ADOConnection::outp( "<b>UpdateBlob</b>: Unknown blobtype=$blobtype"); return false;
 900          case 'BLOB': $type = OCI_B_BLOB; break;
 901          case 'CLOB': $type = OCI_B_CLOB; break;
 902          }
 903  
 904          if ($this->databaseType == 'oci8po')
 905              $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO ?";
 906          else
 907              $sql = "UPDATE $table set $column=EMPTY_{$blobtype}() WHERE $where RETURNING $column INTO :blob";
 908  
 909          $desc = oci_new_descriptor($this->_connectionID, OCI_D_LOB);
 910          $arr['blob'] = array($desc,-1,$type);
 911  
 912          $this->BeginTrans();
 913          $rs = ADODB_oci8::Execute($sql,$arr);
 914          if ($rez = !empty($rs)) {
 915              $desc->savefile($val);
 916          }
 917          $desc->free();
 918          $this->CommitTrans();
 919  
 920          if ($rez) {
 921              $rs->Close();
 922          }
 923          return $rez;
 924      }
 925  
 926      /**
 927       * Execute SQL
 928       *
 929       * @param sql        SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
 930       * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.
 931       * @return         RecordSet or false
 932       */
 933  	function Execute($sql,$inputarr=false)
 934      {
 935          if ($this->fnExecute) {
 936              $fn = $this->fnExecute;
 937              $ret = $fn($this,$sql,$inputarr);
 938              if (isset($ret)) {
 939                  return $ret;
 940              }
 941          }
 942          if ($inputarr !== false) {
 943              if (!is_array($inputarr)) {
 944                  $inputarr = array($inputarr);
 945              }
 946  
 947              $element0 = reset($inputarr);
 948              $array2d =  $this->bulkBind && is_array($element0) && !is_object(reset($element0));
 949  
 950              # see http://phplens.com/lens/lensforum/msgs.php?id=18786
 951              if ($array2d || !$this->_bindInputArray) {
 952  
 953                  # is_object check because oci8 descriptors can be passed in
 954                  if ($array2d && $this->_bindInputArray) {
 955                      if (is_string($sql)) {
 956                          $stmt = $this->Prepare($sql);
 957                      } else {
 958                          $stmt = $sql;
 959                      }
 960  
 961                      foreach($inputarr as $arr) {
 962                          $ret = $this->_Execute($stmt,$arr);
 963                          if (!$ret) {
 964                              return $ret;
 965                          }
 966                      }
 967                      return $ret;
 968                  } else {
 969                      $sqlarr = explode(':', $sql);
 970                      $sql = '';
 971                      $lastnomatch = -2;
 972                      #var_dump($sqlarr);echo "<hr>";var_dump($inputarr);echo"<hr>";
 973                      foreach($sqlarr as $k => $str) {
 974                          if ($k == 0) {
 975                              $sql = $str;
 976                              continue;
 977                          }
 978                          // we need $lastnomatch because of the following datetime,
 979                          // eg. '10:10:01', which causes code to think that there is bind param :10 and :1
 980                          $ok = preg_match('/^([0-9]*)/', $str, $arr);
 981  
 982                          if (!$ok) {
 983                              $sql .= $str;
 984                          } else {
 985                              $at = $arr[1];
 986                              if (isset($inputarr[$at]) || is_null($inputarr[$at])) {
 987                                  if ((strlen($at) == strlen($str) && $k < sizeof($arr)-1)) {
 988                                      $sql .= ':'.$str;
 989                                      $lastnomatch = $k;
 990                                  } else if ($lastnomatch == $k-1) {
 991                                      $sql .= ':'.$str;
 992                                  } else {
 993                                      if (is_null($inputarr[$at])) {
 994                                          $sql .= 'null';
 995                                      }
 996                                      else {
 997                                          $sql .= $this->qstr($inputarr[$at]);
 998                                      }
 999                                      $sql .= substr($str, strlen($at));
1000                                  }
1001                              } else {
1002                                  $sql .= ':'.$str;
1003                              }
1004                          }
1005                      }
1006                      $inputarr = false;
1007                  }
1008              }
1009              $ret = $this->_Execute($sql,$inputarr);
1010  
1011          } else {
1012              $ret = $this->_Execute($sql,false);
1013          }
1014  
1015          return $ret;
1016      }
1017  
1018      /*
1019       * Example of usage:
1020       *    $stmt = $this->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
1021      */
1022  	function Prepare($sql,$cursor=false)
1023      {
1024      static $BINDNUM = 0;
1025  
1026          $stmt = oci_parse($this->_connectionID,$sql);
1027  
1028          if (!$stmt) {
1029              $this->_errorMsg = false;
1030              $this->_errorCode = false;
1031              $arr = @oci_error($this->_connectionID);
1032              if ($arr === false) {
1033                  return false;
1034              }
1035  
1036              $this->_errorMsg = $arr['message'];
1037              $this->_errorCode = $arr['code'];
1038              return false;
1039          }
1040  
1041          $BINDNUM += 1;
1042  
1043          $sttype = @oci_statement_type($stmt);
1044          if ($sttype == 'BEGIN' || $sttype == 'DECLARE') {
1045              return array($sql,$stmt,0,$BINDNUM, ($cursor) ? oci_new_cursor($this->_connectionID) : false);
1046          }
1047          return array($sql,$stmt,0,$BINDNUM);
1048      }
1049  
1050      /*
1051          Call an oracle stored procedure and returns a cursor variable as a recordset.
1052          Concept by Robert Tuttle robert@ud.com
1053  
1054          Example:
1055              Note: we return a cursor variable in :RS2
1056              $rs = $db->ExecuteCursor("BEGIN adodb.open_tab(:RS2); END;",'RS2');
1057  
1058              $rs = $db->ExecuteCursor(
1059                  "BEGIN :RS2 = adodb.getdata(:VAR1); END;",
1060                  'RS2',
1061                  array('VAR1' => 'Mr Bean'));
1062  
1063      */
1064  	function ExecuteCursor($sql,$cursorName='rs',$params=false)
1065      {
1066          if (is_array($sql)) {
1067              $stmt = $sql;
1068          }
1069          else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate oci_new_cursor
1070  
1071          if (is_array($stmt) && sizeof($stmt) >= 5) {
1072              $hasref = true;
1073              $ignoreCur = false;
1074              $this->Parameter($stmt, $ignoreCur, $cursorName, false, -1, OCI_B_CURSOR);
1075              if ($params) {
1076                  foreach($params as $k => $v) {
1077                      $this->Parameter($stmt,$params[$k], $k);
1078                  }
1079              }
1080          } else
1081              $hasref = false;
1082  
1083          $rs = $this->Execute($stmt);
1084          if ($rs) {
1085              if ($rs->databaseType == 'array') {
1086                  oci_free_cursor($stmt[4]);
1087              }
1088              elseif ($hasref) {
1089                  $rs->_refcursor = $stmt[4];
1090              }
1091          }
1092          return $rs;
1093      }
1094  
1095      /**
1096       * Bind a variable -- very, very fast for executing repeated statements in oracle.
1097       *
1098       * Better than using
1099       *    for ($i = 0; $i < $max; $i++) {
1100       *        $p1 = ?; $p2 = ?; $p3 = ?;
1101       *        $this->Execute("insert into table (col0, col1, col2) values (:0, :1, :2)", array($p1,$p2,$p3));
1102       *    }
1103       *
1104       * Usage:
1105       *    $stmt = $DB->Prepare("insert into table (col0, col1, col2) values (:0, :1, :2)");
1106       *    $DB->Bind($stmt, $p1);
1107       *    $DB->Bind($stmt, $p2);
1108       *    $DB->Bind($stmt, $p3);
1109       *    for ($i = 0; $i < $max; $i++) {
1110       *        $p1 = ?; $p2 = ?; $p3 = ?;
1111       *        $DB->Execute($stmt);
1112       *    }
1113       *
1114       * Some timings to insert 1000 records, test table has 3 cols, and 1 index.
1115       * - Time 0.6081s (1644.60 inserts/sec) with direct oci_parse/oci_execute
1116       * - Time 0.6341s (1577.16 inserts/sec) with ADOdb Prepare/Bind/Execute
1117       * - Time 1.5533s ( 643.77 inserts/sec) with pure SQL using Execute
1118       *
1119       * Now if PHP only had batch/bulk updating like Java or PL/SQL...
1120       *
1121       * Note that the order of parameters differs from oci_bind_by_name,
1122       * because we default the names to :0, :1, :2
1123       */
1124  	function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false,$isOutput=false)
1125      {
1126  
1127          if (!is_array($stmt)) {
1128              return false;
1129          }
1130  
1131          if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) {
1132              return oci_bind_by_name($stmt[1],":".$name,$stmt[4],$size,$type);
1133          }
1134  
1135          if ($name == false) {
1136              if ($type !== false) {
1137                  $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size,$type);
1138              }
1139              else {
1140                  $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator
1141              }
1142              $stmt[2] += 1;
1143          } else if (oci_lob_desc($type)) {
1144              if ($this->debug) {
1145                  ADOConnection::outp("<b>Bind</b>: name = $name");
1146              }
1147              //we have to create a new Descriptor here
1148              $numlob = count($this->_refLOBs);
1149              $this->_refLOBs[$numlob]['LOB'] = oci_new_descriptor($this->_connectionID, oci_lob_desc($type));
1150              $this->_refLOBs[$numlob]['TYPE'] = $isOutput;
1151  
1152              $tmp = $this->_refLOBs[$numlob]['LOB'];
1153              $rez = oci_bind_by_name($stmt[1], ":".$name, $tmp, -1, $type);
1154              if ($this->debug) {
1155                  ADOConnection::outp("<b>Bind</b>: descriptor has been allocated, var (".$name.") binded");
1156              }
1157  
1158              // if type is input then write data to lob now
1159              if ($isOutput == false) {
1160                  $var = $this->BlobEncode($var);
1161                  $tmp->WriteTemporary($var);
1162                  $this->_refLOBs[$numlob]['VAR'] = &$var;
1163                  if ($this->debug) {
1164                      ADOConnection::outp("<b>Bind</b>: LOB has been written to temp");
1165                  }
1166              } else {
1167                  $this->_refLOBs[$numlob]['VAR'] = &$var;
1168              }
1169              $rez = $tmp;
1170          } else {
1171              if ($this->debug)
1172                  ADOConnection::outp("<b>Bind</b>: name = $name");
1173  
1174              if ($type !== false) {
1175                  $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size,$type);
1176              }
1177              else {
1178                  $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size); // +1 byte for null terminator
1179              }
1180          }
1181  
1182          return $rez;
1183      }
1184  
1185  	function Param($name,$type='C')
1186      {
1187          return ':'.$name;
1188      }
1189  
1190      /**
1191       * Usage:
1192       *    $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
1193       *    $db->Parameter($stmt,$id,'myid');
1194       *    $db->Parameter($stmt,$group,'group');
1195       *    $db->Execute($stmt);
1196       *
1197       * @param $stmt Statement returned by Prepare() or PrepareSP().
1198       * @param $var PHP variable to bind to
1199       * @param $name Name of stored procedure variable name to bind to.
1200       * @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
1201       * @param [$maxLen] Holds an maximum length of the variable.
1202       * @param [$type] The data type of $var. Legal values depend on driver.
1203       *
1204       * @link http://php.net/oci_bind_by_name
1205      */
1206  	function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
1207      {
1208              if  ($this->debug) {
1209                  $prefix = ($isOutput) ? 'Out' : 'In';
1210                  $ztype = (empty($type)) ? 'false' : $type;
1211                  ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
1212              }
1213              return $this->Bind($stmt,$var,$maxLen,$type,$name,$isOutput);
1214      }
1215  
1216      /**
1217       * returns query ID if successful, otherwise false
1218       * this version supports:
1219       *
1220       * 1. $db->execute('select * from table');
1221       *
1222       * 2. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
1223       *    $db->execute($prepared_statement, array(1,2,3));
1224       *
1225       * 3. $db->execute('insert into table (a,b,c) values (:a,:b,:c)',array('a'=>1,'b'=>2,'c'=>3));
1226       *
1227       * 4. $db->prepare('insert into table (a,b,c) values (:0,:1,:2)');
1228       *    $db->bind($stmt,1); $db->bind($stmt,2); $db->bind($stmt,3);
1229       *    $db->execute($stmt);
1230       */
1231  	function _query($sql,$inputarr=false)
1232      {
1233          if (is_array($sql)) { // is prepared sql
1234              $stmt = $sql[1];
1235  
1236              // we try to bind to permanent array, so that oci_bind_by_name is persistent
1237              // and carried out once only - note that max array element size is 4000 chars
1238              if (is_array($inputarr)) {
1239                  $bindpos = $sql[3];
1240                  if (isset($this->_bind[$bindpos])) {
1241                  // all tied up already
1242                      $bindarr = $this->_bind[$bindpos];
1243                  } else {
1244                  // one statement to bind them all
1245                      $bindarr = array();
1246                      foreach($inputarr as $k => $v) {
1247                          $bindarr[$k] = $v;
1248                          oci_bind_by_name($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000);
1249                      }
1250                      $this->_bind[$bindpos] = $bindarr;
1251                  }
1252              }
1253          } else {
1254              $stmt=oci_parse($this->_connectionID,$sql);
1255          }
1256  
1257          $this->_stmt = $stmt;
1258          if (!$stmt) {
1259              return false;
1260          }
1261  
1262          if (defined('ADODB_PREFETCH_ROWS')) {
1263              @oci_set_prefetch($stmt,ADODB_PREFETCH_ROWS);
1264          }
1265  
1266          if (is_array($inputarr)) {
1267              foreach($inputarr as $k => $v) {
1268                  if (is_array($v)) {
1269                      // suggested by g.giunta@libero.
1270                      if (sizeof($v) == 2) {
1271                          oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1]);
1272                      }
1273                      else {
1274                          oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);
1275                      }
1276  
1277                      if ($this->debug==99) {
1278                          if (is_object($v[0])) {
1279                              echo "name=:$k",' len='.$v[1],' type='.$v[2],'<br>';
1280                          }
1281                          else {
1282                              echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';
1283                          }
1284  
1285                      }
1286                  } else {
1287                      $len = -1;
1288                      if ($v === ' ') {
1289                          $len = 1;
1290                      }
1291                      if (isset($bindarr)) {    // is prepared sql, so no need to oci_bind_by_name again
1292                          $bindarr[$k] = $v;
1293                      } else {                 // dynamic sql, so rebind every time
1294                          oci_bind_by_name($stmt,":$k",$inputarr[$k],$len);
1295                      }
1296                  }
1297              }
1298          }
1299  
1300          $this->_errorMsg = false;
1301          $this->_errorCode = false;
1302          if (oci_execute($stmt,$this->_commit)) {
1303  
1304              if (count($this -> _refLOBs) > 0) {
1305  
1306                  foreach ($this -> _refLOBs as $key => $value) {
1307                      if ($this -> _refLOBs[$key]['TYPE'] == true) {
1308                          $tmp = $this -> _refLOBs[$key]['LOB'] -> load();
1309                          if ($this -> debug) {
1310                              ADOConnection::outp("<b>OUT LOB</b>: LOB has been loaded. <br>");
1311                          }
1312                          //$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp;
1313                          $this -> _refLOBs[$key]['VAR'] = $tmp;
1314                      } else {
1315                          $this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']);
1316                          $this -> _refLOBs[$key]['LOB']->free();
1317                          unset($this -> _refLOBs[$key]);
1318                          if ($this->debug) {
1319                              ADOConnection::outp("<b>IN LOB</b>: LOB has been saved. <br>");
1320                          }
1321                      }
1322                  }
1323              }
1324  
1325              switch (@oci_statement_type($stmt)) {
1326                  case "SELECT":
1327                      return $stmt;
1328  
1329                  case 'DECLARE':
1330                  case "BEGIN":
1331                      if (is_array($sql) && !empty($sql[4])) {
1332                          $cursor = $sql[4];
1333                          if (is_resource($cursor)) {
1334                              $ok = oci_execute($cursor);
1335                              return $cursor;
1336                          }
1337                          return $stmt;
1338                      } else {
1339                          if (is_resource($stmt)) {
1340                              oci_free_statement($stmt);
1341                              return true;
1342                          }
1343                          return $stmt;
1344                      }
1345                      break;
1346                  default :
1347  
1348                      return true;
1349              }
1350          }
1351          return false;
1352      }
1353  
1354      // From Oracle Whitepaper: PHP Scalability and High Availability
1355  	function IsConnectionError($err)
1356      {
1357          switch($err) {
1358              case 378: /* buffer pool param incorrect */
1359              case 602: /* core dump */
1360              case 603: /* fatal error */
1361              case 609: /* attach failed */
1362              case 1012: /* not logged in */
1363              case 1033: /* init or shutdown in progress */
1364              case 1043: /* Oracle not available */
1365              case 1089: /* immediate shutdown in progress */
1366              case 1090: /* shutdown in progress */
1367              case 1092: /* instance terminated */
1368              case 3113: /* disconnect */
1369              case 3114: /* not connected */
1370              case 3122: /* closing window */
1371              case 3135: /* lost contact */
1372              case 12153: /* TNS: not connected */
1373              case 27146: /* fatal or instance terminated */
1374              case 28511: /* Lost RPC */
1375              return true;
1376          }
1377          return false;
1378      }
1379  
1380      // returns true or false
1381  	function _close()
1382      {
1383          if (!$this->_connectionID) {
1384              return;
1385          }
1386  
1387  
1388          if (!$this->autoCommit) {
1389              oci_rollback($this->_connectionID);
1390          }
1391          if (count($this->_refLOBs) > 0) {
1392              foreach ($this ->_refLOBs as $key => $value) {
1393                  $this->_refLOBs[$key]['LOB']->free();
1394                  unset($this->_refLOBs[$key]);
1395              }
1396          }
1397          oci_close($this->_connectionID);
1398  
1399          $this->_stmt = false;
1400          $this->_connectionID = false;
1401      }
1402  
1403  	function MetaPrimaryKeys($table, $owner=false,$internalKey=false)
1404      {
1405          if ($internalKey) {
1406              return array('ROWID');
1407          }
1408  
1409          // tested with oracle 8.1.7
1410          $table = strtoupper($table);
1411          if ($owner) {
1412              $owner_clause = "AND ((a.OWNER = b.OWNER) AND (a.OWNER = UPPER('$owner')))";
1413              $ptab = 'ALL_';
1414          } else {
1415              $owner_clause = '';
1416              $ptab = 'USER_';
1417          }
1418          $sql = "
1419  SELECT /*+ RULE */ distinct b.column_name
1420     FROM {$ptab}CONSTRAINTS a
1421        , {$ptab}CONS_COLUMNS b
1422    WHERE ( UPPER(b.table_name) = ('$table'))
1423      AND (UPPER(a.table_name) = ('$table') and a.constraint_type = 'P')
1424      $owner_clause
1425      AND (a.constraint_name = b.constraint_name)";
1426  
1427          $rs = $this->Execute($sql);
1428          if ($rs && !$rs->EOF) {
1429              $arr = $rs->GetArray();
1430              $a = array();
1431              foreach($arr as $v) {
1432                  $a[] = reset($v);
1433              }
1434              return $a;
1435          }
1436          else return false;
1437      }
1438  
1439      /**
1440       * returns assoc array where keys are tables, and values are foreign keys
1441       *
1442       * @param    str        $table
1443       * @param    str        $owner    [optional][default=NULL]
1444       * @param    bool    $upper    [optional][discarded]
1445       * @return    mixed[]            Array of foreign key information
1446       *
1447       * @link http://gis.mit.edu/classes/11.521/sqlnotes/referential_integrity.html
1448       */
1449  	function MetaForeignKeys($table, $owner=false, $upper=false)
1450      {
1451          global $ADODB_FETCH_MODE;
1452  
1453          $save = $ADODB_FETCH_MODE;
1454          $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
1455          $table = $this->qstr(strtoupper($table));
1456          if (!$owner) {
1457              $owner = $this->user;
1458              $tabp = 'user_';
1459          } else
1460              $tabp = 'all_';
1461  
1462          $owner = ' and owner='.$this->qstr(strtoupper($owner));
1463  
1464          $sql =
1465  "select constraint_name,r_owner,r_constraint_name
1466      from {$tabp}constraints
1467      where constraint_type = 'R' and table_name = $table $owner";
1468  
1469          $constraints = $this->GetArray($sql);
1470          $arr = false;
1471          foreach($constraints as $constr) {
1472              $cons = $this->qstr($constr[0]);
1473              $rowner = $this->qstr($constr[1]);
1474              $rcons = $this->qstr($constr[2]);
1475              $cols = $this->GetArray("select column_name from {$tabp}cons_columns where constraint_name=$cons $owner order by position");
1476              $tabcol = $this->GetArray("select table_name,column_name from {$tabp}cons_columns where owner=$rowner and constraint_name=$rcons order by position");
1477  
1478              if ($cols && $tabcol)
1479                  for ($i=0, $max=sizeof($cols); $i < $max; $i++) {
1480                      $arr[$tabcol[$i][0]] = $cols[$i][0].'='.$tabcol[$i][1];
1481                  }
1482          }
1483          $ADODB_FETCH_MODE = $save;
1484  
1485          return $arr;
1486      }
1487  
1488  
1489  	function CharMax()
1490      {
1491          return 4000;
1492      }
1493  
1494  	function TextMax()
1495      {
1496          return 4000;
1497      }
1498  
1499      /**
1500       * Quotes a string.
1501       * An example is  $db->qstr("Don't bother",magic_quotes_runtime());
1502       *
1503       * @param string $s the string to quote
1504       * @param bool $magic_quotes if $s is GET/POST var, set to get_magic_quotes_gpc().
1505       *             This undoes the stupidity of magic quotes for GPC.
1506       *
1507       * @return string quoted string to be sent back to database
1508       */
1509  	function qstr($s,$magic_quotes=false)
1510      {
1511          //$nofixquotes=false;
1512  
1513          if ($this->noNullStrings && strlen($s)==0) {
1514              $s = ' ';
1515          }
1516          if (!$magic_quotes) {
1517              if ($this->replaceQuote[0] == '\\'){
1518                  $s = str_replace('\\','\\\\',$s);
1519              }
1520              return  "'".str_replace("'",$this->replaceQuote,$s)."'";
1521          }
1522  
1523          // undo magic quotes for " unless sybase is on
1524          if (!ini_get('magic_quotes_sybase')) {
1525              $s = str_replace('\\"','"',$s);
1526              $s = str_replace('\\\\','\\',$s);
1527              return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
1528          } else {
1529              return "'".$s."'";
1530          }
1531      }
1532  
1533  }
1534  
1535  /*--------------------------------------------------------------------------------------
1536      Class Name: Recordset
1537  --------------------------------------------------------------------------------------*/
1538  
1539  class ADORecordset_oci8 extends ADORecordSet {
1540  
1541      var $databaseType = 'oci8';
1542      var $bind=false;
1543      var $_fieldobjs;
1544  
1545  	function __construct($queryID,$mode=false)
1546      {
1547          if ($mode === false) {
1548              global $ADODB_FETCH_MODE;
1549              $mode = $ADODB_FETCH_MODE;
1550          }
1551          switch ($mode) {
1552              case ADODB_FETCH_ASSOC:
1553                  $this->fetchMode = OCI_ASSOC;
1554                  break;
1555              case ADODB_FETCH_DEFAULT:
1556              case ADODB_FETCH_BOTH:
1557                  $this->fetchMode = OCI_NUM + OCI_ASSOC;
1558                  break;
1559              case ADODB_FETCH_NUM:
1560              default:
1561                  $this->fetchMode = OCI_NUM;
1562                  break;
1563          }
1564          $this->fetchMode += OCI_RETURN_NULLS + OCI_RETURN_LOBS;
1565          $this->adodbFetchMode = $mode;
1566          $this->_queryID = $queryID;
1567      }
1568      
1569      /**
1570      * Overrides the core destructor method as that causes problems here
1571      *
1572      * @return void
1573      */
1574  	function __destruct() {}
1575  
1576  	function Init()
1577      {
1578          if ($this->_inited) {
1579              return;
1580          }
1581  
1582          $this->_inited = true;
1583          if ($this->_queryID) {
1584  
1585              $this->_currentRow = 0;
1586              @$this->_initrs();
1587              if ($this->_numOfFields) {
1588                  $this->EOF = !$this->_fetch();
1589              }
1590              else $this->EOF = true;
1591  
1592              /*
1593              // based on idea by Gaetano Giunta to detect unusual oracle errors
1594              // see http://phplens.com/lens/lensforum/msgs.php?id=6771
1595              $err = oci_error($this->_queryID);
1596              if ($err && $this->connection->debug) {
1597                  ADOConnection::outp($err);
1598              }
1599              */
1600  
1601              if (!is_array($this->fields)) {
1602                  $this->_numOfRows = 0;
1603                  $this->fields = array();
1604              }
1605          } else {
1606              $this->fields = array();
1607              $this->_numOfRows = 0;
1608              $this->_numOfFields = 0;
1609              $this->EOF = true;
1610          }
1611      }
1612  
1613  	function _initrs()
1614      {
1615          $this->_numOfRows = -1;
1616          $this->_numOfFields = oci_num_fields($this->_queryID);
1617          if ($this->_numOfFields>0) {
1618              $this->_fieldobjs = array();
1619              $max = $this->_numOfFields;
1620              for ($i=0;$i<$max; $i++) $this->_fieldobjs[] = $this->_FetchField($i);
1621          }
1622      }
1623  
1624      /**
1625       * Get column information in the Recordset object.
1626       * fetchField() can be used in order to obtain information about fields
1627       * in a certain query result. If the field offset isn't specified, the next
1628       * field that wasn't yet retrieved by fetchField() is retrieved
1629       *
1630       * @return object containing field information
1631       */
1632  	function _FetchField($fieldOffset = -1)
1633      {
1634          $fld = new ADOFieldObject;
1635          $fieldOffset += 1;
1636          $fld->name =oci_field_name($this->_queryID, $fieldOffset);
1637          if (ADODB_ASSOC_CASE == ADODB_ASSOC_CASE_LOWER) {
1638              $fld->name = strtolower($fld->name);
1639          }
1640          $fld->type = oci_field_type($this->_queryID, $fieldOffset);
1641          $fld->max_length = oci_field_size($this->_queryID, $fieldOffset);
1642  
1643          switch($fld->type) {
1644              case 'NUMBER':
1645                  $p = oci_field_precision($this->_queryID, $fieldOffset);
1646                  $sc = oci_field_scale($this->_queryID, $fieldOffset);
1647                  if ($p != 0 && $sc == 0) {
1648                      $fld->type = 'INT';
1649                  }
1650                  $fld->scale = $p;
1651                  break;
1652  
1653              case 'CLOB':
1654              case 'NCLOB':
1655              case 'BLOB':
1656                  $fld->max_length = -1;
1657                  break;
1658          }
1659          return $fld;
1660      }
1661  
1662      /* For some reason, oci_field_name fails when called after _initrs() so we cache it */
1663  	function FetchField($fieldOffset = -1)
1664      {
1665          return $this->_fieldobjs[$fieldOffset];
1666      }
1667  
1668  
1669  	function MoveNext()
1670      {
1671          if ($this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) {
1672              $this->_currentRow += 1;
1673              $this->_updatefields();
1674              return true;
1675          }
1676          if (!$this->EOF) {
1677              $this->_currentRow += 1;
1678              $this->EOF = true;
1679          }
1680          return false;
1681      }
1682  
1683      // Optimize SelectLimit() by using oci_fetch()
1684  	function GetArrayLimit($nrows,$offset=-1)
1685      {
1686          if ($offset <= 0) {
1687              $arr = $this->GetArray($nrows);
1688              return $arr;
1689          }
1690          $arr = array();
1691          for ($i=1; $i < $offset; $i++) {
1692              if (!@oci_fetch($this->_queryID)) {
1693                  return $arr;
1694              }
1695          }
1696  
1697          if (!$this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) {
1698              return $arr;
1699          }
1700          $this->_updatefields();
1701          $results = array();
1702          $cnt = 0;
1703          while (!$this->EOF && $nrows != $cnt) {
1704              $results[$cnt++] = $this->fields;
1705              $this->MoveNext();
1706          }
1707  
1708          return $results;
1709      }
1710  
1711  
1712      // Use associative array to get fields array
1713  	function Fields($colname)
1714      {
1715          if (!$this->bind) {
1716              $this->bind = array();
1717              for ($i=0; $i < $this->_numOfFields; $i++) {
1718                  $o = $this->FetchField($i);
1719                  $this->bind[strtoupper($o->name)] = $i;
1720              }
1721          }
1722  
1723          return $this->fields[$this->bind[strtoupper($colname)]];
1724      }
1725  
1726  
1727  	function _seek($row)
1728      {
1729          return false;
1730      }
1731  
1732  	function _fetch()
1733      {
1734          $this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode);
1735          $this->_updatefields();
1736  
1737          return $this->fields;
1738      }
1739  
1740      /**
1741       * close() only needs to be called if you are worried about using too much
1742       * memory while your script is running. All associated result memory for the
1743       * specified result identifier will automatically be freed.
1744       */
1745  	function _close()
1746      {
1747          if ($this->connection->_stmt === $this->_queryID) {
1748              $this->connection->_stmt = false;
1749          }
1750          if (!empty($this->_refcursor)) {
1751              oci_free_cursor($this->_refcursor);
1752              $this->_refcursor = false;
1753          }
1754          @oci_free_statement($this->_queryID);
1755          $this->_queryID = false;
1756      }
1757  
1758      /**
1759       * not the fastest implementation - quick and dirty - jlim
1760       * for best performance, use the actual $rs->MetaType().
1761       *
1762       * @param    mixed    $t
1763       * @param    int        $len        [optional] Length of blobsize
1764       * @param    bool    $fieldobj    [optional][discarded]
1765       * @return    str                    The metatype of the field
1766       */
1767  	function MetaType($t, $len=-1, $fieldobj=false)
1768      {
1769          if (is_object($t)) {
1770              $fieldobj = $t;
1771              $t = $fieldobj->type;
1772              $len = $fieldobj->max_length;
1773          }
1774  
1775          switch (strtoupper($t)) {
1776          case 'VARCHAR':
1777          case 'VARCHAR2':
1778          case 'CHAR':
1779          case 'VARBINARY':
1780          case 'BINARY':
1781          case 'NCHAR':
1782          case 'NVARCHAR':
1783          case 'NVARCHAR2':
1784              if ($len <= $this->blobSize) {
1785                  return 'C';
1786              }
1787  
1788          case 'NCLOB':
1789          case 'LONG':
1790          case 'LONG VARCHAR':
1791          case 'CLOB':
1792          return 'X';
1793  
1794          case 'LONG RAW':
1795          case 'LONG VARBINARY':
1796          case 'BLOB':
1797              return 'B';
1798  
1799          case 'DATE':
1800              return  ($this->connection->datetime) ? 'T' : 'D';
1801  
1802  
1803          case 'TIMESTAMP': return 'T';
1804  
1805          case 'INT':
1806          case 'SMALLINT':
1807          case 'INTEGER':
1808              return 'I';
1809  
1810          default:
1811              return 'N';
1812          }
1813      }
1814  }
1815  
1816  class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 {
1817  	function __construct($queryID,$mode=false)
1818      {
1819          parent::__construct($queryID, $mode);
1820      }
1821  
1822  	function MoveNext()
1823      {
1824          return adodb_movenext($this);
1825      }
1826  }


Generated: Wed Jan 22 11:59:49 2025 Cross-referenced by PHPXref 0.7.1