Subversion Repositories oidplus

Rev

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

Rev Author Line No. Line
295 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
5
 * Copyright 2019 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
abstract class OIDplusDatabaseConnection {
21
        protected /*bool*/ $connected = false;
22
        protected /*?bool*/ $html = null;
23
        protected /*?string*/ $last_query = null;
316 daniel-mar 24
        private /*?OIDplusSqlSlangPlugin*/ $slang = null;
295 daniel-mar 25
 
26
        protected abstract function doQuery(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult;
27
        public abstract function error(): string;
28
        public abstract function transaction_begin()/*: void*/;
29
        public abstract function transaction_commit()/*: void*/;
30
        public abstract function transaction_rollback()/*: void*/;
31
        public abstract function transaction_supported(): bool;
32
        public abstract function transaction_level(): int;
33
        protected abstract function doConnect()/*: void*/;
34
        protected abstract function doDisconnect()/*: void*/;
35
 
36
        public function insert_id(): int {
37
                // This is the "fallback" variant. If your database provider (e.g. PDO) supports
38
                // a function to detect the last inserted id, please override this
39
                // function in order to use that specialized function (since it is usually
40
                // more reliable).
316 daniel-mar 41
                return $this->getSlang()->insert_id($this);
295 daniel-mar 42
        }
43
 
44
        public final function query(string $sql, /*?array*/ $prepared_args=null): OIDplusQueryResult {
45
 
46
                $query_logfile = OIDplus::baseConfig()->getValue('QUERY_LOGFILE', '');
47
                if (!empty($query_logfile)) {
48
                        $ts = explode(" ",microtime());
49
                        $ts = date("Y-m-d H:i:s",$ts[1]).substr((string)$ts[0],1,4);
50
                        static $log_session_id = "";
51
                        if (empty($log_session_id)) {
52
                                $log_session_id = rand(10000,99999);
53
                        }
54
                        $file = isset($_SERVER['REQUEST_URI']) ? ' | '.$_SERVER['REQUEST_URI'] : '';
55
                        file_put_contents($query_logfile, "$ts <$log_session_id$file> $sql\n", FILE_APPEND);
56
                }
57
 
58
                $this->last_query = $sql;
59
                $sql = str_replace('###', OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', ''), $sql);
60
                return $this->doQuery($sql, $prepared_args);
61
        }
62
 
63
        public final function connect()/*: void*/ {
64
                if ($this->connected) return;
65
                $this->beforeConnect();
66
                $this->doConnect();
67
                $this->connected = true;
68
                register_shutdown_function(array($this, 'disconnect'));
69
                $this->afterConnect();
70
        }
71
 
72
        public final function disconnect()/*: void*/ {
73
                if (!$this->connected) return;
74
                $this->beforeDisconnect();
75
                $this->doDisconnect();
76
                $this->connected = false;
77
                $this->afterDisconnect();
78
        }
79
 
80
        public function natOrder($fieldname, $order='asc'): string {
81
                if (!is_null($this->slang)) {
82
                        return $this->slang->natOrder($fieldname, $order);
83
                } else {
84
                        $order = strtolower($order);
85
                        if (($order != 'asc') && ($order != 'desc')) {
86
                                throw new OIDplusException("Invalid order '$order' (needs to be 'asc' or 'desc')");
87
                        }
88
 
89
                        // For (yet) unsupported DBMS, we do not offer natural sort
90
                        return "$fieldname $order";
91
                }
92
        }
93
 
94
        protected function beforeDisconnect()/*: void*/ {}
95
 
96
        protected function afterDisconnect()/*: void*/ {}
97
 
98
        protected function beforeConnect()/*: void*/ {}
99
 
100
        protected function afterConnect()/*: void*/ {
101
                // Check if the config table exists. This is important because the database version is stored in it
102
                $this->initRequireTables(array('config'));
103
 
104
                // Do the database tables need an update?
105
                // It is important that we do it immediately after connecting,
106
                // because the database structure might change and therefore various things might fail.
107
                // Note: The config setting "database_version" is inserted in setup/sql/...sql, not in the OIDplus core init
108
 
109
                $res = $this->query("SELECT value FROM ###config WHERE name = 'database_version'");
110
                $row = $res->fetch_array();
111
                if ($row == null) {
112
                        throw new OIDplusConfigInitializationException('Cannot determine database version (the entry "database_version" inside the table "###config" is probably missing)');
113
                }
114
                $version = $row['value'];
115
                if (!is_numeric($version) || ($version < 200) || ($version > 999)) {
116
                        throw new OIDplusConfigInitializationException('Entry "database_version" inside the table "###config" seems to be wrong (expect number between 200 and 999)');
117
                }
313 daniel-mar 118
 
119
                while (file_exists($file = OIDplus::basePath().'/includes/db_updates/update'.$version.'.inc.php')) {
295 daniel-mar 120
                        $prev_version = $version;
121
                        include $file; // run update-script
122
                        if ($version != $prev_version+1) {
123
                                // This should usually not happen, since the update-file should increase the version
124
                                // or throw an Exception by itself
125
                                throw new OIDplusException("Database update $prev_version -> ".($prev_version+1)." failed (script reports new version to be $version)");
126
                        }
127
                }
128
 
129
                // Now that our database is up-to-date, we check if database tables are existing
130
                // without config table, because it was checked above
131
                $this->initRequireTables(array('objects', 'asn1id', 'iri', 'ra'/*, 'config'*/));
316 daniel-mar 132
 
133
                // In case an auto-detection of the slang is required (for generic providers like PDO or ODBC),
134
                // we must not be inside a transaction, because the detection requires intentionally submitting
135
                // invalid queries to detect the correct DBMS. If we would be inside a transaction, providers like
136
                // PDO would automatically roll-back. Therefore, we detect the slang right at the beginning,
137
                // before any transaction is used.
138
                $this->getSlang();
295 daniel-mar 139
        }
140
 
299 daniel-mar 141
        protected static function getHardcodedSlangById($id)/*: ?OIDplusSqlSlangPlugin*/ {
295 daniel-mar 142
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
143
                        if ($plugin::id() == $id) {
144
                                return $plugin;
145
                        }
146
                }
147
                return null;
148
        }
149
 
150
        private function initRequireTables($tableNames)/*: void*/ {
151
                $msgs = array();
152
                foreach ($tableNames as $tableName) {
153
                        $prefix = OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', '');
154
                        if (!$this->tableExists($prefix.$tableName)) {
155
                                $msgs[] = 'Table '.$prefix.$tableName.' is missing!';
156
                        }
157
                }
158
                if (count($msgs) > 0) {
159
                        throw new OIDplusConfigInitializationException(implode("\n\n",$msgs));
160
                }
161
        }
162
 
163
        public function tableExists($tableName): bool {
164
                try {
165
                        $this->query("select 0 from ".$tableName." where 1=0");
166
                        return true;
167
                } catch (Exception $e) {
168
                        return false;
169
                }
170
        }
171
 
172
        public function isConnected(): bool {
173
                return $this->connected;
174
        }
175
 
176
        public function init($html = true)/*: void*/ {
177
                $this->html = $html;
178
        }
179
 
180
        public function sqlDate(): string {
181
                if (!is_null($this->slang)) {
182
                        return $this->slang->sqlDate();
183
                } else {
184
                        return "'" . datetime('Y-m-d H:i:s') . "'";
185
                }
186
        }
187
 
316 daniel-mar 188
        public function getSlang(bool $mustExist=true)/*: ?OIDplusSqlSlangPlugin*/ {
295 daniel-mar 189
                if (is_null($this->slang)) {
190
                        if (OIDplus::baseConfig()->exists('FORCE_DBMS_SLANG')) {
191
                                $name = OIDplus::baseConfig()->getValue('FORCE_DBMS_SLANG', '');
192
                                $this->slang = self::getHardcodedSlangById($name);
193
                                if ($mustExist && is_null($this->slang)) {
194
                                        throw new OIDplusConfigInitializationException("Enforced SQL slang (via setting FORCE_DBMS_SLANG) '$name' does not exist.");
195
                                }
196
                        } else {
197
                                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
316 daniel-mar 198
                                        if ($plugin->detect($this)) {
295 daniel-mar 199
                                                $this->slang = $plugin;
200
                                                break;
201
                                        }
202
                                }
203
                                if ($mustExist && is_null($this->slang)) {
204
                                        throw new OIDplusException("Cannot determine the SQL slang of your DBMS. Your DBMS is probably not supported.");
205
                                }
206
                        }
207
                }
208
 
209
                return $this->slang;
210
        }
211
}
212