Subversion Repositories oidplus

Rev

Rev 1050 | Rev 1116 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  *     http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  */
  19.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusDatabaseConnectionODBC extends OIDplusDatabaseConnection {
  27.         private $conn;
  28.         private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
  29.         private $transactions_supported = false;
  30.  
  31.         protected function forcePrepareEmulation() {
  32.                 $mode = OIDplus::baseConfig()->getValue('PREPARED_STATEMENTS_EMULATION', 'auto');
  33.                 if ($mode === 'on') return true;
  34.                 if ($mode === 'off') return false;
  35.  
  36.                 static $res = null;
  37.                 if (is_null($res)) {
  38.                         $sql = 'select name from ###config where name = ?';
  39.                         $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
  40.                         $res = @odbc_prepare($this->conn, $sql) === false;
  41.                 }
  42.  
  43.                 return $res;
  44.         }
  45.  
  46.         protected function doQueryInternalPrepare(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
  47.                                 foreach ($prepared_args as &$value) {
  48.                                         // ODBC/SQLServer has problems converting "true" to the data type "bit"
  49.                                         // Error "Invalid character value for cast specification"
  50.                                         if (is_bool($value)) {
  51.                                                 if ($this->slangDetectionDone) {
  52.                                                         $value = $this->getSlang()->getSQLBool($value);
  53.                                                 } else {
  54.                                                         $value = $value ? '1' : '0';
  55.                                                 }
  56.                                         }
  57.                                 }
  58.  
  59.                                 $ps = @odbc_prepare($this->conn, $sql);
  60.                                 if (!$ps) {
  61.                                         // If preparation fails, try the emulation
  62.                                         // For example, SQL Server ODBC Driver cannot have "?" in a subquery,
  63.                                         // otherwise you receive the error message
  64.                                         // "Syntax error or access violation" on odbc_prepare()
  65.                                         return $this->doQueryPrepareEmulation($sql, $prepared_args);
  66.                                         /*
  67.                                         $this->last_error = odbc_errormsg($this->conn);
  68.                                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  69.                                         */
  70.                                 }
  71.  
  72.                                 if (!@odbc_execute($ps, $prepared_args)) {
  73.                                         $this->last_error = odbc_errormsg($this->conn);
  74.                                         throw new OIDplusSQLException($sql, $this->error());
  75.                                 }
  76.                                 return new OIDplusQueryResultODBC($ps);
  77.  
  78.         }
  79.  
  80.         protected function doQueryPrepareEmulation(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
  81.                                 // For some drivers (e.g. Microsoft Access), we need to do this kind of emulation, because odbc_prepare() does not work
  82.                                 $sql = str_replace('?', chr(1), $sql);
  83.                                 foreach ($prepared_args as $arg) {
  84.                                         $needle = chr(1);
  85.                                         if (is_bool($arg)) {
  86.                                                 if ($this->slangDetectionDone) {
  87.                                                         $replace = $this->getSlang()->getSQLBool($arg);
  88.                                                 } else {
  89.                                                         $replace = $arg ? '1' : '0';
  90.                                                 }
  91.                                         } else {
  92.                                                 if ($this->slangDetectionDone) {
  93.                                                         $replace = "'".$this->getSlang()->escapeString($arg)."'"; // TODO: types
  94.                                                 } else {
  95.                                                         $replace = "'".str_replace("'", "''", $arg)."'"; // TODO: types
  96.                                                 }
  97.                                         }
  98.                                         $pos = strpos($sql, $needle);
  99.                                         if ($pos !== false) {
  100.                                                 $sql = substr_replace($sql, $replace, $pos, strlen($needle));
  101.                                         }
  102.                                 }
  103.                                 $sql = str_replace(chr(1), '?', $sql);
  104.                                 $ps = @odbc_exec($this->conn, $sql);
  105.                                 if (!$ps) {
  106.                                         $this->last_error = odbc_errormsg($this->conn);
  107.                                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  108.                                 }
  109.                                 return new OIDplusQueryResultODBC($ps);
  110.         }
  111.  
  112.         public function doQuery(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
  113.                 $this->last_error = null;
  114.                 if (is_null($prepared_args)) {
  115.                         $res = @odbc_exec($this->conn, $sql);
  116.  
  117.                         if ($res === false) {
  118.                                 $this->last_error = odbc_errormsg($this->conn);
  119.                                 throw new OIDplusSQLException($sql, $this->error());
  120.                         } else {
  121.                                 return new OIDplusQueryResultODBC($res);
  122.                         }
  123.                 } else {
  124.                         if (!is_array($prepared_args)) {
  125.                                 throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
  126.                         }
  127.  
  128.                         if ($this->forcePrepareEmulation()) {
  129.                                 return $this->doQueryPrepareEmulation($sql, $prepared_args);
  130.                         } else {
  131.                                 return $this->doQueryInternalPrepare($sql, $prepared_args);
  132.                         }
  133.                 }
  134.         }
  135.  
  136.         public function error(): string {
  137.                 $err = $this->last_error;
  138.                 if ($err == null) $err = '';
  139.                 $err = vts_utf8_encode($err); // because ODBC might output weird stuff ...
  140.                 return $err;
  141.         }
  142.  
  143.         protected function doConnect()/*: void*/ {
  144.                 if (!function_exists('odbc_connect')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','ODBC'));
  145.  
  146.                 // Try connecting to the database
  147.                 $dsn      = OIDplus::baseConfig()->getValue('ODBC_DSN',      'DRIVER={SQL Server};SERVER=localhost;DATABASE=oidplus;CHARSET=UTF8');
  148.                 $username = OIDplus::baseConfig()->getValue('ODBC_USERNAME', '');
  149.                 $password = OIDplus::baseConfig()->getValue('ODBC_PASSWORD', '');
  150.                 $this->conn = @odbc_connect($dsn, $username, $password);
  151.  
  152.                 if (!$this->conn) {
  153.                         $message = odbc_errormsg();
  154.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' '.$message));
  155.                 }
  156.  
  157.                 $this->last_error = null;
  158.  
  159.                 try {
  160.                         @odbc_exec($this->conn, "SET NAMES 'utf8'"); // Does most likely NOT work with ODBC. Try adding ";CHARSET=UTF8" (or similar) to the DSN
  161.                 } catch (\Exception $e) {
  162.                 }
  163.  
  164.                 // We check if the DBMS supports autocommit.
  165.                 // Attention: Check it after you have sent a query already, because Microsoft Access doesn't seem to allow
  166.                 // changing auto commit once a query was executed ("Attribute cannot be set now SQLState: S1011")
  167.                 // Note: For some weird reason we *DO* need to redirect the output to "$dummy", otherwise it won't work!
  168.                 $sql = "select name from ###config where 1=0";
  169.                 $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
  170.                 $dummy = @odbc_exec($this->conn, $sql);
  171.                 $this->transactions_supported = @odbc_autocommit($this->conn, false);
  172.                 @odbc_autocommit($this->conn, true);
  173.         }
  174.  
  175.         protected function doDisconnect()/*: void*/ {
  176.                 if (!is_null($this->conn)) {
  177.                         @odbc_close($this->conn);
  178.                         $this->conn = null;
  179.                 }
  180.         }
  181.  
  182.         private $intransaction = false;
  183.  
  184.         public function transaction_supported(): bool {
  185.                 return $this->transactions_supported;
  186.         }
  187.  
  188.         public function transaction_level(): int {
  189.                 if (!$this->transaction_supported()) {
  190.                         // TODO?
  191.                         return 0;
  192.                 }
  193.                 return $this->intransaction ? 1 : 0;
  194.         }
  195.  
  196.         public function transaction_begin()/*: void*/ {
  197.                 if (!$this->transaction_supported()) {
  198.                         // TODO?
  199.                         return;
  200.                 }
  201.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  202.                 odbc_autocommit($this->conn, false); // begin transaction
  203.                 $this->intransaction = true;
  204.         }
  205.  
  206.         public function transaction_commit()/*: void*/ {
  207.                 if (!$this->transaction_supported()) {
  208.                         // TODO?
  209.                         return;
  210.                 }
  211.                 odbc_commit($this->conn);
  212.                 odbc_autocommit($this->conn, true);
  213.                 $this->intransaction = false;
  214.         }
  215.  
  216.         public function transaction_rollback()/*: void*/ {
  217.                 if (!$this->transaction_supported()) {
  218.                         // TODO?
  219.                         return;
  220.                 }
  221.                 odbc_rollback($this->conn);
  222.                 odbc_autocommit($this->conn, true);
  223.                 $this->intransaction = false;
  224.         }
  225. }
  226.