r2628 - interpretPredicate(): make use of pre-built predicate table
[racktables] / upgrade.php
CommitLineData
6dc745d2 1<?php
fbbb74fb 2
90b96ff6
DO
3$relnotes = array
4(
063ad43c
AD
5 '0.17.0' => "This release requires changes to the configuration file. " .
6 "Move inc/secret.php to local/secret.php and add the following to the file:<br><br>" .
88492978 7 "\$user_auth_src = 'database';<br>\$require_valid_user = TRUE;<br><br>" .
204284ba
DO
8 "(and adjust to your needs, if necessary)<br>" .
9 "Another change is the addition of support for file uploads. Files are stored<br>" .
90b96ff6 10 "in the database. There are several settings in php.ini which you may need to modify:<br>" .
4114697d
DO
11 "<ul><li>file_uploads - needs to be On</li>" .
12 "<li>upload_max_filesize - max size for uploaded files</li>" .
a476909e
DO
13 "<li>post_max_size - max size of all form data submitted via POST (including files)</li></ul><br>" .
14 "User accounts used to have 'enabled' flag, which allowed individual blocking and<br>" .
15 "unblocking of each. This flag was dropped in favor of existing mean of access<br>" .
16 "setup (RackCode). An unconditional denying rule is automatically added into RackCode<br>" .
17 "for such blocked account, so the effective security policy remains the same.<br>",
90b96ff6
DO
18);
19
fbbb74fb
DO
20// At the moment we assume, that for any two releases we can
21// sequentally execute all batches, that separate them, and
22// nothing will break. If this changes one day, the function
23// below will have to generate smarter upgrade paths, while
24// the upper layer will remain the same.
25// Returning an empty array means that no upgrade is necessary.
4114697d 26// Returning NULL indicates an error.
fbbb74fb
DO
27function getDBUpgradePath ($v1, $v2)
28{
a6f83a72
DO
29 $versionhistory = array
30 (
b3f866fc 31 '0.16.4',
64347dcf 32 '0.16.5',
90b96ff6 33 '0.16.6',
30d0a2a3 34 '0.17.0',
a6f83a72 35 );
120e9ddd
DO
36 if (!in_array ($v1, $versionhistory) or !in_array ($v2, $versionhistory))
37 return NULL;
fbbb74fb 38 $skip = TRUE;
4114697d 39 $path = NULL;
fbbb74fb
DO
40 // Now collect all versions > $v1 and <= $v2
41 foreach ($versionhistory as $v)
42 {
4114697d 43 if ($skip and $v == $v1)
fbbb74fb
DO
44 {
45 $skip = FALSE;
4114697d 46 $path = array();
fbbb74fb
DO
47 continue;
48 }
49 if ($skip)
50 continue;
51 $path[] = $v;
52 if ($v == $v2)
53 break;
54 }
55 return $path;
56}
57
90b96ff6
DO
58// Upgrade batches are named exactly as the release where they first appear.
59// That is simple, but seems sufficient for beginning.
fbbb74fb
DO
60function executeUpgradeBatch ($batchid)
61{
62 $query = array();
ce109ff2 63 global $dbxlink;
fbbb74fb
DO
64 switch ($batchid)
65 {
64347dcf
DO
66 case '0.16.5':
67 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('IPV4_TREE_SHOW_USAGE','yes','string','no','no','Show address usage in IPv4 tree')";
68 $query[] = "update Config set varvalue = '0.16.5' where varname = 'DB_VERSION'";
69 break;
90b96ff6
DO
70 case '0.16.6':
71 $query[] = "update Config set varvalue = '0.16.6' where varname = 'DB_VERSION'";
72 break;
30d0a2a3 73 case '0.17.0':
e1ae3fb4
AD
74 // create tables for storing files (requires InnoDB support)
75 if (!isInnoDBSupported ())
76 {
f3c50166
AD
77 showError ("Cannot upgrade because InnoDB tables are not supported by your MySQL server. See the README for details.", __FILE__);
78 die;
e1ae3fb4 79 }
f76c4197
DY
80
81 $query[] = "alter table Chapter change chapter_no id int(10) unsigned NOT NULL auto_increment";
82 $query[] = "alter table Chapter change chapter_name name char(128) NOT NULL";
83 $query[] = "alter table Chapter drop key chapter_name";
84 $query[] = "alter table Chapter add UNIQUE KEY name (name)";
85 $query[] = "alter table Attribute change attr_id id int(10) unsigned NOT NULL auto_increment";
86 $query[] = "alter table Attribute change attr_type type enum('string','uint','float','dict') default NULL";
87 $query[] = "alter table Attribute change attr_name name char(64) default NULL";
88 $query[] = "alter table Attribute drop key attr_name";
89 $query[] = "alter table Attribute add UNIQUE KEY name (name)";
90 $query[] = "alter table AttributeMap change chapter_no chapter_id int(10) unsigned NOT NULL";
91 $query[] = "alter table Dictionary change chapter_no chapter_id int(10) unsigned NOT NULL";
90b96ff6
DO
92 // Many dictionary changes were made... remove all dictvendor entries and install fresh.
93 // Take care not to erase locally added records. 0.16.x ends with max key 797
f76c4197
DY
94 $query[] = 'DELETE FROM Dictionary WHERE ((chapter_id BETWEEN 11 AND 14) or (chapter_id BETWEEN 16 AND 19) ' .
95 'or (chapter_id BETWEEN 21 AND 24)) and dict_key <= 797';
f3c50166
AD
96 $f = fopen ("install/init-dictvendors.sql", 'r');
97 if ($f === FALSE)
98 {
99 showError ("Failed to open install/init-dictvendors.sql for reading");
100 die;
101 }
102 $longq = '';
103 while (!feof ($f))
104 {
105 $line = fgets ($f);
106 if (ereg ('^--', $line))
107 continue;
108 $longq .= $line;
109 }
110 fclose ($f);
111 foreach (explode (";\n", $longq) as $dict_query)
112 {
113 if (empty ($dict_query))
114 continue;
115 $query[] = $dict_query;
116 }
117
118 // schema changes for file management
e1ae3fb4
AD
119 $query[] = "
120CREATE TABLE `File` (
121 `id` int(10) unsigned NOT NULL auto_increment,
122 `name` char(255) NOT NULL,
123 `type` char(255) NOT NULL,
124 `size` int(10) unsigned NOT NULL,
125 `ctime` datetime NOT NULL,
126 `mtime` datetime NOT NULL,
127 `atime` datetime NOT NULL,
128 `contents` longblob NOT NULL,
129 `comment` text,
13edfa1c
AD
130 PRIMARY KEY (`id`),
131 UNIQUE KEY `name` (`name`)
e1ae3fb4
AD
132) ENGINE=InnoDB";
133 $query[] = "
134CREATE TABLE `FileLink` (
135 `id` int(10) unsigned NOT NULL auto_increment,
136 `file_id` int(10) unsigned NOT NULL,
137 `entity_type` enum('ipv4net','ipv4rspool','ipv4vs','object','rack','user') NOT NULL default 'object',
138 `entity_id` int(10) NOT NULL,
139 PRIMARY KEY (`id`),
af721881 140 UNIQUE KEY `FileLink-unique` (`file_id`,`entity_type`,`entity_id`),
e1ae3fb4
AD
141 KEY `FileLink-file_id` (`file_id`),
142 CONSTRAINT `FileLink-File_fkey` FOREIGN KEY (`file_id`) REFERENCES `File` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
143) ENGINE=InnoDB";
144 $query[] = "ALTER TABLE TagStorage MODIFY COLUMN target_realm enum('file','ipv4net','ipv4rspool','ipv4vs','object','rack','user') NOT NULL default 'object'";
f3c50166
AD
145
146 // add network security as an object type
f76c4197
DY
147 $query[] = "INSERT INTO `Chapter` (`id`, `sticky`, `name`) VALUES (24,'no','network security models')";
148 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,1,0)";
149 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,2,24)";
150 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,3,0)";
151 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,5,0)";
152 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,14,0)";
153 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,16,0)";
154 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,17,0)";
155 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,18,0)";
156 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,20,0)";
157 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,21,0)";
158 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,22,0)";
159 $query[] = "INSERT INTO `AttributeMap` (`objtype_id`, `attr_id`, `chapter_id`) VALUES (798,24,0)";
d4739002 160 $query[] = "UPDATE Dictionary SET dict_value = 'Network switch' WHERE dict_key = 8";
706ce117
DO
161 $query[] = 'alter table IPBonds rename to IPv4Allocation';
162 $query[] = 'alter table PortForwarding rename to IPv4NAT';
163 $query[] = 'alter table IPRanges rename to IPv4Network';
164 $query[] = 'alter table IPAddress rename to IPv4Address';
165 $query[] = 'alter table IPLoadBalancer rename to IPv4LB';
4114697d 166 $query[] = 'alter table IPRSPool rename to IPv4RSPool';
706ce117 167 $query[] = 'alter table IPRealServer rename to IPv4RS';
4114697d 168 $query[] = 'alter table IPVirtualService rename to IPv4VS';
120e9ddd
DO
169 $query[] = "alter table TagStorage change column target_realm entity_realm enum('file','ipv4net','ipv4vs','ipv4rspool','object','rack','user') NOT NULL default 'object'";
170 $query[] = 'alter table TagStorage change column target_id entity_id int(10) unsigned NOT NULL';
171 $query[] = 'alter table TagStorage drop key entity_tag';
172 $query[] = 'alter table TagStorage drop key target_id';
173 $query[] = 'alter table TagStorage add UNIQUE KEY `entity_tag` (`entity_realm`,`entity_id`,`tag_id`)';
174 $query[] = 'alter table TagStorage add KEY `entity_id` (`entity_id`)';
37e59768
DO
175 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('PREVIEW_TEXT_MAXCHARS','10240','uint','yes','no','Max chars for text file preview')";
176 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('PREVIEW_TEXT_ROWS','25','uint','yes','no','Rows for text file preview')";
177 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('PREVIEW_TEXT_COLS','80','uint','yes','no','Columns for text file preview')";
178 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('PREVIEW_IMAGE_MAXPXS','320','uint','yes','no','Max pixels per axis for image file preview')";
f3d274bf 179 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('VENDOR_SIEVE','','string','yes','no','Vendor sieve configuration')";
35bf153d
DO
180 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('IPV4LB_LISTSRC','{$typeid_4}','string','yes','no','List source: IPv4 load balancers')";
181 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('IPV4OBJ_LISTSRC','{$typeid_4} or {$typeid_7} or {$typeid_8} or {$typeid_12} or {$typeid_445} or {$typeid_447}','string','yes','no','List source: IPv4-enabled objects')";
182 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('IPV4NAT_LISTSRC','{$typeid_4} or {$typeid_7} or {$typeid_8}','string','yes','no','List source: IPv4 NAT performers')";
183 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('ASSETWARN_LISTSRC','{$typeid_4} or {$typeid_7} or {$typeid_8}','string','yes','no','List source: object, for which asset tag should be set')";
184 $query[] = "INSERT INTO `Config` (varname, varvalue, vartype, emptyok, is_hidden, description) VALUES ('NAMEWARN_LISTSRC','{$typeid_4} or {$typeid_7} or {$typeid_8}','string','yes','no','List source: object, for which common name should be set')";
529eac25
DO
185 $query[] = "delete from Config where varname = 'USER_AUTH_SRC'";
186 $query[] = "delete from Config where varname = 'COOKIE_TTL'";
187 $query[] = "delete from Config where varname = 'rtwidth_0'";
188 $query[] = "delete from Config where varname = 'rtwidth_1'";
189 $query[] = "delete from Config where varname = 'rtwidth_2'";
c6bc0ac5
DO
190 $query[] = "delete from Config where varname = 'NAMEFUL_OBJTYPES'";
191 $query[] = "delete from Config where varname = 'REQUIRE_ASSET_TAG_FOR'";
192 $query[] = "delete from Config where varname = 'IPV4_PERFORMERS'";
193 $query[] = "delete from Config where varname = 'NATV4_PERFORMERS'";
dbb33805 194 $query[] = "alter table TagTree add column valid_realm set('file','ipv4net','ipv4vs','ipv4rspool','object','rack','user') not null default 'file,ipv4net,ipv4vs,ipv4rspool,object,rack,user' after parent_id";
a476909e
DO
195 $result = $dbxlink->query ("select user_id, user_name, user_realname from UserAccount where user_enabled = 'no'");
196 while ($row = $result->fetch (PDO::FETCH_ASSOC))
197 $query[] = "update Script set script_text = concat('deny {\$userid_${row['user_id']}} # ${row['user_name']} (${row['user_realname']})\n', script_text) where script_name = 'RackCode'";
198 $query[] = "update Script set script_text = NULL where script_name = 'RackCodeCache'";
199 unset ($result);
79b8ad1e 200 $query[] = "alter table UserAccount drop column user_enabled";
f76c4197 201
10bac82a
DY
202 $query[] = "CREATE TABLE RackRow ( id int(10) unsigned NOT NULL auto_increment, name char(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM";
203
9f14a7ef
DY
204 $result = $dbxlink->query ("select dict_key, dict_value from Dictionary where chapter_no = 3");
205 while($row = $result->fetch(PDO::FETCH_NUM))
10bac82a
DY
206 {
207 $query[] = "insert into RackRow set id=${row[0]}, name='${row[1]}'";
208 }
f76c4197 209 $query[] = "delete from Dictionary where chapter_id = 3";
10bac82a 210
f76c4197
DY
211 $query[] = "UPDATE Config SET varvalue = '0.17.0' WHERE varname = 'DB_VERSION'";
212
b3f866fc 213 break;
fbbb74fb 214 default:
b0348307 215 showError ("executeUpgradeBatch () failed, because batch '${batchid}' isn't defined", __FILE__);
fbbb74fb
DO
216 die;
217 break;
218 }
fbbb74fb 219 $failures = array();
4114697d 220 echo "<tr><th>Executing batch '${batchid}'</th><td>";
fbbb74fb
DO
221 foreach ($query as $q)
222 {
223 $result = $dbxlink->query ($q);
4114697d 224 if ($result == NULL)
758fe24c 225 {
758fe24c
DO
226 $errorInfo = $dbxlink->errorInfo();
227 $failures[] = array ($q, $errorInfo[2]);
228 }
fbbb74fb 229 }
fbbb74fb 230 if (!count ($failures))
4114697d 231 echo "<strong><font color=green>done</font></strong>";
fbbb74fb
DO
232 else
233 {
4114697d 234 echo "<strong><font color=red>The following queries failed:</font></strong><br><pre>";
fbbb74fb
DO
235 foreach ($failures as $f)
236 {
237 list ($q, $i) = $f;
4114697d 238 echo "${q} -- ${i}\n";
fbbb74fb 239 }
4114697d 240 echo "</pre>";
fbbb74fb 241 }
4114697d 242 echo '</td></tr>';
fbbb74fb
DO
243}
244
245// ******************************************************************
246//
247// Execution starts here
248//
249// ******************************************************************
250
251$root = (empty($_SERVER['HTTPS'])?'http':'https').
252 '://'.
253 (isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:($_SERVER['SERVER_NAME'].($_SERVER['SERVER_PORT']=='80'?'':$_SERVER['SERVER_PORT']))).
54c2a7a8
DO
254 dirname($_SERVER['PHP_SELF']);
255if (substr ($root, -1) != '/')
256 $root .= '/';
fbbb74fb
DO
257
258// The below will be necessary as long as we rely on showError()
259require_once 'inc/interface.php';
260
261require_once 'inc/config.php';
262require_once 'inc/database.php';
063ad43c
AD
263if (file_exists ('local/secret.php'))
264 require_once 'local/secret.php';
fbbb74fb 265else
063ad43c
AD
266 die ("Database connection parameters are read from local/secret.php file, " .
267 "which cannot be found.\nCopy provided config/secret-sample.php to " .
268 "local/secret.php and modify to your setup.\n\nThen reload the page.");
fbbb74fb
DO
269
270try
271{
272 $dbxlink = new PDO ($pdo_dsn, $db_username, $db_password);
273}
274catch (PDOException $e)
275{
276 die ("Database connection failed:\n\n" . $e->getMessage());
277}
278
fbbb74fb
DO
279// Now we need to be sure that the current user is the administrator.
280// The rest doesn't matter within this context.
fbbb74fb 281
120e9ddd 282function authenticate_admin ($username, $password)
a1f3710a 283{
43c7895d 284 global $dbxlink;
93bdb7ba 285 $hash = sha1 ($password);
120e9ddd 286 $query = "select count(*) from UserAccount where user_id = 1 and user_name = '${username}' and user_password_hash = '${hash}'";
a1f3710a
DO
287 if (($result = $dbxlink->query ($query)) == NULL)
288 die ('SQL query failed in ' . __FUNCTION__);
120e9ddd 289 $rows = $result->fetchAll (PDO::FETCH_NUM);
43c7895d 290 return $rows[0][0] == 1;
a1f3710a
DO
291}
292
204284ba 293switch ($user_auth_src)
99ee5479 294{
120e9ddd
DO
295 case 'database':
296 case 'ldap': // authenticate against DB as well
297 if
298 (
299 !isset ($_SERVER['PHP_AUTH_USER']) or
300 !strlen ($_SERVER['PHP_AUTH_USER']) or
301 !isset ($_SERVER['PHP_AUTH_PW']) or
302 !strlen ($_SERVER['PHP_AUTH_PW']) or
303 !authenticate_admin (escapeString ($_SERVER['PHP_AUTH_USER']), escapeString ($_SERVER['PHP_AUTH_PW']))
304 )
305 {
306 header ('WWW-Authenticate: Basic realm="RackTables upgrade"');
307 header ('HTTP/1.0 401 Unauthorized');
308 showError ('You must be authenticated as an administrator to complete the upgrade.', __FILE__);
309 die;
310 }
311 break; // cleared
312 case 'httpd':
313 if
314 (
315 !isset ($_SERVER['REMOTE_USER']) or
316 !strlen ($_SERVER['REMOTE_USER'])
317 )
318 {
319 showError ('System misconfiguration. The web-server didn\'t authenticate the user, although ought to do.');
320 die;
321 }
322 break; // cleared
323 default:
204284ba 324 showError ('authentication source misconfiguration', __FILE__);
120e9ddd 325 die;
99ee5479 326}
fbbb74fb
DO
327
328$dbver = getDatabaseVersion();
4114697d
DO
329echo '<table border=1>';
330echo "<tr><th>Current status</th><td>Data version: ${dbver}<br>Code version: " . CODE_VERSION . "</td></tr>\n";
331
332$path = getDBUpgradePath ($dbver, CODE_VERSION);
333if ($path === NULL)
758fe24c 334{
4114697d
DO
335 echo "<tr><th>Upgrade path</th><td><font color=red>not found</font></td></tr>\n";
336 echo "<tr><th>Summary</th><td>Check README for more information.</td></tr>\n";
758fe24c 337}
4114697d 338else
5f4027b8 339{
4114697d
DO
340 if (!count ($path))
341 echo "<tr><th>Summary</th><td>Come back later.</td></tr>\n";
342 else
343 {
344 echo "<tr><th>Upgrade path</th><td>${dbver} &rarr; " . implode (' &rarr; ', $path) . "</td></tr>\n";
345 foreach ($path as $batchid)
346 {
347 executeUpgradeBatch ($batchid);
348 if (isset ($relnotes[$batchid]))
349 echo "<tr><th>Release notes for ${batchid}</th><td>" . $relnotes[$batchid] . "</td></tr>\n";
350 }
351 echo "<tr><th>Summary</th><td>Upgrade complete, it is Ok to <a href='${root}'>enter</a> the system.</td></tr>\n";
352 }
5f4027b8 353}
4114697d 354echo '</table>';
fbbb74fb
DO
355
356?>