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