Subversion Repositories oidplus

Rev

Rev 1214 | Rev 1220 | 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 OIDplusDatabaseConnectionMySQLi extends OIDplusDatabaseConnection {
  27.  
  28.         /**
  29.          * @var mixed|null
  30.          */
  31.         private $conn = null; // only with MySQLnd
  32.  
  33.         /**
  34.          * @var array
  35.          */
  36.         private $prepare_cache = array();
  37.  
  38.         /**
  39.          * @var string|null
  40.          */
  41.         private $last_error = null; // we need that because MySQL divides prepared statement errors and normal query errors, but we have only one "error()" method
  42.  
  43.         /**
  44.          * @param string $sql
  45.          * @param array|null $prepared_args
  46.          * @return OIDplusQueryResultMySQL|OIDplusQueryResultMySQLNoNativeDriver
  47.          * @throws OIDplusException
  48.          */
  49.         public function doQuery(string $sql, array $prepared_args=null): OIDplusQueryResult {
  50.                 $this->last_error = null;
  51.                 if (is_null($prepared_args)) {
  52.                         try {
  53.                                 $res = $this->conn->query($sql, MYSQLI_STORE_RESULT);
  54.                         } catch (\Exception $e) {
  55.                                 $this->last_error = $e->getMessage();
  56.                                 throw new OIDplusSQLException($sql, $e->getMessage());
  57.                         }
  58.  
  59.                         if ($res === false) {
  60.                                 $this->last_error = $this->conn->error;
  61.                                 throw new OIDplusSQLException($sql, $this->error());
  62.                         } else {
  63.                                 return new OIDplusQueryResultMySQL($res);
  64.                         }
  65.                 } else {
  66.                         foreach ($prepared_args as &$value) {
  67.                                 // MySQLi has problems converting "true/false" to the data type "tinyint(1)"
  68.                                 // It seems to be the same issue as in PDO reported 14 years ago at https://bugs.php.net/bug.php?id=57157
  69.                                 if (is_bool($value)) $value = $value ? '1' : '0';
  70.                         }
  71.  
  72.                         if (isset($this->prepare_cache[$sql])) {
  73.                                 $ps = $this->prepare_cache[$sql];
  74.                         } else {
  75.                                 try {
  76.                                         $ps = $this->conn->prepare($sql);
  77.                                 } catch (\Exception $e) {
  78.                                         $this->last_error = $e->getMessage();
  79.                                         throw new OIDplusSQLException($sql, $e->getMessage());
  80.                                 }
  81.                                 if (!$ps) {
  82.                                         $this->last_error = $this->conn->error;
  83.                                         throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
  84.                                 }
  85.  
  86.                                 // Caching the prepared is very risky
  87.                                 // In PDO and ODBC we may not do it, because execute() will
  88.                                 // destroy the existing cursors.
  89.                                 // (test this with ./?goto=oid%3A1.3.6.1.4.1.37553.8.32488192274
  90.                                 // you will see that 2.999 is missing in the tree)
  91.                                 // But $ps->get_result() seems to "clone" the cursor,
  92.                                 // so that $ps->execute may be called a second time?!
  93.                                 // However, it only works with mysqlnd's get_result,
  94.                                 // not with OIDplusQueryResultMySQLNoNativeDriver
  95.                                 if (self::nativeDriverAvailable()) {
  96.                                         $this->prepare_cache[$sql] = $ps;
  97.                                 }
  98.                         }
  99.  
  100.                         self::bind_placeholder_vars($ps,$prepared_args);
  101.                         if (!$ps->execute()) {
  102.                                 $this->last_error = mysqli_stmt_error($ps);
  103.                                 throw new OIDplusSQLException($sql, $this->error());
  104.                         }
  105.  
  106.                         if (self::nativeDriverAvailable()) {
  107.                                 return new OIDplusQueryResultMySQL($ps->get_result());
  108.                         } else {
  109.                                 return new OIDplusQueryResultMySQLNoNativeDriver($ps);
  110.                         }
  111.                 }
  112.         }
  113.  
  114.         /**
  115.          * @return int
  116.          */
  117.         public function doInsertId(): int {
  118.                 return $this->conn->insert_id;
  119.         }
  120.  
  121.         /**
  122.          * @return string
  123.          */
  124.         public function error(): string {
  125.                 $err = $this->last_error;
  126.                 if ($err === null) $err = '';
  127.                 return $err;
  128.         }
  129.  
  130.         /**
  131.          * @return void
  132.          * @throws OIDplusConfigInitializationException
  133.          * @throws OIDplusException
  134.          */
  135.         protected function doConnect()/*: void*/ {
  136.                 if (!function_exists('mysqli_connect')) throw new OIDplusException(_L('PHP extension "%1" not installed','MySQLi'));
  137.  
  138.                 // Try connecting to the database
  139.                 $host     = OIDplus::baseConfig()->getValue('MYSQL_HOST',     'localhost');
  140.                 $username = OIDplus::baseConfig()->getValue('MYSQL_USERNAME', 'root');
  141.                 $password = OIDplus::baseConfig()->getValue('MYSQL_PASSWORD', '');
  142.                 $database = OIDplus::baseConfig()->getValue('MYSQL_DATABASE', 'oidplus');
  143.                 $socket   = OIDplus::baseConfig()->getValue('MYSQL_SOCKET',   '');
  144.                 list($hostname,$port) = explode(':', $host.':'.ini_get("mysqli.default_port"));
  145.                 $port = intval($port);
  146.                 $this->conn = @new \mysqli($hostname, $username, $password, $database, $port, $socket);
  147.                 if (!empty($this->conn->connect_error) || ($this->conn->connect_errno != 0)) {
  148.                         $message = $this->conn->connect_error;
  149.                         throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' '.$message));
  150.                 }
  151.  
  152.                 $this->prepare_cache = array();
  153.                 $this->last_error = null;
  154.  
  155.                 $this->query("SET NAMES 'utf8mb4'");
  156.         }
  157.  
  158.         /**
  159.          * @return void
  160.          */
  161.         protected function doDisconnect()/*: void*/ {
  162.                 $this->prepare_cache = array();
  163.                 if (!is_null($this->conn)) {
  164.                         $this->conn->close();
  165.                         $this->conn = null;
  166.                 }
  167.         }
  168.  
  169.         /**
  170.          * @var bool
  171.          */
  172.         private $intransaction = false;
  173.  
  174.         /**
  175.          * @return bool
  176.          */
  177.         public function transaction_supported(): bool {
  178.                 return true;
  179.         }
  180.  
  181.         /**
  182.          * @return int
  183.          */
  184.         public function transaction_level(): int {
  185.                 return $this->intransaction ? 1 : 0;
  186.         }
  187.  
  188.         /**
  189.          * @return void
  190.          * @throws OIDplusException
  191.          */
  192.         public function transaction_begin()/*: void*/ {
  193.                 if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
  194.                 $this->conn->autocommit(false);
  195.                 $this->conn->begin_transaction();
  196.                 $this->intransaction = true;
  197.         }
  198.  
  199.         /**
  200.          * @return void
  201.          */
  202.         public function transaction_commit()/*: void*/ {
  203.                 $this->conn->commit();
  204.                 $this->conn->autocommit(true);
  205.                 $this->intransaction = false;
  206.         }
  207.  
  208.         /**
  209.          * @return void
  210.          */
  211.         public function transaction_rollback()/*: void*/ {
  212.                 $this->conn->rollback();
  213.                 $this->conn->autocommit(true);
  214.                 $this->intransaction = false;
  215.         }
  216.  
  217.         /**
  218.          * @return string
  219.          */
  220.         public function sqlDate(): string {
  221.                 return 'now()';
  222.         }
  223.  
  224.         /**
  225.          * @return bool
  226.          * @throws OIDplusException
  227.          */
  228.         public static function nativeDriverAvailable(): bool {
  229.                 return function_exists('mysqli_fetch_all') && (OIDplus::baseConfig()->getValue('MYSQL_FORCE_MYSQLND_SUPPLEMENT', false) === false);
  230.         }
  231.  
  232.         /**
  233.          * @param object $stmt
  234.          * @param array $params
  235.          * @return bool
  236.          */
  237.         private static function bind_placeholder_vars(&$stmt, array $params): bool {
  238.                 // Note: "object" is not a type-hint!
  239.                 // Credit to: Dave Morgan
  240.                 // Code taken from: http://www.devmorgan.com/blog/2009/03/27/dydl-part-3-dynamic-binding-with-mysqli-php/
  241.                 //                  https://stackoverflow.com/questions/17219214/how-to-bind-in-mysqli-dynamically
  242.                 if ($params != null) {
  243.                         $types = '';                        //initial sting with types
  244.                         foreach ($params as $param) {        //for each element, determine type and add
  245.                                 if (is_int($param)) {
  246.                                         $types .= 'i';              //integer
  247.                                 } elseif (is_float($param)) {
  248.                                         $types .= 'd';              //double
  249.                                 } elseif (is_string($param)) {
  250.                                         $types .= 's';              //string
  251.                                 } else {
  252.                                         $types .= 'b';              //blob and unknown
  253.                                 }
  254.                         }
  255.  
  256.                         $bind_names = array();
  257.                         $bind_names[] = $types;             //first param needed is the type string, e.g.: 'issss'
  258.  
  259.                         for ($i=0; $i<count($params);$i++) {    //go through incoming params and added em to array
  260.                                 $bind_name = 'bind' . $i;       //give them an arbitrary name
  261.                                 $$bind_name = $params[$i];      //add the parameter to the variable variable
  262.                                 $bind_names[] = &$$bind_name;   //now associate the variable as an element in an array
  263.                         }
  264.  
  265.                         //error_log("better_mysqli has params ".print_r($bind_names, 1));
  266.                         //call the function bind_param with dynamic params
  267.                         call_user_func_array(array($stmt,'bind_param'),$bind_names);
  268.                         return true;
  269.                 } else {
  270.                         return false;
  271.                 }
  272.         }
  273.  
  274.         /**
  275.          * @param bool $mustExist
  276.          * @return OIDplusSqlSlangPlugin|null
  277.          * @throws OIDplusConfigInitializationException
  278.          */
  279.         protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
  280.                 $slang = OIDplus::getSqlSlangPlugin('mysql');
  281.                 if (is_null($slang)) {
  282.                         throw new OIDplusConfigInitializationException(_L('SQL-Slang plugin "%1" is missing. Please check if it exists in the directory "plugin/sqlSlang". If it is not existing, please recover it from an SVN snapshot or OIDplus TAR.GZ file.','mysql'));
  283.                 }
  284.                 return $slang;
  285.         }
  286. }
  287.