Subversion Repositories oidplus

Rev

Rev 1389 | 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.         /**
  28.          * @var mixed|null
  29.          */
  30.         private $conn = null;
  31.  
  32.         /**
  33.          * @var string|null
  34.          */
  35.         private $last_error = null; // do the same like MySQL+PDO, just to be equal in the behavior
  36.  
  37.         /**
  38.          * @var bool
  39.          */
  40.         private $transactions_supported = false;
  41.  
  42.         /**
  43.          * @return bool|null
  44.          * @throws OIDplusException
  45.          */
  46.         protected function forcePrepareEmulation() {
  47.                 $mode = OIDplus::baseConfig()->getValue('PREPARED_STATEMENTS_EMULATION', 'auto');
  48.                 if ($mode === 'on') return true;
  49.                 if ($mode === 'off') return false;
  50.  
  51.                 static $res = null;
  52.                 if (is_null($res)) {
  53.                         $sql = 'select name from ###config where name = ?';
  54.                         $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
  55.                         $res = @odbc_prepare($this->conn, $sql) === false;
  56.                 }
  57.  
  58.                 return $res;
  59.         }
  60.  
  61.         /**
  62.          * @var array
  63.          */
  64.         private $prepare_cache = [];
  65.  
  66.         /**
  67.          * @param string $sql
  68.          * @param array|null $prepared_args
  69.          * @return OIDplusQueryResultODBC
  70.          * @throws OIDplusConfigInitializationException
  71.          * @throws OIDplusException
  72.          * @throws OIDplusSQLException
  73.          */
  74.         protected function doQueryInternalPrepare(string $sql, array $prepared_args=null): OIDplusQueryResultODBC {
  75.                 foreach ($prepared_args as &$value) {
  76.                         // ODBC/SQLServer has problems converting "true" to the data type "bit"
  77.                         // Error "Invalid character value for cast specification"
  78.                         if (is_bool($value)) {
  79.                                 if ($this->slangDetectionDone) {
  80.                                         $value = $this->getSlang()->getSQLBool($value);
  81.                                 } else {
  82.                                         $value = $value ? '1' : '0';
  83.                                 }
  84.                         }
  85.                 }
  86.                 unset($value);
  87.  
  88.                 if (isset($this->prepare_cache[$sql])) {
  89.                         $ps = $this->prepare_cache[$sql];
  90.                 } else {
  91.                         $ps = @odbc_prepare($this->conn, $sql);
  92.                         if (!$ps) $ps = false; // because null will result in isset()=false
  93.                         $this->prepare_cache[$sql] = $ps;
  94.                 }
  95.                 if (!$ps) {
  96.                         // If preparation fails, try the emulation
  97.                         // For example, SQL Server ODBC Driver cannot have "?" in a subquery,
  98.                         // otherwise you receive the error message
  99.                         // "Syntax error or access violation" on odbc_prepare()
  100.                         return $this->doQueryPrepareEmulation($sql, $prepared_args);
  101.                         /*
  102.                         $this->last_error = odbc_errormsg($this->conn);
  103.                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  104.                         */
  105.                 }
  106.  
  107.                 if (!@odbc_execute($ps, $prepared_args)) {
  108.                         $this->last_error = odbc_errormsg($this->conn);
  109.                         throw new OIDplusSQLException($sql.' mit Args '.print_r($prepared_args,true), $this->error());
  110.                 }
  111.                 return new OIDplusQueryResultODBC($ps);
  112.         }
  113.  
  114.         /**
  115.          * @param string $sql
  116.          * @param array|null $prepared_args
  117.          * @return OIDplusQueryResultODBC
  118.          * @throws OIDplusConfigInitializationException
  119.          * @throws OIDplusException
  120.          * @throws OIDplusSQLException
  121.          */
  122.         protected function doQueryPrepareEmulation(string $sql, array $prepared_args=null): OIDplusQueryResultODBC {
  123.                 // For some drivers (e.g. Microsoft Access), we need to do this kind of emulation, because odbc_prepare() does not work
  124.                 $dummy = find_nonexisting_substr($sql);
  125.                 $sql = str_replace('?', $dummy, $sql);
  126.                 foreach ($prepared_args as $arg) {
  127.                         $needle = $dummy;
  128.                         if (is_bool($arg)) {
  129.                                 if ($this->slangDetectionDone) {
  130.                                         $replace = $this->getSlang()->getSQLBool($arg);
  131.                                 } else {
  132.                                         $replace = $arg ? '1' : '0';
  133.                                 }
  134.                         } else if (is_int($arg)) {
  135.                                 $replace = $arg;
  136.                         } else if (is_float($arg)) {
  137.                                 $replace = number_format($arg, 10, '.', '');
  138.                         } else if (is_null($arg)) {
  139.                                 $replace = 'NULL';
  140.                         } else {
  141.                                 // TODO: More types?
  142.                                 // Note: Actually, the strings should be N'...' instead of '...',
  143.                                 //       but since Unicode does not work with ODBC, it does not make a difference
  144.                                 if ($this->slangDetectionDone) {
  145.                                         $replace = "'".$this->getSlang()->escapeString($arg)."'";
  146.                                 } else {
  147.                                         $replace = "'".str_replace("'", "''", $arg)."'";
  148.                                 }
  149.                         }
  150.                         $pos = strpos($sql, $needle);
  151.                         if ($pos !== false) {
  152.                                 $sql = substr_replace($sql, $replace, $pos, strlen($needle));
  153.                         }
  154.                 }
  155.                 $sql = str_replace($dummy, '?', $sql);
  156.                 $ps = @odbc_exec($this->conn, $sql);
  157.                 if (!$ps) {
  158.                         $this->last_error = odbc_errormsg($this->conn);
  159.                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  160.                 }
  161.                 return new OIDplusQueryResultODBC($ps);
  162.         }
  163.  
  164.         /**
  165.          * @param string $sql
  166.          * @param array|null $prepared_args
  167.          * @return OIDplusQueryResultODBC
  168.          * @throws OIDplusException
  169.          */
  170.         public function doQuery(string $sql, array $prepared_args=null): OIDplusQueryResult {
  171.                 $this->last_error = null;
  172.                 if (is_null($prepared_args)) {
  173.                         $res = @odbc_exec($this->conn, $sql);
  174.  
  175.                         if ($res === false) {
  176.                                 $this->last_error = odbc_errormsg($this->conn);
  177.                                 throw new OIDplusSQLException($sql, $this->error());
  178.                         } else {
  179.                                 return new OIDplusQueryResultODBC($res);
  180.                         }
  181.                 } else {
  182.                         if ($this->forcePrepareEmulation()) {
  183.                                 return $this->doQueryPrepareEmulation($sql, $prepared_args);
  184.                         } else {
  185.                                 return $this->doQueryInternalPrepare($sql, $prepared_args);
  186.                         }
  187.                 }
  188.         }
  189.  
  190.         /**
  191.          * @return string
  192.          */
  193.         public function error(): string {
  194.                 $err = $this->last_error;
  195.                 if ($err == null) $err = '';
  196.                 return vts_utf8_encode($err); // UTF-8 encode, because ODBC might output weird stuff ...
  197.         }
  198.  
  199.         /**
  200.          * @return void
  201.          * @throws OIDplusConfigInitializationException
  202.          * @throws OIDplusException
  203.          */
  204.         protected function doConnect()/*: void*/ {
  205.                 if (!function_exists('odbc_connect')) throw new OIDplusConfigInitializationException(_L('PHP extension "%1" not installed','ODBC'));
  206.  
  207.                 // Try connecting to the database
  208.                 $dsn      = OIDplus::baseConfig()->getValue('ODBC_DSN',      'DRIVER={SQL Server};SERVER=localhost;DATABASE=oidplus');
  209.                 $username = OIDplus::baseConfig()->getValue('ODBC_USERNAME', '');
  210.                 $password = OIDplus::baseConfig()->getValue('ODBC_PASSWORD', '');
  211.  
  212.                 // Try to extend DSN with charset
  213.                 // Note: For MySQL, must be utf8mb4 or utf8, and not UTF-8
  214.                 if (stripos($dsn,"charset=") === false) {
  215.                         $this->conn = odbc_connect("$dsn;charset=utf8mb4", $username, $password);
  216.                         if (!$this->conn) $this->conn = odbc_connect("$dsn;charset=utf8", $username, $password);
  217.                         if (!$this->conn) $this->conn = odbc_connect("$dsn;charset=UTF-8", $username, $password);
  218.                         if (!$this->conn) $this->conn = odbc_connect($dsn, $username, $password);
  219.                 } else {
  220.                         $this->conn = odbc_connect($dsn, $username, $password);
  221.                 }
  222.  
  223.                 if (!$this->conn) {
  224.                         $message = odbc_errormsg();
  225.                         $message = vts_utf8_encode($message); // Make UTF-8 if it is NOT already UTF-8. Important for German Microsoft Access.
  226.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' '.$message));
  227.                 }
  228.  
  229.                 $this->last_error = null;
  230.  
  231.                 try {
  232.                         @odbc_exec($this->conn, "SET NAMES 'UTF-8'"); // Does most likely NOT work with ODBC. Try adding ";CHARSET=UTF8" (or similar) to the DSN
  233.                 } catch (\Exception $e) {
  234.                 }
  235.  
  236.                 try {
  237.                         @odbc_exec($this->conn, "SET CHARACTER SET 'UTF-8'"); // Does most likely NOT work with ODBC. Try adding ";CHARSET=UTF8" (or similar) to the DSN
  238.                 } catch (\Exception $e) {
  239.                 }
  240.  
  241.                 try {
  242.                         @odbc_exec($this->conn, "SET NAMES 'utf8mb4'"); // Does most likely NOT work with ODBC. Try adding ";CHARSET=UTF8" (or similar) to the DSN
  243.                 } catch (\Exception $e) {
  244.                 }
  245.  
  246.                 // We check if the DBMS supports autocommit.
  247.                 // Attention: Check it after you have sent a query already, because Microsoft Access doesn't seem to allow
  248.                 // changing auto commit once a query was executed ("Attribute cannot be set now SQLState: S1011")
  249.                 // Note: For some weird reason we *DO* need to redirect the output to "$dummy", otherwise it won't work!
  250.                 $sql = "select name from ###config where 1=0";
  251.                 $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
  252.                 $dummy = @odbc_exec($this->conn, $sql);
  253.                 $this->transactions_supported = @odbc_autocommit($this->conn, false);
  254.                 @odbc_autocommit($this->conn, true);
  255.         }
  256.  
  257.         /**
  258.          * @return void
  259.          */
  260.         protected function doDisconnect()/*: void*/ {
  261.                 if (!is_null($this->conn)) {
  262.                         @odbc_close($this->conn);
  263.                         $this->conn = null;
  264.                 }
  265.         }
  266.  
  267.         /**
  268.          * @var bool
  269.          */
  270.         private $intransaction = false;
  271.  
  272.         /**
  273.          * @return bool
  274.          */
  275.         public function transaction_supported(): bool {
  276.                 return $this->transactions_supported;
  277.         }
  278.  
  279.         /**
  280.          * @return int
  281.          */
  282.         public function transaction_level(): int {
  283.                 if (!$this->transaction_supported()) {
  284.                         // TODO?
  285.                         return 0;
  286.                 }
  287.                 return $this->intransaction ? 1 : 0;
  288.         }
  289.  
  290.         /**
  291.          * @return void
  292.          * @throws OIDplusException
  293.          */
  294.         public function transaction_begin()/*: void*/ {
  295.                 if (!$this->transaction_supported()) {
  296.                         // TODO?
  297.                         return;
  298.                 }
  299.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  300.                 odbc_autocommit($this->conn, false); // begin transaction
  301.                 $this->intransaction = true;
  302.         }
  303.  
  304.         /**
  305.          * @return void
  306.          */
  307.         public function transaction_commit()/*: void*/ {
  308.                 if (!$this->transaction_supported()) {
  309.                         // TODO?
  310.                         return;
  311.                 }
  312.                 odbc_commit($this->conn);
  313.                 odbc_autocommit($this->conn, true);
  314.                 $this->intransaction = false;
  315.         }
  316.  
  317.         /**
  318.          * @return void
  319.          */
  320.         public function transaction_rollback()/*: void*/ {
  321.                 if (!$this->transaction_supported()) {
  322.                         // TODO?
  323.                         return;
  324.                 }
  325.                 odbc_rollback($this->conn);
  326.                 odbc_autocommit($this->conn, true);
  327.                 $this->intransaction = false;
  328.         }
  329.  
  330.         /**
  331.          * @return array
  332.          */
  333.         public function getExtendedInfo(): array {
  334.                 $dsn = OIDplus::baseConfig()->getValue('ODBC_DSN', 'DRIVER={SQL Server};SERVER=localhost;DATABASE=oidplus;CHARSET=UTF8');
  335.                 $dsn = preg_replace('@(Password|PWD)=(.+);@ismU', '('._L('redacted').');', $dsn);
  336.                 return array(
  337.                         _L('DSN') => $dsn
  338.                 );
  339.         }
  340.  
  341. }
  342.