Subversion Repositories oidplus

Rev

Rev 299 | Go to most recent revision | Details | 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;
24
        protected /*?OIDplusSqlSlangPlugin*/ $slang = null;
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).
41
                return $this->getSlang()->insert_id();
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
                }
118
                while (file_exists($file = OIDplus::basePath().'/includes/db_updates/update$version.inc.php')) {
119
                        $prev_version = $version;
120
                        include $file; // run update-script
121
                        if ($version != $prev_version+1) {
122
                                // This should usually not happen, since the update-file should increase the version
123
                                // or throw an Exception by itself
124
                                throw new OIDplusException("Database update $prev_version -> ".($prev_version+1)." failed (script reports new version to be $version)");
125
                        }
126
                }
127
 
128
                // Now that our database is up-to-date, we check if database tables are existing
129
                // without config table, because it was checked above
130
                $this->initRequireTables(array('objects', 'asn1id', 'iri', 'ra'/*, 'config'*/));
131
        }
132
 
133
        protected static function getHardcodedSlangById($id): /*?*/OIDplusSqlSlangPlugin {
134
                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
135
                        if ($plugin::id() == $id) {
136
                                return $plugin;
137
                        }
138
                }
139
                return null;
140
        }
141
 
142
        private function initRequireTables($tableNames)/*: void*/ {
143
                $msgs = array();
144
                foreach ($tableNames as $tableName) {
145
                        $prefix = OIDplus::baseConfig()->getValue('TABLENAME_PREFIX', '');
146
                        if (!$this->tableExists($prefix.$tableName)) {
147
                                $msgs[] = 'Table '.$prefix.$tableName.' is missing!';
148
                        }
149
                }
150
                if (count($msgs) > 0) {
151
                        throw new OIDplusConfigInitializationException(implode("\n\n",$msgs));
152
                }
153
        }
154
 
155
        public function tableExists($tableName): bool {
156
                try {
157
                        $this->query("select 0 from ".$tableName." where 1=0");
158
                        return true;
159
                } catch (Exception $e) {
160
                        return false;
161
                }
162
        }
163
 
164
        public function isConnected(): bool {
165
                return $this->connected;
166
        }
167
 
168
        public function init($html = true)/*: void*/ {
169
                $this->html = $html;
170
        }
171
 
172
        public function sqlDate(): string {
173
                if (!is_null($this->slang)) {
174
                        return $this->slang->sqlDate();
175
                } else {
176
                        return "'" . datetime('Y-m-d H:i:s') . "'";
177
                }
178
        }
179
 
180
        public final function getSlang(bool $mustExist=true): /*?*/OIDplusSqlSlangPlugin {
181
                if (is_null($this->slang)) {
182
                        if (OIDplus::baseConfig()->exists('FORCE_DBMS_SLANG')) {
183
                                $name = OIDplus::baseConfig()->getValue('FORCE_DBMS_SLANG', '');
184
                                $this->slang = self::getHardcodedSlangById($name);
185
                                if ($mustExist && is_null($this->slang)) {
186
                                        throw new OIDplusConfigInitializationException("Enforced SQL slang (via setting FORCE_DBMS_SLANG) '$name' does not exist.");
187
                                }
188
                        } else {
189
                                foreach (OIDplus::getSqlSlangPlugins() as $plugin) {
190
                                        if ($plugin->detect()) {
191
                                                $this->slang = $plugin;
192
                                                break;
193
                                        }
194
                                }
195
                                if ($mustExist && is_null($this->slang)) {
196
                                        throw new OIDplusException("Cannot determine the SQL slang of your DBMS. Your DBMS is probably not supported.");
197
                                }
198
                        }
199
                }
200
 
201
                return $this->slang;
202
        }
203
}
204