Subversion Repositories oidplus

Rev

Rev 863 | Rev 1086 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
635 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
5
 * Copyright 2019 - 2021 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
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
635 daniel-mar 21
 
22
class OIDplusDatabaseConnectionMySQLi extends OIDplusDatabaseConnection {
23
        private $conn = null; // only with MySQLnd
24
        private $prepare_cache = array();
25
        private $last_error = null; // we need that because MySQL divides prepared statement errors and normal query errors, but we have only one "error()" method
26
 
27
        public function doQuery(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
28
                $this->last_error = null;
29
                if (is_null($prepared_args)) {
30
                        $res = $this->conn->query($sql, MYSQLI_STORE_RESULT);
31
 
32
                        if ($res === false) {
33
                                $this->last_error = $this->conn->error;
34
                                throw new OIDplusSQLException($sql, $this->error());
35
                        } else {
36
                                return new OIDplusQueryResultMySQL($res);
37
                        }
38
                } else {
39
                        if (!is_array($prepared_args)) {
40
                                throw new OIDplusException(_L('"prepared_args" must be either NULL or an ARRAY.'));
41
                        }
42
 
43
                        foreach ($prepared_args as &$value) {
44
                                // MySQLi has problems converting "true/false" to the data type "tinyint(1)"
45
                                // It seems to be the same issue like in PDO reported 14 years ago at https://bugs.php.net/bug.php?id=57157
46
                                if (is_bool($value)) $value = $value ? '1' : '0';
47
                        }
48
 
49
                        if (isset($this->prepare_cache[$sql])) {
50
                                $ps = $this->prepare_cache[$sql];
51
                        } else {
52
                                $ps = $this->conn->prepare($sql);
53
                                if (!$ps) {
54
                                        $this->last_error = $this->conn->error;
55
                                        throw new OIDplusSQLException($sql, _L('Cannot prepare statement').': '.$this->error());
56
                                }
57
 
58
                                // Caching the prepared is very risky
59
                                // In PDO and ODBC we may not do it, because execute() will
60
                                // destroy the existing cursors.
61
                                // (test this with ./?goto=oid%3A1.3.6.1.4.1.37553.8.32488192274
62
                                // you will see that 2.999 is missing in the tree)
63
                                // But $ps->get_result() seems to "clone" the cursor,
64
                                // so that $ps->execute may be called a second time?!
65
                                // However, it only works with mysqlnd's get_result,
66
                                // not with OIDplusQueryResultMySQLNoNativeDriver
67
                                if (self::nativeDriverAvailable()) {
68
                                        $this->prepare_cache[$sql] = $ps;
69
                                }
70
                        }
71
 
72
                        self::bind_placeholder_vars($ps,$prepared_args);
73
                        if (!$ps->execute()) {
74
                                $this->last_error = mysqli_stmt_error($ps);
75
                                throw new OIDplusSQLException($sql, $this->error());
76
                        }
77
 
78
                        if (self::nativeDriverAvailable()) {
79
                                return new OIDplusQueryResultMySQL($ps->get_result());
80
                        } else {
81
                                return new OIDplusQueryResultMySQLNoNativeDriver($ps);
82
                        }
83
                }
84
        }
85
 
86
        public function insert_id(): int {
87
                return $this->conn->insert_id;
88
        }
89
 
90
        public function error(): string {
91
                $err = $this->last_error;
92
                if ($err == null) $err = '';
93
                return $err;
94
        }
95
 
96
        protected function doConnect()/*: void*/ {
97
                if (!function_exists('mysqli_connect')) throw new OIDplusException(_L('PHP extension "%1" not installed','MySQLi'));
98
 
99
                // Try connecting to the database
100
                $host     = OIDplus::baseConfig()->getValue('MYSQL_HOST',     'localhost');
101
                $username = OIDplus::baseConfig()->getValue('MYSQL_USERNAME', 'root');
102
                $password = OIDplus::baseConfig()->getValue('MYSQL_PASSWORD', '');
103
                $database = OIDplus::baseConfig()->getValue('MYSQL_DATABASE', 'oidplus');
813 daniel-mar 104
                $socket   = OIDplus::baseConfig()->getValue('MYSQL_SOCKET',   '');
635 daniel-mar 105
                list($hostname,$port) = explode(':', $host.':'.ini_get("mysqli.default_port"));
106
                $port = intval($port);
1050 daniel-mar 107
                $this->conn = @new \mysqli($hostname, $username, $password, $database, $port, $socket);
635 daniel-mar 108
                if (!empty($this->conn->connect_error) || ($this->conn->connect_errno != 0)) {
109
                        $message = $this->conn->connect_error;
863 daniel-mar 110
                        throw new OIDplusConfigInitializationException(trim(_L('Connection to the database failed!').' '.$message));
635 daniel-mar 111
                }
112
 
113
                $this->prepare_cache = array();
114
                $this->last_error = null;
115
 
116
                $this->query("SET NAMES 'utf8'");
117
        }
118
 
119
        protected function doDisconnect()/*: void*/ {
120
                $this->prepare_cache = array();
121
                if (!is_null($this->conn)) {
122
                        $this->conn->close();
123
                        $this->conn = null;
124
                }
125
        }
126
 
127
        private $intransaction = false;
128
 
129
        public function transaction_supported(): bool {
130
                return true;
131
        }
132
 
133
        public function transaction_level(): int {
134
                return $this->intransaction ? 1 : 0;
135
        }
136
 
137
        public function transaction_begin()/*: void*/ {
138
                if ($this->intransaction) throw new OIDplusException(_L('Nested transactions are not supported by this database plugin.'));
139
                $this->conn->autocommit(false);
140
                $this->conn->begin_transaction();
141
                $this->intransaction = true;
142
        }
143
 
144
        public function transaction_commit()/*: void*/ {
145
                $this->conn->commit();
146
                $this->conn->autocommit(true);
147
                $this->intransaction = false;
148
        }
149
 
150
        public function transaction_rollback()/*: void*/ {
151
                $this->conn->rollback();
152
                $this->conn->autocommit(true);
153
                $this->intransaction = false;
154
        }
155
 
156
        public function sqlDate(): string {
157
                return 'now()';
158
        }
159
 
160
        public static function nativeDriverAvailable(): bool {
161
                return function_exists('mysqli_fetch_all') && (OIDplus::baseConfig()->getValue('MYSQL_FORCE_MYSQLND_SUPPLEMENT', false) === false);
162
        }
163
 
164
        private static function bind_placeholder_vars(&$stmt,$params): bool {
165
                // Credit to: Dave Morgan
166
                // Code taken from: http://www.devmorgan.com/blog/2009/03/27/dydl-part-3-dynamic-binding-with-mysqli-php/
167
                //                  https://stackoverflow.com/questions/17219214/how-to-bind-in-mysqli-dynamically
168
                if ($params != null) {
169
                        $types = '';                        //initial sting with types
170
                        foreach ($params as $param) {        //for each element, determine type and add
171
                                if (is_int($param)) {
172
                                        $types .= 'i';              //integer
173
                                } elseif (is_float($param)) {
174
                                        $types .= 'd';              //double
175
                                } elseif (is_string($param)) {
176
                                        $types .= 's';              //string
177
                                } else {
178
                                        $types .= 'b';              //blob and unknown
179
                                }
180
                        }
181
 
182
                        $bind_names = array();
183
                        $bind_names[] = $types;             //first param needed is the type string, e.g.: 'issss'
184
 
185
                        for ($i=0; $i<count($params);$i++) {    //go through incoming params and added em to array
186
                                $bind_name = 'bind' . $i;       //give them an arbitrary name
187
                                $$bind_name = $params[$i];      //add the parameter to the variable variable
188
                                $bind_names[] = &$$bind_name;   //now associate the variable as an element in an array
189
                        }
190
 
191
                        //error_log("better_mysqli has params ".print_r($bind_names, 1));
192
                        //call the function bind_param with dynamic params
193
                        call_user_func_array(array($stmt,'bind_param'),$bind_names);
194
                        return true;
195
                } else {
196
                        return false;
197
                }
198
        }
199
 
200
        protected function doGetSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
201
                $slang = OIDplus::getSqlSlangPlugin('mysql');
202
                if (is_null($slang)) {
203
                        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'));
204
                }
205
                return $slang;
206
        }
207
}