r3780 convertPDOException(): new function
[racktables] / inc / database.php
CommitLineData
b325120a 1<?php
e673ee24
DO
2/*
3*
4* This file is a library of database access functions for RackTables.
5*
6*/
7
a6e91ac2
DO
8$SQLSchema = array
9(
10 'object' => array
11 (
12 'table' => 'RackObject',
13 'columns' => array
14 (
15 'id' => 'id',
16 'name' => 'name',
17 'label' => 'label',
18 'barcode' => 'barcode',
19 'asset_no' => 'asset_no',
20 'objtype_id' => 'objtype_id',
21 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
22 'Rack_name' => '(select name from Rack where id = rack_id)',
23 'row_id' => '(select row_id from Rack where id = rack_id)',
24 'Row_name' => '(select name from RackRow where id = row_id)',
0d993afe 25 'has_problems' => 'has_problems',
6657739e 26 'comment' => 'comment',
6d472f26 27 'nports' => '(SELECT COUNT(*) FROM Port WHERE object_id = RackObject.id)',
b48d8d61 28 'runs8021Q' => '(SELECT 1 FROM VLANSwitch WHERE object_id = id LIMIT 1)',
a6e91ac2
DO
29 ),
30 'keycolumn' => 'id',
978dc510 31 'ordcolumns' => array ('RackObject.name'),
a6e91ac2
DO
32 ),
33 'user' => array
34 (
35 'table' => 'UserAccount',
36 'columns' => array
37 (
38 'user_id' => 'user_id',
39 'user_name' => 'user_name',
40 'user_password_hash' => 'user_password_hash',
41 'user_realname' => 'user_realname',
42 ),
43 'keycolumn' => 'user_id',
978dc510 44 'ordcolumns' => array ('UserAccount.user_name'),
a6e91ac2
DO
45 ),
46 'ipv4net' => array
47 (
48 'table' => 'IPv4Network',
49 'columns' => array
50 (
51 'id' => 'id',
52 'ip' => 'INET_NTOA(IPv4Network.ip)',
53 'mask' => 'mask',
54 'name' => 'name',
99ab184f 55 'comment' => 'comment',
b1e39212 56 'parent_id' => '(SELECT id FROM IPv4Network AS subt WHERE IPv4Network.ip & (4294967295 >> (32 - subt.mask)) << (32 - subt.mask) = subt.ip and subt.mask < IPv4Network.mask ORDER BY subt.mask DESC limit 1)',
a5f9d1ca 57 'vlanc' => '(SELECT COUNT(*) FROM VLANIPv4 WHERE ipv4net_id = id)',
a6e91ac2
DO
58 ),
59 'keycolumn' => 'id',
978dc510 60 'ordcolumns' => array ('IPv4Network.ip', 'IPv4Network.mask'),
a6e91ac2
DO
61 ),
62 'file' => array
63 (
64 'table' => 'File',
65 'columns' => array
66 (
67 'id' => 'id',
68 'name' => 'name',
69 'type' => 'type',
70 'size' => 'size',
71 'ctime' => 'ctime',
72 'mtime' => 'mtime',
73 'atime' => 'atime',
74 'comment' => 'comment',
75 ),
76 'keycolumn' => 'id',
978dc510 77 'ordcolumns' => array ('File.name'),
a6e91ac2
DO
78 ),
79 'ipv4vs' => array
80 (
81 'table' => 'IPv4VS',
82 'columns' => array
83 (
84 'id' => 'id',
85 'vip' => 'INET_NTOA(vip)',
86 'vport' => 'vport',
87 'proto' => 'proto',
88 'name' => 'name',
89 'vsconfig' => 'vsconfig',
90 'rsconfig' => 'rsconfig',
91 'poolcount' => '(select count(vs_id) from IPv4LB where vs_id = id)',
92 'dname' => 'CONCAT_WS("/", CONCAT_WS(":", INET_NTOA(vip), vport), proto)',
93 ),
94 'keycolumn' => 'id',
978dc510 95 'ordcolumns' => array ('IPv4VS.vip', 'IPv4VS.proto', 'IPv4VS.vport'),
a6e91ac2
DO
96 ),
97 'ipv4rspool' => array
98 (
99 'table' => 'IPv4RSPool',
100 'columns' => array
101 (
102 'id' => 'id',
103 'name' => 'name',
104 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
105 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
106 'vsconfig' => 'vsconfig',
107 'rsconfig' => 'rsconfig',
108 ),
109 'keycolumn' => 'id',
978dc510 110 'ordcolumns' => array ('IPv4RSPool.name', 'IPv4RSPool.id'),
a6e91ac2
DO
111 ),
112 'rack' => array
113 (
114 'table' => 'Rack',
115 'columns' => array
116 (
117 'id' => 'id',
118 'name' => 'name',
119 'height' => 'height',
120 'comment' => 'comment',
121 'row_id' => 'row_id',
122 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
123 ),
124 'keycolumn' => 'id',
978dc510 125 'ordcolumns' => array ('row_name', 'Rack.name'),
a6e91ac2
DO
126 'pidcolumn' => 'row_id',
127 ),
128);
129
1b4a0a6a
DO
130$searchfunc = array
131(
132 'object' => array
133 (
134 'by_sticker' => 'getStickerSearchResults',
135 'by_port' => 'getPortSearchResults',
136 'by_attr' => 'getObjectAttrsSearchResults',
137 'by_iface' => 'getObjectIfacesSearchResults',
138 'by_nat' => 'getObjectNATSearchResults',
139 ),
140);
141
be28b696
DO
142$tablemap_8021q = array
143(
144 'desired' => array
145 (
146 'pvm' => 'PortVLANMode',
147 'pav' => 'PortAllowedVLAN',
148 'pnv' => 'PortNativeVLAN',
149 ),
150 'cached' => array
151 (
152 'pvm' => 'CachedPVM',
153 'pav' => 'CachedPAV',
154 'pnv' => 'CachedPNV',
155 ),
156);
157
e1ae3fb4
AD
158function isInnoDBSupported ($dbh = FALSE) {
159 global $dbxlink;
160
161 // sometimes db handle isn't available globally, must be passed
162 if (!$dbxlink)
163 $dbxlink = $dbh;
164
165 // create a temp table
166 $dbxlink->query("CREATE TABLE `innodb_test` (`id` int) ENGINE=InnoDB");
167 $row = $dbxlink->query("SHOW TABLE STATUS LIKE 'innodb_test'")->fetch(PDO::FETCH_ASSOC);
168 $dbxlink->query("DROP TABLE `innodb_test`");
169 if ($row['Engine'] == 'InnoDB')
170 return TRUE;
171
172 return FALSE;
173}
174
160a82e6 175function escapeString ($value, $do_db_escape = FALSE)
e673ee24 176{
b614498d 177 $ret = htmlspecialchars ($value, ENT_QUOTES, 'UTF-8');
5f54485b
DO
178 if ($do_db_escape)
179 {
180 global $dbxlink;
181 $ret = substr ($dbxlink->quote ($ret), 1, -1);
182 }
183 return $ret;
e673ee24
DO
184}
185
a8ce7234
DO
186// Return detailed information about one rack row.
187function getRackRowInfo ($rackrow_id)
e673ee24 188{
e673ee24 189 $query =
10bac82a 190 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
5332840f 191 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
10bac82a 192 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
298d2375 193 "where RackRow.id = ? " .
1743cafe 194 "group by RackRow.id";
298d2375 195 $result = usePreparedSelectBlade ($query, array ($rackrow_id));
a8ce7234
DO
196 if ($row = $result->fetch (PDO::FETCH_ASSOC))
197 return $row;
e673ee24 198 else
0cc24e9a 199 throw new EntityNotFoundException ('rackrow', $rackrow_id);
e673ee24
DO
200}
201
51690ad4
DY
202function getRackRows ()
203{
650ef981 204 $result = usePreparedSelectBlade ('SELECT id, name FROM RackRow ORDER BY name');
51690ad4
DY
205 $rows = array();
206 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2a3f0501 207 $rows[$row['id']] = $row['name'];
51690ad4
DY
208 return $rows;
209}
210
10bac82a
DY
211function commitAddRow($rackrow_name)
212{
298d2375 213 return usePreparedInsertBlade ('RackRow', array ('name' => $rackrow_name));
10bac82a
DY
214}
215
39eadd27 216function commitUpdateRow ($rackrow_id, $rackrow_name)
10bac82a 217{
39eadd27 218 return usePreparedExecuteBlade ('UPDATE RackRow SET name = ? WHERE id = ?', array ($rackrow_name, $rackrow_id));
10bac82a
DY
219}
220
9f14a7ef
DY
221function commitDeleteRow($rackrow_id)
222{
298d2375 223 return usePreparedDeleteBlade ('RackRow', array ('id' => $rackrow_id));
9f14a7ef
DY
224}
225
8d4f7d18 226// Return a simple object list w/o related information, so that the returned value
c6bc0ac5
DO
227// can be directly used by printSelect(). An optional argument is the name of config
228// option with constraint in RackCode.
229function getNarrowObjectList ($varname = '')
e9132485 230{
212c9d8a 231 $wideList = listCells ('object');
59dce363 232 if (strlen ($varname) and strlen (getConfigVar ($varname)))
e9132485 233 {
59dce363
DO
234 global $parseCache;
235 if (!isset ($parseCache[$varname]))
236 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
237 if ($parseCache[$varname]['result'] != 'ACK')
238 return array();
212c9d8a 239 $wideList = filterCellList ($wideList, $parseCache[$varname]['load']);
e9132485 240 }
212c9d8a
DO
241 $ret = array();
242 foreach ($wideList as $cell)
243 $ret[$cell['id']] = $cell['dname'];
e9132485
DO
244 return $ret;
245}
246
d08d766d 247// For a given realm return a list of entity records, each with
212c9d8a 248// enough information for judgeCell() to execute.
a8efc03e 249function listCells ($realm, $parent_id = 0)
d08d766d 250{
7cfc98b1
DO
251 if (!$parent_id)
252 {
253 global $entityCache;
254 if (isset ($entityCache['complete'][$realm]))
255 return $entityCache['complete'][$realm];
256 }
a6e91ac2
DO
257 global $SQLSchema;
258 if (!isset ($SQLSchema[$realm]))
c5f84f48 259 throw new RealmNotFoundException ($realm);
a6e91ac2 260 $SQLinfo = $SQLSchema[$realm];
a685e6d7 261 $qparams = array ($realm);
a8efc03e 262 $query = 'SELECT tag_id';
a6e91ac2 263 foreach ($SQLinfo['columns'] as $alias => $expression)
573214e0 264 // Automatically prepend table name to each single column, but leave all others intact.
a6e91ac2 265 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
a685e6d7 266 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
a6e91ac2 267 if (isset ($SQLinfo['pidcolumn']) and $parent_id)
a685e6d7
DO
268 {
269 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ?";
270 $qparams[] = $parent_id;
271 }
a8efc03e 272 $query .= " ORDER BY ";
a6e91ac2 273 foreach ($SQLinfo['ordcolumns'] as $oc)
978dc510 274 $query .= "${oc}, ";
0fbbfad0 275 $query .= " tag_id";
a685e6d7 276 $result = usePreparedSelectBlade ($query, $qparams);
d08d766d
DO
277 $ret = array();
278 global $taglist;
279 // Index returned result by the value of key column.
280 while ($row = $result->fetch (PDO::FETCH_ASSOC))
281 {
a6e91ac2 282 $entity_id = $row[$SQLinfo['keycolumn']];
d08d766d
DO
283 // Init the first record anyway, but store tag only if there is one.
284 if (!isset ($ret[$entity_id]))
285 {
573214e0 286 $ret[$entity_id] = array ('realm' => $realm);
a6e91ac2 287 foreach (array_keys ($SQLinfo['columns']) as $alias)
573214e0
DO
288 $ret[$entity_id][$alias] = $row[$alias];
289 $ret[$entity_id]['etags'] = array();
d08d766d
DO
290 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
291 $ret[$entity_id]['etags'][] = array
292 (
293 'id' => $row['tag_id'],
294 'tag' => $taglist[$row['tag_id']]['tag'],
295 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
296 );
297 }
a6e91ac2 298 elseif (isset ($taglist[$row['tag_id']]))
d08d766d
DO
299 // Meeting existing key later is always more tags on existing list.
300 $ret[$entity_id]['etags'][] = array
301 (
302 'id' => $row['tag_id'],
303 'tag' => $taglist[$row['tag_id']]['tag'],
304 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
305 );
306 }
7cfc98b1
DO
307 // Add necessary finish to the list before returning it. Maintain caches.
308 if (!$parent_id)
309 unset ($entityCache['partial'][$realm]);
d08d766d
DO
310 foreach (array_keys ($ret) as $entity_id)
311 {
6df2025d 312 $ret[$entity_id]['etags'] = getExplicitTagsOnly ($ret[$entity_id]['etags']);
d08d766d 313 $ret[$entity_id]['itags'] = getImplicitTags ($ret[$entity_id]['etags']);
d16af52f 314 $ret[$entity_id]['atags'] = generateEntityAutoTags ($ret[$entity_id]);
23cdc7e9
DO
315 switch ($realm)
316 {
317 case 'object':
cfa8f3cf 318 setDisplayedName ($ret[$entity_id]);
23cdc7e9 319 break;
d724d290
DO
320 case 'ipv4net':
321 $ret[$entity_id]['ip_bin'] = ip2long ($ret[$entity_id]['ip']);
322 $ret[$entity_id]['mask_bin'] = binMaskFromDec ($ret[$entity_id]['mask']);
323 $ret[$entity_id]['mask_bin_inv'] = binInvMaskFromDec ($ret[$entity_id]['mask']);
324 $ret[$entity_id]['db_first'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] & $ret[$entity_id]['mask_bin']);
325 $ret[$entity_id]['db_last'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] | ($ret[$entity_id]['mask_bin_inv']));
326 break;
23cdc7e9
DO
327 default:
328 break;
329 }
7cfc98b1
DO
330 if (!$parent_id)
331 $entityCache['complete'][$realm][$entity_id] = $ret[$entity_id];
332 else
333 $entityCache['partial'][$realm][$entity_id] = $ret[$entity_id];
d08d766d
DO
334 }
335 return $ret;
336}
337
a6e91ac2
DO
338// Very much like listCells(), but return only one record requested (or NULL,
339// if it does not exist).
340function spotEntity ($realm, $id)
341{
7cfc98b1
DO
342 global $entityCache;
343 if (isset ($entityCache['complete'][$realm]))
344 // Emphasize the absence of record, if listCells() has already been called.
b135a49d
DY
345 if (isset ($entityCache['complete'][$realm][$id]))
346 return $entityCache['complete'][$realm][$id];
347 else
348 throw new EntityNotFoundException ($realm, $id);
7cfc98b1
DO
349 elseif (isset ($entityCache['partial'][$realm][$id]))
350 return $entityCache['partial'][$realm][$id];
a6e91ac2
DO
351 global $SQLSchema;
352 if (!isset ($SQLSchema[$realm]))
c5f84f48 353 throw new RealmNotFoundException ($realm);
a6e91ac2
DO
354 $SQLinfo = $SQLSchema[$realm];
355 $query = 'SELECT tag_id';
356 foreach ($SQLinfo['columns'] as $alias => $expression)
357 // Automatically prepend table name to each single column, but leave all others intact.
358 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
a685e6d7
DO
359 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
360 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ?";
a6e91ac2 361 $query .= " ORDER BY tag_id";
a685e6d7 362 $result = usePreparedSelectBlade ($query, array ($realm, $id));
a6e91ac2
DO
363 $ret = array();
364 global $taglist;
365 while ($row = $result->fetch (PDO::FETCH_ASSOC))
366 if (!isset ($ret['realm']))
367 {
368 $ret = array ('realm' => $realm);
369 foreach (array_keys ($SQLinfo['columns']) as $alias)
370 $ret[$alias] = $row[$alias];
371 $ret['etags'] = array();
372 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
373 $ret['etags'][] = array
374 (
375 'id' => $row['tag_id'],
376 'tag' => $taglist[$row['tag_id']]['tag'],
377 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
378 );
379 }
380 elseif (isset ($taglist[$row['tag_id']]))
381 $ret['etags'][] = array
382 (
383 'id' => $row['tag_id'],
384 'tag' => $taglist[$row['tag_id']]['tag'],
385 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
386 );
387 unset ($result);
388 if (!isset ($ret['realm'])) // no rows were returned
b135a49d 389 throw new EntityNotFoundException ($realm, $id);
6df2025d 390 $ret['etags'] = getExplicitTagsOnly ($ret['etags']);
a6e91ac2 391 $ret['itags'] = getImplicitTags ($ret['etags']);
d16af52f 392 $ret['atags'] = generateEntityAutoTags ($ret);
a6e91ac2
DO
393 switch ($realm)
394 {
395 case 'object':
cfa8f3cf 396 setDisplayedName ($ret);
a6e91ac2 397 break;
d724d290
DO
398 case 'ipv4net':
399 $ret['ip_bin'] = ip2long ($ret['ip']);
400 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
401 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
402 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
403 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
404 break;
a6e91ac2
DO
405 default:
406 break;
407 }
7cfc98b1 408 $entityCache['partial'][$realm][$id] = $ret;
a6e91ac2
DO
409 return $ret;
410}
411
d08d766d 412// This function can be used with array_walk().
573214e0 413function amplifyCell (&$record, $dummy = NULL)
d08d766d 414{
d08d766d
DO
415 switch ($record['realm'])
416 {
417 case 'object':
418 $record['ports'] = getObjectPortsAndLinks ($record['id']);
419 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
420 $record['nat4'] = getNATv4ForObject ($record['id']);
421 $record['ipv4rspools'] = getRSPoolsForObject ($record['id']);
422 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
423 break;
8bc5d1e4
DO
424 case 'file':
425 $record['links'] = getFileLinks ($record['id']);
426 break;
a6e91ac2
DO
427 case 'ipv4rspool':
428 $record['lblist'] = array();
429 $query = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
430 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
a685e6d7
DO
431 "where rspool_id = ? order by object_id, vip, vport";
432 $result = usePreparedSelectBlade ($query, array ($record['id']));
a6e91ac2
DO
433 while ($row = $result->fetch (PDO::FETCH_ASSOC))
434 $record['lblist'][$row['object_id']][$row['vs_id']] = array
435 (
436 'rsconfig' => $row['rsconfig'],
437 'vsconfig' => $row['vsconfig'],
438 );
439 unset ($result);
7c38462f 440 $record['rslist'] = array();
a6e91ac2 441 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
a685e6d7
DO
442 "IPv4RS where rspool_id = ? order by IPv4RS.rsip, rsport";
443 $result = usePreparedSelectBlade ($query, array ($record['id']));
a6e91ac2
DO
444 while ($row = $result->fetch (PDO::FETCH_ASSOC))
445 $record['rslist'][$row['id']] = array
446 (
447 'inservice' => $row['inservice'],
448 'rsip' => $row['rsip'],
449 'rsport' => $row['rsport'],
450 'rsconfig' => $row['rsconfig'],
451 );
452 unset ($result);
7c38462f
DO
453 break;
454 case 'ipv4vs':
455 // Get the detailed composition of a particular virtual service, namely the list
456 // of all pools, each shown with the list of objects servicing it. VS/RS configs
457 // will be returned as well.
458 $record['rspool'] = array();
459 $query = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
460 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
461 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
a685e6d7
DO
462 "where vs_id = ? order by pool.name, object_id";
463 $result = usePreparedSelectBlade ($query, array ($record['id']));
7c38462f
DO
464 while ($row = $result->fetch (PDO::FETCH_ASSOC))
465 {
466 if (!isset ($record['rspool'][$row['id']]))
467 $record['rspool'][$row['id']] = array
468 (
469 'name' => $row['name'],
470 'vsconfig' => $row['vsconfig'],
471 'rsconfig' => $row['rsconfig'],
472 'lblist' => array(),
473 );
474 if ($row['object_id'] == NULL)
475 continue;
476 $record['rspool'][$row['id']]['lblist'][$row['object_id']] = array
477 (
478 'vsconfig' => $row['lb_vsconfig'],
479 'rsconfig' => $row['lb_rsconfig'],
480 );
481 }
482 unset ($result);
483 break;
61a1d996
DO
484 case 'rack':
485 $record['mountedObjects'] = array();
486 // start with default rackspace
487 for ($i = $record['height']; $i > 0; $i--)
488 for ($locidx = 0; $locidx < 3; $locidx++)
489 $record[$i][$locidx]['state'] = 'F';
490 // load difference
491 $query =
492 "select unit_no, atom, state, object_id " .
a685e6d7
DO
493 "from RackSpace where rack_id = ? and " .
494 "unit_no between 1 and ? order by unit_no";
495 $result = usePreparedSelectBlade ($query, array ($record['id'], $record['height']));
61a1d996
DO
496 global $loclist;
497 $mounted_objects = array();
498 while ($row = $result->fetch (PDO::FETCH_ASSOC))
499 {
500 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
501 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
502 if ($row['state'] == 'T' and $row['object_id'] != NULL)
503 $mounted_objects[$row['object_id']] = TRUE;
504 }
505 $record['mountedObjects'] = array_keys ($mounted_objects);
506 unset ($result);
507 break;
a5f9d1ca
DO
508 case 'ipv4net':
509 $record['8021q'] = getIPv4Network8021QBindings ($record['id']);
510 break;
d08d766d
DO
511 default:
512 }
513}
514
125b5f39 515function getObjectPortsAndLinks ($object_id)
e673ee24 516{
9f75e165 517 $query = "SELECT id, name, label, l2address, iif_id, (SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name, " .
045bab87 518 "type AS oif_id, (SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, reservation_comment " .
298d2375 519 "FROM Port WHERE object_id = ?";
1919110a 520 // list and decode all ports of the current object
298d2375 521 $result = usePreparedSelectBlade ($query, array ($object_id));
e425f895 522 $ret=array();
e425f895 523 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 524 {
1919110a
DO
525 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
526 $row['remote_id'] = NULL;
527 $row['remote_name'] = NULL;
528 $row['remote_object_id'] = NULL;
1919110a
DO
529 $ret[] = $row;
530 }
531 unset ($result);
532 // now find and decode remote ends for all locally terminated connections
125b5f39 533 // FIXME: can't this data be extracted in one pass with sub-queries?
1919110a
DO
534 foreach (array_keys ($ret) as $tmpkey)
535 {
536 $portid = $ret[$tmpkey]['id'];
537 $remote_id = NULL;
298d2375
DO
538 $query = "select porta, portb from Link where porta = ? or portb = ?";
539 $result = usePreparedSelectBlade ($query, array ($portid, $portid));
1919110a 540 if ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 541 {
1919110a
DO
542 if ($portid != $row['porta'])
543 $remote_id = $row['porta'];
544 elseif ($portid != $row['portb'])
545 $remote_id = $row['portb'];
546 }
547 unset ($result);
548 if ($remote_id) // there's a remote end here
549 {
298d2375
DO
550 $query = "SELECT name, object_id FROM Port WHERE id = ?";
551 $result = usePreparedSelectBlade ($query, array ($remote_id));
1919110a
DO
552 if ($row = $result->fetch (PDO::FETCH_ASSOC))
553 {
cd3775e9 554 $ret[$tmpkey]['remote_name'] = $row['name'];
1919110a 555 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
1919110a
DO
556 }
557 $ret[$tmpkey]['remote_id'] = $remote_id;
558 unset ($result);
e673ee24
DO
559 }
560 }
9f75e165 561 usort ($ret, 'sortByName');
e673ee24
DO
562 return $ret;
563}
564
f19c75d6 565function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
e673ee24 566{
59a83bd8 567 if ($row_id <= 0 or $height <= 0 or !strlen ($name))
f19c75d6 568 return FALSE;
298d2375 569 $result = usePreparedInsertBlade
406b54bd
DO
570 (
571 'Rack',
572 array
573 (
574 'row_id' => $row_id,
298d2375 575 'name' => $name,
406b54bd 576 'height' => $height,
298d2375 577 'comment' => $comment
406b54bd
DO
578 )
579 );
c63a8d6e 580 $last_insert_id = lastInsertID();
32832c0e 581 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', $last_insert_id);
e673ee24
DO
582}
583
f60bb422 584function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
e673ee24 585{
f60bb422
DO
586 // Maintain UNIQUE INDEX for common names and asset tags by
587 // filtering out empty strings (not NULLs).
298d2375 588 $result1 = usePreparedInsertBlade
f60bb422
DO
589 (
590 'RackObject',
591 array
592 (
298d2375 593 'name' => !strlen ($new_name) ? NULL : $new_name,
650ef981 594 'label' => $new_label,
298d2375 595 'barcode' => !strlen ($new_barcode) ? NULL : $new_barcode,
f60bb422 596 'objtype_id' => $new_type_id,
298d2375 597 'asset_no' => !strlen ($new_asset_no) ? NULL : $new_asset_no,
f60bb422
DO
598 )
599 );
c63a8d6e 600 $last_insert_id = lastInsertID();
ad0e4754
DO
601 // Do AutoPorts magic
602 executeAutoPorts ($last_insert_id, $new_type_id);
f60bb422 603 // Now tags...
351c0966 604 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
fee7977b 605
32832c0e 606 recordHistory ('RackObject', $last_insert_id);
fee7977b
DO
607
608 return $last_insert_id;
e673ee24
DO
609}
610
611function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
612{
178fda20 613 if ($new_type_id == 0)
c5f84f48 614 throw new InvalidArgException ('$new_type_id', $new_type_id);
b02b2455 615 $ret = FALSE !== usePreparedExecuteBlade
39eadd27
DO
616 (
617 'UPDATE RackObject SET name=?, label=?, barcode=?, objtype_id=?, has_problems=?, ' .
618 'asset_no=?, comment=? WHERE id=?',
619 array
620 (
621 !strlen ($new_name) ? NULL : $new_name,
622 $new_label,
623 !strlen ($new_barcode) ? NULL : $new_barcode,
624 $new_type_id,
625 $new_has_problems,
626 !strlen ($new_asset_no) ? NULL : $new_asset_no,
627 $new_comment,
628 $object_id
629 )
630 );
32832c0e 631 return $ret and recordHistory ('RackObject', $object_id);
e673ee24
DO
632}
633
6657739e
DO
634// Remove file links related to the entity, but leave the entity and file(s) intact.
635function releaseFiles ($entity_realm, $entity_id)
636{
298d2375 637 usePreparedDeleteBlade ('FileLink', array ('entity_type' => $entity_realm, 'entity_id' => $entity_id));
6657739e
DO
638}
639
52b34485
AD
640// There are times when you want to delete all traces of an object
641function commitDeleteObject ($object_id = 0)
642{
6657739e 643 releaseFiles ('object', $object_id);
29c3a4d8 644 destroyTagsForEntity ('object', $object_id);
298d2375
DO
645 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
646 usePreparedDeleteBlade ('IPv4Allocation', array ('object_id' => $object_id));
647 usePreparedDeleteBlade ('IPv4NAT', array ('object_id' => $object_id));
39eadd27
DO
648 usePreparedExecuteBlade ('DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
649 usePreparedExecuteBlade ('DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
298d2375 650 usePreparedDeleteBlade ('RackObject', array ('id' => $object_id));
52b34485
AD
651 return '';
652}
653
c8187437
DY
654function commitDeleteRack($rack_id)
655{
6657739e 656 releaseFiles ('rack', $rack_id);
29c3a4d8 657 destroyTagsForEntity ('rack', $rack_id);
298d2375
DO
658 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
659 usePreparedDeleteBlade ('RackHistory', array ('id' => $rack_id));
660 usePreparedDeleteBlade ('Rack', array ('id' => $rack_id));
c8187437
DY
661 return TRUE;
662}
663
e673ee24
DO
664function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
665{
7d70d643 666 // Can't shrink a rack if rows being deleted contain mounted objects
298d2375 667 $check_result = usePreparedSelectBlade ('SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = ? AND unit_no > ?', array ($rack_id, $new_height));
7d70d643 668 $check_row = $check_result->fetch (PDO::FETCH_ASSOC);
de9067c2 669 unset ($check_result);
39eadd27 670 if ($check_row['count'] > 0)
0cc24e9a 671 throw new InvalidArgException ('new_height', $new_height, 'Cannot shrink rack, objects are still mounted there');
7d70d643 672
39eadd27
DO
673 usePreparedExecuteBlade
674 (
675 'UPDATE Rack SET name=?, height=?, comment=?, row_id=? WHERE id=?',
676 array
677 (
678 $new_name,
679 $new_height,
680 $new_comment,
681 $new_row_id,
682 $rack_id,
683 )
684 );
32832c0e 685 return recordHistory ('Rack', $rack_id);
e673ee24
DO
686}
687
61a1d996 688// This function accepts rack data returned by amplifyCell(), validates and applies changes
e673ee24
DO
689// supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
690// correspond to current rack ID.
691// 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
692// If 4th arg is present, object_id fields will be updated accordingly to the new state.
693// The function returns the modified rack upon success.
694function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
695{
32832c0e 696 global $loclist;
e673ee24
DO
697 $rack_id = $rackData['id'];
698 $rack_name = $rackData['name'];
699 $rackchanged = FALSE;
700 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
701 {
702 for ($locidx = 0; $locidx < 3; $locidx++)
703 {
704 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
705 continue;
706 // detect a change
707 $state = $rackData[$unit_no][$locidx]['state'];
708 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
709 $newstate = $checked_state;
710 else
711 $newstate = $unchecked_state;
712 if ($state == $newstate)
713 continue;
714 $rackchanged = TRUE;
715 // and validate
716 $atom = $loclist[$locidx];
717 // The only changes allowed are those introduced by checkbox grid.
718 if
719 (
720 !($state == $checked_state && $newstate == $unchecked_state) &&
721 !($state == $unchecked_state && $newstate == $checked_state)
722 )
723 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
724 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
725 // anyway and then looking for probable need of INSERT.
32832c0e 726 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom));
e673ee24 727 if ($newstate != 'F')
32832c0e 728 usePreparedInsertBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom, 'state' => $newstate));
e673ee24
DO
729 if ($newstate == 'T' and $object_id != 0)
730 {
731 // At this point we already have a record in RackSpace.
32832c0e
DO
732 $r = usePreparedExecuteBlade
733 (
734 'UPDATE RackSpace SET object_id=? ' .
735 'WHERE rack_id=? AND unit_no=? AND atom=?',
736 array ($object_id, $rack_id, $unit_no, $atom)
737 );
738 if ($r === FALSE)
e673ee24 739 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
32832c0e 740 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
e673ee24
DO
741 }
742 }
743 }
744 if ($rackchanged)
c7fe33be
DO
745 {
746 resetThumbCache ($rack_id);
e673ee24 747 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
c7fe33be 748 }
e673ee24
DO
749 else
750 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
751}
752
753// This function builds a list of rack-unit-atom records, which are assigned to
754// the requested object.
298d2375 755function getMoleculeForObject ($object_id)
e673ee24 756{
298d2375
DO
757 $result = usePreparedSelectBlade
758 (
759 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
760 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
761 array ($object_id)
762 );
763 return $result->fetchAll (PDO::FETCH_ASSOC);
e673ee24
DO
764}
765
766// This function builds a list of rack-unit-atom records for requested molecule.
767function getMolecule ($mid = 0)
768{
298d2375
DO
769 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
770 return $result->fetchAll (PDO::FETCH_ASSOC);
e673ee24
DO
771}
772
c63a8d6e
DO
773// returns exactly what is's named after
774function lastInsertID ()
775{
a685e6d7 776 $result = usePreparedSelectBlade ('select last_insert_id()');
c63a8d6e
DO
777 $row = $result->fetch (PDO::FETCH_NUM);
778 return $row[0];
779}
780
e673ee24
DO
781// This function creates a new record in Molecule and number of linked
782// R-U-A records in Atom.
783function createMolecule ($molData)
784{
32832c0e 785 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
c63a8d6e 786 $molecule_id = lastInsertID();
64b95774 787 foreach ($molData as $rua)
298d2375
DO
788 usePreparedInsertBlade
789 (
790 'Atom',
791 array
792 (
793 'molecule_id' => $molecule_id,
794 'rack_id' => $rua['rack_id'],
795 'unit_no' => $rua['unit_no'],
796 'atom' => $rua['atom'],
797 )
798 );
e673ee24
DO
799 return $molecule_id;
800}
801
802// History logger. This function assumes certain table naming convention and
803// column design:
804// 1. History table name equals to dictionary table name plus 'History'.
805// 2. History table must have the same row set (w/o keys) plus one row named
806// 'ctime' of type 'timestamp'.
32832c0e 807function recordHistory ($tableName, $orig_id)
e673ee24 808{
32832c0e
DO
809 global $remote_username;
810 return FALSE !== usePreparedExecuteBlade
811 (
812 "INSERT INTO ${tableName}History SELECT *, CURRENT_TIMESTAMP(), ? " .
813 "FROM ${tableName} WHERE id=?",
814 array ($remote_username, $orig_id)
815 );
e673ee24
DO
816}
817
818function getRackspaceHistory ()
819{
298d2375
DO
820 $result = usePreparedSelectBlade
821 (
7fa7047a 822 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
298d2375
DO
823 "MountOperation ORDER BY ctime DESC"
824 );
7fa7047a 825 return $result->fetchAll (PDO::FETCH_ASSOC);
e673ee24
DO
826}
827
828// This function is used in renderRackspaceHistory()
829function getOperationMolecules ($op_id = 0)
830{
298d2375 831 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
e673ee24
DO
832 // We expect one row.
833 $row = $result->fetch (PDO::FETCH_ASSOC);
298d2375 834 return array ($row['old_molecule_id'], $row['new_molecule_id']);
e673ee24
DO
835}
836
c7fe33be 837function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
e673ee24 838{
298d2375 839 $result = usePreparedSelectBlade ('SELECT DISTINCT rack_id FROM RackSpace WHERE object_id = ? ORDER BY rack_id', array ($object_id));
e673ee24 840 $rows = $result->fetchAll (PDO::FETCH_NUM);
61a1d996 841 unset ($result);
e673ee24
DO
842 $ret = array();
843 foreach ($rows as $row)
844 {
b422aee6
DO
845 if (!$fetch_rackdata)
846 {
847 $ret[$row[0]] = $row[0];
848 continue;
849 }
0cc24e9a 850 $rackData = spotEntity ('rack', $row[0]);
61a1d996 851 amplifyCell ($rackData);
e673ee24
DO
852 $ret[$row[0]] = $rackData;
853 }
e673ee24
DO
854 return $ret;
855}
856
e673ee24
DO
857function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
858{
05771508
DO
859 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
860 return "Invalid L2 address ${port_l2address}";
029a14bc
DO
861 global $dbxlink;
862 $dbxlink->exec ('LOCK TABLES Port WRITE');
863 if (alreadyUsedL2Address ($db_l2address, $object_id))
864 {
865 $dbxlink->exec ('UNLOCK TABLES');
866 return "address ${db_l2address} belongs to another object";
867 }
3153a326
DO
868 $matches = array();
869 switch (1)
870 {
871 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
872 $iif_id = $matches[1];
873 $oif_id = $matches[2];
874 break;
875 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
876 $iif_id = 1;
877 $oif_id = $matches[1];
878 break;
879 default:
880 $dbxlink->exec ('UNLOCK TABLES');
881 return "invalid port type id '${port_type_id}'";
882 }
298d2375 883 $result = usePreparedInsertBlade
e673ee24
DO
884 (
885 'Port',
886 array
887 (
298d2375 888 'name' => $port_name,
3153a326 889 'object_id' => $object_id,
298d2375 890 'label' => $port_label,
3153a326
DO
891 'iif_id' => $iif_id,
892 'type' => $oif_id,
298d2375 893 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
e673ee24
DO
894 )
895 );
029a14bc 896 $dbxlink->exec ('UNLOCK TABLES');
e673ee24
DO
897 if ($result)
898 return '';
899 else
900 return 'SQL query failed';
901}
902
d0a69ce8
DO
903// The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
904// string value. In case it is omitted, we just assign it its current value.
905// It would be nice to simplify this semantics later.
6be06cbb 906function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
e673ee24 907{
05771508
DO
908 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
909 return "Invalid L2 address ${port_l2address}";
029a14bc
DO
910 global $dbxlink;
911 $dbxlink->exec ('LOCK TABLES Port WRITE');
912 if (alreadyUsedL2Address ($db_l2address, $object_id))
913 {
914 $dbxlink->exec ('UNLOCK TABLES');
915 return "address ${db_l2address} belongs to another object";
916 }
a5c589d2
DO
917 $result = usePreparedExecuteBlade
918 (
919 'UPDATE Port SET name=?, type=?, label=?, reservation_comment=?, ' .
920 'l2address=? WHERE id=? AND object_id=?',
921 array
922 (
923 $port_name,
924 $port_type_id,
925 $port_label,
926 $port_reservation_comment,
927 ($db_l2address === '') ? NULL : $db_l2address,
928 $port_id,
929 $object_id
930 )
931 );
029a14bc 932 $dbxlink->exec ('UNLOCK TABLES');
e673ee24
DO
933 if ($result == 1)
934 return '';
935 $errorInfo = $dbxlink->errorInfo();
936 // We could update nothing.
937 if ($errorInfo[0] == '00000')
938 return '';
939 return $errorInfo[2];
940}
941
942function delObjectPort ($port_id)
943{
298d2375
DO
944 if (usePreparedDeleteBlade ('Port', array ('id' => $port_id)) != TRUE)
945 return __FUNCTION__ . ': usePreparedDeleteBlade() failed';
e673ee24
DO
946 return '';
947}
948
6ef9683b 949function getAllIPv4Allocations ()
e673ee24 950{
298d2375
DO
951 $result = usePreparedSelectBlade
952 (
e673ee24
DO
953 "select object_id as object_id, ".
954 "RackObject.name as object_name, ".
706ce117 955 "IPv4Allocation.name as name, ".
e673ee24 956 "INET_NTOA(ip) as ip ".
298d2375
DO
957 "from IPv4Allocation join RackObject on id=object_id "
958 );
e673ee24 959 $ret = array();
e673ee24 960 while ($row = $result->fetch (PDO::FETCH_ASSOC))
298d2375 961 $ret[] = $row;
e673ee24
DO
962 return $ret;
963}
964
e673ee24
DO
965function linkPorts ($porta, $portb)
966{
967 if ($porta == $portb)
32832c0e 968 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
e673ee24
DO
969 if ($porta > $portb)
970 {
971 $tmp = $porta;
972 $porta = $portb;
973 $portb = $tmp;
974 }
32832c0e
DO
975 $ret = FALSE !== usePreparedInsertBlade ('Link', array ('porta' => $porta, 'portb' => $portb));
976 $ret = $ret and FALSE !== usePreparedExecuteBlade
977 (
978 'UPDATE Port SET reservation_comment=NULL WHERE id IN(?, ?)',
979 array ($porta, $portb)
980 );
981 return $ret ? '' : 'query failed';
e673ee24
DO
982}
983
cd3775e9 984function unlinkPort ($port_id)
e673ee24 985{
298d2375 986 usePreparedDeleteBlade ('Link', array ('porta' => $port_id, 'portb' => $port_id), 'OR');
e673ee24 987 return '';
e673ee24
DO
988}
989
2c817354
DO
990// Return all IPv4 addresses allocated to the objects. Attach detailed
991// info about address to each alocation records. Index result by dotted-quad
992// address.
0ab782bc
DO
993function getObjectIPv4Allocations ($object_id = 0)
994{
995 $ret = array();
298d2375
DO
996 $result = usePreparedSelectBlade
997 (
998 'SELECT name AS osif, type, inet_ntoa(ip) AS dottedquad FROM IPv4Allocation ' .
999 'WHERE object_id = ? ORDER BY ip',
1000 array ($object_id)
650ef981 1001 );
85970da2 1002 // don't spawn a sub-query with unfetched buffer, it may fail
0ab782bc 1003 while ($row = $result->fetch (PDO::FETCH_ASSOC))
85970da2
DO
1004 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1005 unset ($result);
1006 foreach (array_keys ($ret) as $dottedquad)
1007 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
0ab782bc
DO
1008 return $ret;
1009}
1010
e6ca609a
DO
1011// Return minimal IPv4 address, optionally with "ip" key set, if requested.
1012function constructIPv4Address ($dottedquad = NULL)
a910829d 1013{
e6ca609a 1014 $ret = array
a910829d
DO
1015 (
1016 'name' => '',
1017 'reserved' => 'no',
a910829d
DO
1018 'outpf' => array(),
1019 'inpf' => array(),
a910829d 1020 'rslist' => array(),
2d318652 1021 'allocs' => array(),
a910829d
DO
1022 'lblist' => array()
1023 );
e6ca609a
DO
1024 if ($dottedquad != NULL)
1025 $ret['ip'] = $dottedquad;
1026 return $ret;
1027}
1028
1029// Check the range requested for meaningful IPv4 records, build them
1030// into a list and return. Return an empty list if nothing matched.
1031// Both arguments are expected in signed int32 form. The resulting list
1032// is keyed by uint32 form of each IP address, items aren't sorted.
f7414fa5
DO
1033// LATER: accept a list of pairs and build WHERE sub-expression accordingly
1034function scanIPv4Space ($pairlist)
e6ca609a
DO
1035{
1036 $ret = array();
f7414fa5 1037 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
178fda20 1038 return $ret;
f7414fa5
DO
1039 // FIXME: this is a copy-and-paste prototype
1040 $or = '';
1041 $whereexpr1 = '(';
1042 $whereexpr2 = '(';
1043 $whereexpr3 = '(';
1044 $whereexpr4 = '(';
1045 $whereexpr5a = '(';
1046 $whereexpr5b = '(';
a5c589d2 1047 $qparams = array();
f7414fa5
DO
1048 foreach ($pairlist as $tmp)
1049 {
1050 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
1051 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
a5c589d2
DO
1052 $whereexpr1 .= $or . "ip between ? and ?";
1053 $whereexpr2 .= $or . "ip between ? and ?";
1054 $whereexpr3 .= $or . "vip between ? and ?";
1055 $whereexpr4 .= $or . "rsip between ? and ?";
1056 $whereexpr5a .= $or . "remoteip between ? and ?";
1057 $whereexpr5b .= $or . "localip between ? and ?";
f7414fa5 1058 $or = ' or ';
a5c589d2
DO
1059 $qparams[] = $db_first;
1060 $qparams[] = $db_last;
f7414fa5
DO
1061 }
1062 $whereexpr1 .= ')';
1063 $whereexpr2 .= ')';
1064 $whereexpr3 .= ')';
1065 $whereexpr4 .= ')';
1066 $whereexpr5a .= ')';
1067 $whereexpr5b .= ')';
a910829d
DO
1068
1069 // 1. collect labels and reservations
706ce117 1070 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
f7414fa5 1071 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
a5c589d2 1072 $result = usePreparedSelectBlade ($query, $qparams);
a910829d
DO
1073 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1074 {
2d318652
DO
1075 $ip_bin = ip2long ($row['ip']);
1076 if (!isset ($ret[$ip_bin]))
e6ca609a 1077 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
2d318652
DO
1078 $ret[$ip_bin]['name'] = $row['name'];
1079 $ret[$ip_bin]['reserved'] = $row['reserved'];
a910829d
DO
1080 }
1081 unset ($result);
1082
1083 // 2. check for allocations
1084 $query =
a1f97745
DO
1085 "select INET_NTOA(ip) as ip, object_id, name, type " .
1086 "from IPv4Allocation where ${whereexpr2} order by type";
a5c589d2 1087 $result = usePreparedSelectBlade ($query, $qparams);
a1f97745
DO
1088 // release DBX early to avoid issues with nested spotEntity() calls
1089 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1090 unset ($result);
1091 foreach ($allRows as $row)
a910829d 1092 {
2d318652
DO
1093 $ip_bin = ip2long ($row['ip']);
1094 if (!isset ($ret[$ip_bin]))
e6ca609a 1095 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a1f97745
DO
1096 $oinfo = spotEntity ('object', $row['object_id']);
1097 $ret[$ip_bin]['allocs'][] = array
1098 (
1099 'type' => $row['type'],
1100 'name' => $row['name'],
1101 'object_id' => $row['object_id'],
1102 'object_name' => $oinfo['dname'],
1103 );
a910829d 1104 }
a910829d
DO
1105
1106 // 3. look for virtual services and related LB
a1f97745
DO
1107 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, object_id " .
1108 "from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1109 "where ${whereexpr3} order by vport, proto, object_id";
a5c589d2 1110 $result = usePreparedSelectBlade ($query, $qparams);
a1f97745
DO
1111 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1112 unset ($result);
1113 foreach ($allRows as $row)
a910829d 1114 {
2d318652 1115 $ip_bin = ip2long ($row['ip']);
f3d0cb20 1116 if (!isset ($ret[$ip_bin]))
e6ca609a 1117 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a1f97745
DO
1118 $oinfo = spotEntity ('object', $row['object_id']);
1119 $ret[$ip_bin]['lblist'][] = array
1120 (
1121 'vport' => $row['vport'],
1122 'proto' => $row['proto'],
1123 'vs_id' => $row['vs_id'],
1124 'name' => $row['name'],
1125 'vip' => $row['ip'],
1126 'object_id' => $row['object_id'],
1127 'object_name' => $oinfo['dname'],
1128 );
a910829d 1129 }
a910829d
DO
1130
1131 // 4. don't forget about real servers along with pools
2d318652 1132 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
706ce117 1133 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
f7414fa5 1134 "where ${whereexpr4} " .
a910829d 1135 "order by ip, rsport, rspool_id";
a5c589d2 1136 $result = usePreparedSelectBlade ($query, $qparams);
a910829d
DO
1137 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1138 {
2d318652
DO
1139 $ip_bin = ip2long ($row['ip']);
1140 if (!isset ($ret[$ip_bin]))
e6ca609a 1141 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1142 $tmp = array();
1143 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1144 $tmp[$cname] = $row[$cname];
2d318652 1145 $ret[$ip_bin]['rslist'][] = $tmp;
a910829d
DO
1146 }
1147 unset ($result);
1148
1149 // 5. add NAT rules, part 1
1150 $query =
1151 "select " .
1152 "proto, " .
1153 "INET_NTOA(localip) as localip, " .
1154 "localport, " .
1155 "INET_NTOA(remoteip) as remoteip, " .
1156 "remoteport, " .
1157 "description " .
706ce117 1158 "from IPv4NAT " .
51332e78 1159 "where ${whereexpr5a} " .
a910829d 1160 "order by localip, localport, remoteip, remoteport, proto";
a5c589d2 1161 $result = usePreparedSelectBlade ($query, $qparams);
a910829d
DO
1162 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1163 {
2d318652 1164 $remoteip_bin = ip2long ($row['remoteip']);
51332e78
DO
1165 if (!isset ($ret[$remoteip_bin]))
1166 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1167 $ret[$remoteip_bin]['inpf'][] = $row;
1168 }
1169 unset ($result);
1170 // 5. add NAT rules, part 2
1171 $query =
1172 "select " .
1173 "proto, " .
1174 "INET_NTOA(localip) as localip, " .
1175 "localport, " .
1176 "INET_NTOA(remoteip) as remoteip, " .
1177 "remoteport, " .
1178 "description " .
706ce117 1179 "from IPv4NAT " .
51332e78
DO
1180 "where ${whereexpr5b} " .
1181 "order by localip, localport, remoteip, remoteport, proto";
a5c589d2 1182 $result = usePreparedSelectBlade ($query, $qparams);
51332e78
DO
1183 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1184 {
2d318652 1185 $localip_bin = ip2long ($row['localip']);
51332e78
DO
1186 if (!isset ($ret[$localip_bin]))
1187 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1188 $ret[$localip_bin]['outpf'][] = $row;
a910829d 1189 }
51332e78 1190 unset ($result);
a910829d
DO
1191 return $ret;
1192}
1193
2d318652
DO
1194function getIPv4Address ($dottedquad = '')
1195{
1196 if ($dottedquad == '')
c5f84f48 1197 throw new InvalidArgException ('$dottedquad', $dottedquad);
2d318652 1198 $i32 = ip2long ($dottedquad); // signed 32 bit
f7414fa5 1199 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
2d318652 1200 if (!isset ($scanres[$i32]))
8b980e24 1201 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
e6ca609a 1202 return constructIPv4Address ($dottedquad);
2d318652
DO
1203 markupIPv4AddrList ($scanres);
1204 return $scanres[$i32];
a910829d
DO
1205}
1206
5222f192
DO
1207function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1208{
a5c589d2 1209 $result = usePreparedExecuteBlade
5222f192 1210 (
a5c589d2
DO
1211 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1212 array ($ip, $object_id, $name, $type)
5222f192 1213 );
a5c589d2 1214 return $result ? '' : (__FUNCTION__ . '(): query failed');
5222f192
DO
1215}
1216
bb0a44e9 1217// Return the id of the smallest IPv4 network containing the given IPv4 address
d65353ad
DO
1218// or NULL, if nothing was found. When finding the covering network for
1219// another network, it is important to filter out matched records with longer
1220// masks (they aren't going to be the right pick).
1221function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
e673ee24 1222{
3702d093
DO
1223// N.B. To perform the same for IPv6 address and networks, some pre-requisites
1224// are necessary and a different query. IPv6 addresses are 128 bit long, which
1225// is too much for both PHP and MySQL data types. These values must be split
1226// into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1227// Then each network must have its 128-bit netmask split same way and either
1228// stored right in its record or JOINed from decoder and accessible as m_u32_0,
1229// m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1230// covering the given address would look as follows:
1231// $query = 'select id from IPv6Network as n where ' .
1232// "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1233// "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1234// "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1235// "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1236// "mask < ${masklen} " .
1237// 'order by mask desc limit 1';
1238
706ce117 1239 $query = 'select id from IPv4Network where ' .
650ef981 1240 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
298d2375 1241 "and mask < ? " .
bb0a44e9 1242 'order by mask desc limit 1';
298d2375 1243 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
bb0a44e9
DO
1244 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1245 return $row['id'];
e673ee24
DO
1246 return NULL;
1247}
1248
99ab184f 1249function updateIPv4Network_real ($id = 0, $name = '', $comment = '')
e673ee24
DO
1250{
1251 global $dbxlink;
99ab184f
DO
1252 $query = $dbxlink->prepare ('UPDATE IPv4Network SET name = ?, comment = ? WHERE id = ?');
1253 // TODO: $dbxlink->setAttribute (PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
1254 return $query->execute (array ($name, $comment, $id)) ? '' : 'SQL query failed in ' . __FUNCTION__;
e673ee24
DO
1255}
1256
1257// This function is actually used not only to update, but also to create records,
1258// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1259// (MySQL 4.0 workaround).
b4c1ef87 1260function updateAddress ($ip = 0, $name = '', $reserved = 'no')
e673ee24 1261{
32832c0e 1262 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
e673ee24
DO
1263 // INSERT may appear not necessary.
1264 if ($name == '' and $reserved == 'no')
1265 return '';
32832c0e
DO
1266 $ret = usePreparedExecuteBlade
1267 (
1268 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1269 array ($name, $reserved, $ip)
1270 );
1271 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
e673ee24
DO
1272}
1273
e673ee24
DO
1274function updateBond ($ip='', $object_id=0, $name='', $type='')
1275{
32832c0e
DO
1276 return usePreparedExecuteBlade
1277 (
1278 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1279 array ($name, $type, $ip, $object_id)
1280 );
e673ee24
DO
1281}
1282
1283function unbindIpFromObject ($ip='', $object_id=0)
1284{
32832c0e
DO
1285 return usePreparedExecuteBlade
1286 (
1287 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1288 array ($ip, $object_id)
1289 );
e673ee24
DO
1290}
1291
ea5fc465
DO
1292function getIPv4PrefixSearchResult ($terms)
1293{
6df2025d
DO
1294 $byname = getSearchResultByField
1295 (
1296 'IPv4Network',
1297 array ('id'),
1298 'name',
1299 $terms,
1300 'ip'
1301 );
ea5fc465 1302 $ret = array();
6df2025d
DO
1303 foreach ($byname as $row)
1304 $ret[] = spotEntity ('ipv4net', $row['id']);
ea5fc465
DO
1305 return $ret;
1306}
1307
1308function getIPv4AddressSearchResult ($terms)
1309{
706ce117 1310 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
ea5fc465 1311 $or = '';
a685e6d7 1312 $qparams = array();
ea5fc465
DO
1313 foreach (explode (' ', $terms) as $term)
1314 {
a685e6d7 1315 $query .= $or . "name like ?";
ea5fc465 1316 $or = ' or ';
a685e6d7 1317 $qparams[] = "%${term}%";
ea5fc465 1318 }
a685e6d7 1319 $result = usePreparedSelectBlade ($query, $qparams);
ea5fc465
DO
1320 $ret = array();
1321 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1322 $ret[] = $row;
1323 return $ret;
1324}
1325
05411ccd
DO
1326function getIPv4RSPoolSearchResult ($terms)
1327{
6cd32e3c
DO
1328 $byname = getSearchResultByField
1329 (
1330 'IPv4RSPool',
1331 array ('id'),
1332 'name',
1333 $terms,
1334 'name'
1335 );
05411ccd 1336 $ret = array();
6cd32e3c
DO
1337 foreach ($byname as $row)
1338 $ret[] = spotEntity ('ipv4rspool', $row['id']);
05411ccd
DO
1339 return $ret;
1340}
1341
1342function getIPv4VServiceSearchResult ($terms)
1343{
6df2025d
DO
1344 $byname = getSearchResultByField
1345 (
1346 'IPv4VS',
1347 array ('id'),
1348 'name',
1349 $terms,
1350 'vip'
1351 );
05411ccd 1352 $ret = array();
6df2025d
DO
1353 foreach ($byname as $row)
1354 $ret[] = spotEntity ('ipv4vs', $row['id']);
05411ccd
DO
1355 return $ret;
1356}
1357
6a88e734
DO
1358function getAccountSearchResult ($terms)
1359{
ea62d9dc 1360 $byUsername = getSearchResultByField
6a88e734
DO
1361 (
1362 'UserAccount',
1363 array ('user_id', 'user_name', 'user_realname'),
1364 'user_name',
1365 $terms,
1366 'user_name'
1367 );
ea62d9dc
DO
1368 $byRealname = getSearchResultByField
1369 (
1370 'UserAccount',
1371 array ('user_id', 'user_name', 'user_realname'),
1372 'user_realname',
1373 $terms,
1374 'user_name'
1375 );
1376 // Filter out dupes.
1377 foreach ($byUsername as $res1)
1378 foreach (array_keys ($byRealname) as $key2)
1379 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1380 {
1381 unset ($byRealname[$key2]);
1382 continue 2;
1383 }
573214e0
DO
1384 $ret = array_merge ($byUsername, $byRealname);
1385 // Set realm, so it's renderable.
1386 foreach (array_keys ($ret) as $key)
1387 $ret[$key]['realm'] = 'user';
1388 return $ret;
6a88e734
DO
1389}
1390
e1ae3fb4
AD
1391function getFileSearchResult ($terms)
1392{
e531b4d6 1393 $byName = getSearchResultByField
e1ae3fb4
AD
1394 (
1395 'File',
6df2025d 1396 array ('id'),
e1ae3fb4
AD
1397 'name',
1398 $terms,
1399 'name'
1400 );
1401 $byComment = getSearchResultByField
1402 (
1403 'File',
6df2025d 1404 array ('id'),
e1ae3fb4
AD
1405 'comment',
1406 $terms,
1407 'name'
1408 );
1409 // Filter out dupes.
e531b4d6 1410 foreach ($byName as $res1)
e1ae3fb4
AD
1411 foreach (array_keys ($byComment) as $key2)
1412 if ($res1['id'] == $byComment[$key2]['id'])
1413 {
1414 unset ($byComment[$key2]);
1415 continue 2;
1416 }
6df2025d 1417 $ret = array();
e531b4d6 1418 foreach (array_merge ($byName, $byComment) as $row)
6df2025d
DO
1419 $ret[] = spotEntity ('file', $row['id']);
1420 return $ret;
e1ae3fb4
AD
1421}
1422
e531b4d6
DO
1423function getRackSearchResult ($terms)
1424{
1425 $byName = getSearchResultByField
1426 (
1427 'Rack',
1428 array ('id'),
1429 'name',
1430 $terms,
1431 'name'
1432 );
1433 $byComment = getSearchResultByField
1434 (
1435 'Rack',
1436 array ('id'),
1437 'comment',
1438 $terms,
1439 'name'
1440 );
1441 // Filter out dupes.
1442 foreach ($byName as $res1)
1443 foreach (array_keys ($byComment) as $key2)
1444 if ($res1['id'] == $byComment[$key2]['id'])
1445 {
1446 unset ($byComment[$key2]);
1447 continue 2;
1448 }
1449 $ret = array();
1450 foreach (array_merge ($byName, $byComment) as $row)
1451 $ret[] = spotEntity ('rack', $row['id']);
1452 return $ret;
1453}
1454
dfd80d8e 1455function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
6a88e734
DO
1456{
1457 $pfx = '';
1458 $query = 'select ';
a685e6d7 1459 $qparams = array();
6a88e734
DO
1460 foreach ($rcolumns as $col)
1461 {
1462 $query .= $pfx . $col;
1463 $pfx = ', ';
1464 }
1465 $pfx = '';
1466 $query .= " from ${tname} where ";
1467 foreach (explode (' ', $terms) as $term)
1468 {
dfd80d8e
DO
1469 switch ($exactness)
1470 {
1471 case 2: // does this work as expected?
a685e6d7
DO
1472 $query .= $pfx . "binary ${scolumn} = ?";
1473 $qparams[] = $term;
dfd80d8e
DO
1474 break;
1475 case 1:
a685e6d7
DO
1476 $query .= $pfx . "${scolumn} = ?";
1477 $qparams[] = $term;
dfd80d8e
DO
1478 break;
1479 default:
a685e6d7
DO
1480 $query .= $pfx . "${scolumn} like ?";
1481 $qparams[] = "%${term}%";
dfd80d8e
DO
1482 break;
1483 }
6a88e734
DO
1484 $pfx = ' or ';
1485 }
1486 if ($ocolumn != '')
1487 $query .= " order by ${ocolumn}";
a685e6d7 1488 $result = usePreparedSelectBlade ($query, $qparams);
6a88e734
DO
1489 $ret = array();
1490 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1491 $ret[] = $row;
1492 return $ret;
1493}
1494
b1f60545 1495function getObjectSearchResults ($what)
323edbbf
DO
1496{
1497 $ret = array();
1b4a0a6a
DO
1498 global $searchfunc;
1499 foreach ($searchfunc['object'] as $method => $func)
1500 foreach ($func ($what) as $objRecord)
1501 {
1502 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1503 $ret[$objRecord['id']][$method] = $objRecord[$method];
1504 }
b1f60545
DO
1505 return $ret;
1506}
1507
1508function getObjectAttrsSearchResults ($what)
1509{
1510 $ret = array();
1511 foreach (array ('name', 'label', 'asset_no', 'barcode') as $column)
1512 {
1513 $tmp = getSearchResultByField
1514 (
1515 'RackObject',
1516 array ('id'),
1517 $column,
1518 $what,
1519 $column
1520 );
1521 foreach ($tmp as $row)
1522 {
1523 $ret[$row['id']]['id'] = $row['id'];
1524 $ret[$row['id']]['by_attr'][] = $column;
1525 }
1526 }
323edbbf
DO
1527 return $ret;
1528}
1529
1530// Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1531// which matched. A partilar object_id could be returned more, than once, if it has
1532// multiple matching stickers. Search is only performed on "string" attributes.
1533function getStickerSearchResults ($what, $exactness = 0)
1534{
1535 $stickers = getSearchResultByField
1536 (
1537 'AttributeValue',
1538 array ('object_id', 'attr_id'),
1539 'string_value',
1540 $what,
1541 'object_id',
1542 $exactness
1543 );
1544 $map = getAttrMap();
1545 $ret = array();
1546 foreach ($stickers as $sticker)
1547 if ($map[$sticker['attr_id']]['type'] == 'string')
1548 {
1549 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
1550 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
1551 }
1552 return $ret;
1553}
1554
f1b5f68d 1555// search in port "reservation comment", "label" and "L2 address" columns
d516d719 1556function getPortSearchResults ($what)
323edbbf 1557{
f1b5f68d 1558 $ret = array();
323edbbf
DO
1559 $ports = getSearchResultByField
1560 (
1561 'Port',
1b4a0a6a 1562 array ('object_id', 'id', 'reservation_comment'),
323edbbf
DO
1563 'reservation_comment',
1564 $what,
1565 'object_id',
1566 0
1567 );
323edbbf
DO
1568 foreach ($ports as $port)
1569 {
1570 $ret[$port['object_id']]['id'] = $port['object_id'];
1b4a0a6a 1571 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
d516d719 1572 }
f1b5f68d
DO
1573 $ports = getSearchResultByField
1574 (
1575 'Port',
1576 array ('object_id', 'id', 'label'),
1577 'label',
1578 $what,
1579 'object_id',
1580 0
1581 );
1582 foreach ($ports as $port)
1583 {
1584 $ret[$port['object_id']]['id'] = $port['object_id'];
1585 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1586 }
d516d719
DO
1587 if (NULL === ($db_l2address = l2addressForDatabase ($what)))
1588 return $ret;
1589 $ports = getSearchResultByField
1590 (
1591 'Port',
1b4a0a6a 1592 array ('object_id', 'id', 'l2address'),
d516d719
DO
1593 'l2address',
1594 $db_l2address,
1595 'object_id',
1596 2
1597 );
1598 foreach ($ports as $port)
1599 {
1600 $ret[$port['object_id']]['id'] = $port['object_id'];
1b4a0a6a 1601 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
323edbbf
DO
1602 }
1603 return $ret;
1604}
1605
5fd2a004
DO
1606// search in IPv4 allocations
1607function getObjectIfacesSearchResults ($what)
1608{
1609 $ret = array();
1610 $ifaces = getSearchResultByField
1611 (
1612 'IPv4Allocation',
1613 array ('object_id', 'name'),
1614 'name',
1615 $what,
1616 'object_id'
1617 );
1618 foreach ($ifaces as $row)
1619 {
1620 $ret[$row['object_id']]['id'] = $row['object_id'];
1621 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1622 }
1623 return $ret;
1624}
1625
1626function getObjectNATSearchResults ($what)
1627{
1628 $ret = array();
1629 $ifaces = getSearchResultByField
1630 (
1631 'IPv4NAT',
1632 array ('object_id', 'description'),
1633 'description',
1634 $what,
1635 'object_id'
1636 );
1637 foreach ($ifaces as $row)
1638 {
1639 $ret[$row['object_id']]['id'] = $row['object_id'];
1640 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1641 }
1642 return $ret;
1643}
1644
1645// This function returns either port ID or NULL for specified arguments.
e9d357e1 1646function getPortIDs ($object_id, $port_name)
e673ee24 1647{
e9d357e1
DO
1648 $ret = array();
1649 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
1650 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1651 $ret[] = $row['id'];
1652 return $ret;
1653}
1654
1655// Search in "FQDN" attribute only, and return object ID, when there is exactly
1656// one result found (and NULL in any other case).
1657function searchByMgmtHostname ($string)
1658{
1659 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
e673ee24
DO
1660 $rows = $result->fetchAll (PDO::FETCH_NUM);
1661 if (count ($rows) != 1)
1662 return NULL;
e9d357e1 1663 return $rows[0][0];
e673ee24
DO
1664}
1665
1666function commitCreateUserAccount ($username, $realname, $password)
1667{
c9066b1c 1668 return usePreparedInsertBlade
e673ee24
DO
1669 (
1670 'UserAccount',
1671 array
1672 (
654e4636
DO
1673 'user_name' => $username,
1674 'user_realname' => $realname,
1675 'user_password_hash' => $password,
e673ee24
DO
1676 )
1677 );
1678}
1679
1680function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1681{
32832c0e
DO
1682 return usePreparedExecuteBlade
1683 (
1684 'UPDATE UserAccount SET user_name=?, user_realname=?, user_password_hash=? ' .
1685 'WHERE user_id=?',
1686 array ($new_username, $new_realname, $new_password, $id)
1687 );
e673ee24
DO
1688}
1689
e673ee24 1690// This function returns an array of all port type pairs from PortCompat table.
27ec21b2 1691function getPortOIFCompat ()
e673ee24 1692{
e673ee24
DO
1693 $query =
1694 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1695 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
27ec21b2
DO
1696 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1697 'ORDER BY type1name, type2name';
c9066b1c 1698 $result = usePreparedSelectBlade ($query);
27ec21b2 1699 return $result->fetchAll (PDO::FETCH_ASSOC);
e673ee24
DO
1700}
1701
a310dd80
DO
1702// Add a pair to the PortCompat table.
1703function commitSupplementPOIFC ($type1, $type2)
e673ee24 1704{
0cc24e9a
DY
1705 if ($type1 <= 0)
1706 throw new InvalidArgException ('type1', $type1);
1707 if ($type2 <= 0)
1708 throw new InvalidArgException ('type2', $type2);
c9066b1c 1709 return usePreparedInsertBlade
a310dd80
DO
1710 (
1711 'PortCompat',
1712 array ('type1' => $type1, 'type2' => $type2)
1713 );
e673ee24
DO
1714}
1715
a310dd80
DO
1716// Remove a pair from the PortCompat table.
1717function commitReducePOIFC ($type1, $type2)
e673ee24 1718{
c9066b1c 1719 return usePreparedDeleteBlade ('PortCompat', array ('type1' => $type1, 'type2' => $type2));
e673ee24
DO
1720}
1721
da95280e
DO
1722function getDictStats ()
1723{
63811a09 1724 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
c9066b1c
DO
1725 $result = usePreparedSelectBlade
1726 (
10bac82a 1727 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
c9066b1c
DO
1728 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
1729 );
da95280e 1730 $tc = $tw = $uc = $uw = 0;
89fa639f 1731 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1732 {
1733 $tc++;
1734 $tw += $row['wc'];;
1735 if (in_array ($row['chapter_no'], $stock_chapters))
1736 continue;
1737 $uc++;
1738 $uw += $row['wc'];;
1739 }
89fa639f
DO
1740 $result->closeCursor();
1741 unset ($result);
c9066b1c
DO
1742 $result = usePreparedSelectBlade
1743 (
1744 "select count(object_id) as attrc from RackObject as ro left join " .
1745 "AttributeValue as av on ro.id = av.object_id group by ro.id"
1746 );
08b4cb24 1747 $to = $ta = $so = 0;
89fa639f 1748 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1749 {
1750 $to++;
1751 if ($row['attrc'] != 0)
1752 {
1753 $so++;
1754 $ta += $row['attrc'];
1755 }
1756 }
89fa639f 1757 $result->closeCursor();
da95280e
DO
1758 $ret = array();
1759 $ret['Total chapters in dictionary'] = $tc;
1760 $ret['Total words in dictionary'] = $tw;
1761 $ret['User chapters'] = $uc;
1762 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1763 $ret['Total objects'] = $to;
1764 $ret['Objects with stickers'] = $so;
1765 $ret['Total stickers attached'] = $ta;
da95280e
DO
1766 return $ret;
1767}
1768
6807f0be 1769function getIPv4Stats ()
9ec5fdf1 1770{
9ec5fdf1
DO
1771 $ret = array();
1772 $subject = array();
706ce117
DO
1773 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1774 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1775 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1776 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1777 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1778 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1779 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1780 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
9ec5fdf1
DO
1781
1782 foreach ($subject as $item)
1783 {
c9066b1c 1784 $result = usePreparedSelectBlade ($item['q']);
9ec5fdf1
DO
1785 $row = $result->fetch (PDO::FETCH_NUM);
1786 $ret[$item['txt']] = $row[0];
1787 $result->closeCursor();
1788 unset ($result);
1789 }
1790 return $ret;
1791}
1792
6807f0be 1793function getRackspaceStats ()
9ec5fdf1 1794{
9ec5fdf1
DO
1795 $ret = array();
1796 $subject = array();
10bac82a 1797 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
9ec5fdf1
DO
1798 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1799 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1800 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1801
1802 foreach ($subject as $item)
1803 {
c9066b1c 1804 $result = usePreparedSelectBlade ($item['q']);
9ec5fdf1 1805 $row = $result->fetch (PDO::FETCH_NUM);
59a83bd8 1806 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1807 $result->closeCursor();
1808 unset ($result);
1809 }
1810 return $ret;
1811}
1812
6807f0be
DO
1813/*
1814
1815The following allows figuring out records in TagStorage, which refer to non-existing entities:
1816
120e9ddd
DO
1817mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1818mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1819mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1820mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1821mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1822mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1823mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
6807f0be
DO
1824
1825Accordingly, these are the records, which refer to non-existent tags:
1826
1827mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1828
1829*/
1830
826c3dbd 1831// chapter_no is a must, see at @commitReduceDictionary() why
e673ee24
DO
1832function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1833{
32832c0e
DO
1834 return usePreparedExecuteBlade
1835 (
1836 'UPDATE Dictionary SET dict_value=? WHERE chapter_id=? AND dict_key=?',
1837 array ($dict_value, $chapter_no, $dict_key)
1838 );
e673ee24
DO
1839}
1840
1841function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1842{
c5f84f48
DY
1843 if ($chapter_no <= 0)
1844 throw new InvalidArgException ('$chapter_no', $chapter_no);
1845 if (!strlen ($dict_value))
1846 throw new InvalidArgException ('$dict_value', $dict_value);
c9066b1c 1847 return usePreparedInsertBlade
e673ee24
DO
1848 (
1849 'Dictionary',
c9066b1c 1850 array ('chapter_id' => $chapter_no, 'dict_value' => $dict_value)
e673ee24
DO
1851 );
1852}
1853
178fda20
DO
1854// Technically dict_key is enough to delete, but including chapter_id into
1855// WHERE clause makes sure, that the action actually happends for the same
1856// chapter, which authorization was granted for.
e673ee24
DO
1857function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1858{
c9066b1c 1859 return usePreparedDeleteBlade ('Dictionary', array ('chapter_id' => $chapter_no, 'dict_key' => $dict_key));
e673ee24
DO
1860}
1861
1862function commitAddChapter ($chapter_name = '')
1863{
59a83bd8 1864 if (!strlen ($chapter_name))
c5f84f48 1865 throw new InvalidArgException ('$chapter_name', $chapter_name);
c9066b1c 1866 return usePreparedInsertBlade
e673ee24
DO
1867 (
1868 'Chapter',
c9066b1c 1869 array ('name' => $chapter_name)
e673ee24
DO
1870 );
1871}
1872
1873function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1874{
178fda20 1875 if (!strlen ($chapter_name))
c5f84f48 1876 throw new InvalidArgException ('$chapter_name', $chapter_name);
32832c0e
DO
1877 return usePreparedExecuteBlade
1878 (
1879 'UPDATE Chapter SET name=? WHERE id=? AND sticky="no"',
1880 array ($chapter_name, $chapter_no)
1881 );
e673ee24
DO
1882}
1883
1884function commitDeleteChapter ($chapter_no = 0)
1885{
c9066b1c 1886 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
e673ee24
DO
1887}
1888
4c330a14
DO
1889// This is a dictionary accessor. We perform link rendering, so the user sees
1890// nice <select> drop-downs.
7fa7047a 1891function readChapter ($chapter_id = 0, $style = '')
e673ee24 1892{
c9066b1c
DO
1893 $result = usePreparedSelectBlade
1894 (
7fa7047a 1895 "select dict_key, dict_value from Dictionary " .
c9066b1c
DO
1896 "where chapter_id = ?",
1897 array ($chapter_id)
1898 );
e673ee24
DO
1899 $chapter = array();
1900 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7fa7047a 1901 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
e673ee24 1902 $result->closeCursor();
4aa8609b
DO
1903 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1904 asort ($chapter);
e673ee24
DO
1905 return $chapter;
1906}
1907
7fa7047a
DO
1908// Return refcounters for all given keys of the given chapter.
1909function getChapterRefc ($chapter_id, $keylist)
1910{
afdb3cf5
DO
1911 $ret = array();
1912 foreach ($keylist as $key)
1913 $ret[$key] = 0;
7fa7047a
DO
1914 switch ($chapter_id)
1915 {
1916 case CHAP_OBJTYPE:
1917 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
1918 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
c9066b1c 1919 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
7fa7047a
DO
1920 break;
1921 case CHAP_PORTTYPE:
93a83f51 1922 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
7fa7047a 1923 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
93a83f51 1924 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
c9066b1c 1925 "from Dictionary where chapter_id = ?";
7fa7047a
DO
1926 break;
1927 default:
1928 // Find the list of all assigned values of dictionary-addressed attributes, each with
1929 // chapter/word keyed reference counters.
1930 $query = "select uint_value, count(object_id) as refcnt " .
1931 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1932 "inner join AttributeValue as av on a.id = av.attr_id " .
1933 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
c9066b1c 1934 "where a.type = 'dict' and am.chapter_id = ? group by uint_value";
7fa7047a
DO
1935 break;
1936 }
c9066b1c 1937 $result = usePreparedSelectBlade ($query, array ($chapter_id));
7fa7047a
DO
1938 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1939 $ret[$row['uint_value']] = $row['refcnt'];
1940 return $ret;
1941}
1942
e4e9e2a1
DO
1943// Return a list of all stickers with sticker map applied. Each sticker records will
1944// list all its ways on the map with refcnt set.
e673ee24
DO
1945function getAttrMap ()
1946{
c9066b1c
DO
1947 $result = usePreparedSelectBlade
1948 (
978dc510
DO
1949 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
1950 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
7fa7047a 1951 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
e4e9e2a1 1952 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
c9066b1c
DO
1953 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
1954 );
e673ee24
DO
1955 $ret = array();
1956 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1957 {
e4e9e2a1
DO
1958 if (!isset ($ret[$row['id']]))
1959 $ret[$row['id']] = array
1960 (
1961 'id' => $row['id'],
1962 'type' => $row['type'],
1963 'name' => $row['name'],
1964 'application' => array(),
1965 );
e673ee24
DO
1966 if ($row['objtype_id'] == '')
1967 continue;
e4e9e2a1
DO
1968 $application = array
1969 (
1970 'objtype_id' => $row['objtype_id'],
e4e9e2a1
DO
1971 'refcnt' => $row['refcnt'],
1972 );
1973 if ($row['type'] == 'dict')
e673ee24 1974 {
50393983 1975 $application['chapter_no'] = $row['chapter_id'];
e673ee24
DO
1976 $application['chapter_name'] = $row['chapter_name'];
1977 }
e4e9e2a1 1978 $ret[$row['id']]['application'][] = $application;
e673ee24 1979 }
e673ee24
DO
1980 return $ret;
1981}
1982
1983function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1984{
32832c0e 1985 return usePreparedExecuteBlade ('UPDATE Attribute SET name=? WHERE id=?', array ($attr_name, $attr_id));
e673ee24
DO
1986}
1987
1988function commitAddAttribute ($attr_name = '', $attr_type = '')
1989{
59a83bd8 1990 if (!strlen ($attr_name))
0cc24e9a 1991 throw new InvalidArgException ('$attr_name', $attr_name);
e673ee24
DO
1992 switch ($attr_type)
1993 {
1994 case 'uint':
1995 case 'float':
1996 case 'string':
1997 case 'dict':
1998 break;
1999 default:
0cc24e9a 2000 throw new InvalidArgException ('$attr_type', $attr_type, 'Attribute type not supported');
e673ee24 2001 }
c9066b1c 2002 return usePreparedInsertBlade
e673ee24
DO
2003 (
2004 'Attribute',
c9066b1c 2005 array ('name' => $attr_name, 'type' => $attr_type)
e673ee24
DO
2006 );
2007}
2008
2009function commitDeleteAttribute ($attr_id = 0)
2010{
c9066b1c 2011 return usePreparedDeleteBlade ('Attribute', array ('id' => $attr_id));
e673ee24
DO
2012}
2013
2014// FIXME: don't store garbage in chapter_no for non-dictionary types.
2015function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2016{
0cc24e9a
DY
2017 if ($attr_id <= 0)
2018 throw new InvalidArgException ('$attr_id', $attr_id);
2019 if ($objtype_id <= 0)
2020 throw new InvalidArgException ('$objtype_id', $objtype_id);
2021
c9066b1c 2022 return usePreparedInsertBlade
e673ee24
DO
2023 (
2024 'AttributeMap',
2025 array
2026 (
2027 'attr_id' => $attr_id,
2028 'objtype_id' => $objtype_id,
10bac82a 2029 'chapter_id' => $chapter_no
e673ee24
DO
2030 )
2031 );
2032}
2033
2034function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2035{
c9066b1c 2036 return usePreparedDeleteBlade ('AttributeMap', array ('attr_id' => $attr_id, 'objtype_id' => $objtype_id));
e673ee24
DO
2037}
2038
2039// This function returns all optional attributes for requested object
2040// as an array of records. NULL is returned on error and empty array
2041// is returned, if there are no attributes found.
7fa7047a 2042function getAttrValues ($object_id)
e673ee24 2043{
e673ee24 2044 $ret = array();
c9066b1c
DO
2045 $result = usePreparedSelectBlade
2046 (
10bac82a 2047 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
7fa7047a 2048 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
e673ee24 2049 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
10bac82a 2050 "inner join Attribute as A on AM.attr_id = A.id " .
e673ee24 2051 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
10bac82a
DY
2052 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2053 "left join Chapter as C on AM.chapter_id = C.id " .
c9066b1c
DO
2054 "where RO.id = ? order by A.name, A.type",
2055 array ($object_id)
2056 );
e673ee24
DO
2057 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2058 {
2059 $record = array();
2060 $record['id'] = $row['attr_id'];
2061 $record['name'] = $row['attr_name'];
2062 $record['type'] = $row['attr_type'];
2063 switch ($row['attr_type'])
2064 {
7fa7047a
DO
2065 case 'dict':
2066 $record['chapter_id'] = $row['chapter_id'];
2067 $record['chapter_name'] = $row['chapter_name'];
2068 $record['key'] = $row['uint_value'];
2069 // fall through
e673ee24
DO
2070 case 'uint':
2071 case 'float':
2072 case 'string':
24cbe8af 2073 $record['value'] = $row[$row['attr_type'] . '_value'];
7fa7047a 2074 $record['o_value'] = parseWikiLink ($record['value'], 'o');
24cbe8af
DO
2075 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2076 break;
e673ee24
DO
2077 default:
2078 $record['value'] = NULL;
2079 break;
2080 }
2081 $ret[$row['attr_id']] = $record;
2082 }
2083 $result->closeCursor();
2084 return $ret;
2085}
2086
2087function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2088{
c9066b1c 2089 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
e673ee24
DO
2090}
2091
e673ee24
DO
2092function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2093{
0cc24e9a
DY
2094 if ($object_id <= 0)
2095 throw new InvalidArgException ('$objtype_id', $objtype_id);
2096 if ($attr_id <= 0)
2097 throw new InvalidArgException ('$attr_id', $attr_id);
59a83bd8 2098 if (!strlen ($value))
e673ee24 2099 return commitResetAttrValue ($object_id, $attr_id);
c9066b1c 2100 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
e673ee24 2101 $row = $result->fetch (PDO::FETCH_NUM);
e673ee24 2102 $attr_type = $row[0];
c9066b1c 2103 unset ($result);
e673ee24
DO
2104 switch ($attr_type)
2105 {
2106 case 'uint':
2107 case 'float':
2108 case 'string':
2109 $column = $attr_type . '_value';
2110 break;
2111 case 'dict':
2112 $column = 'uint_value';
2113 break;
2114 default:
0cc24e9a 2115 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
e673ee24 2116 }
c9066b1c 2117 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
e673ee24 2118 // We know $value isn't empty here.
c9066b1c
DO
2119 usePreparedInsertBlade
2120 (
2121 'AttributeValue',
2122 array
2123 (
2124 $column => $value,
2125 'object_id' => $object_id,
2126 'attr_id' => $attr_id,
2127 )
2128 );
e673ee24
DO
2129 return TRUE;
2130}
2131
2132function commitUseupPort ($port_id = 0)
2133{
32832c0e 2134 return usePreparedExecuteBlade ('UPDATE Port SET reservation_comment=NULL WHERE id=?', array ($port_id));
e673ee24
DO
2135}
2136
3fb56626
DO
2137function convertPDOException ($e)
2138{
2139 if ($e->getCode() != 23000)
2140 return $e;
2141 switch ($e->errorInfo[1])
2142 {
2143 case 1062:
2144 $text = 'such record already exists';
2145 break;
2146 case 1451:
2147 case 1452:
2148 $text = 'foreign key violation';
2149 break;
2150 default:
2151 $text = 'unknown error code ' . $e->errorInfo[1];
2152 break;
2153 }
2154 return new Exception ($text, E_DB_CONSTRAINT);
2155}
2156
e673ee24
DO
2157// This is a swiss-knife blade to insert a record into a table.
2158// The first argument is table name.
2159// The second argument is an array of "name" => "value" pairs.
357eb2ea
DO
2160function usePreparedInsertBlade ($tablename, $columns)
2161{
2162 global $dbxlink;
2163 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2164 $query .= ') VALUES (' . implode (', ', array_fill (0, count ($columns), '?')) . ')';
2165 // Now the query should be as follows:
2166 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
5f054512
DO
2167 try
2168 {
3fb56626 2169 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2170 if (!$prepared->execute (array_values ($columns)))
2171 return FALSE;
2172 return $prepared->rowCount() == 1;
2173 }
2174 catch (PDOException $e)
2175 {
3fb56626 2176 throw convertPDOException ($e);
5f054512 2177 }
357eb2ea
DO
2178}
2179
9589714d
DO
2180// This swiss-knife blade deletes any number of records from the specified table
2181// using the specified key names and values.
bbae3611 2182function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
8198f2c6
DO
2183{
2184 global $dbxlink;
bbae3611
DO
2185 $conj = '';
2186 $query = "DELETE FROM ${tablename} WHERE ";
2187 foreach ($columns as $colname => $colvalue)
2188 {
de47b574 2189 $query .= " ${conj} ${colname}=?";
bbae3611
DO
2190 $conj = $conjunction;
2191 }
5f054512
DO
2192 try
2193 {
3fb56626 2194 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2195 if (!$prepared->execute (array_values ($columns)))
2196 return FALSE;
2197 return $prepared->rowCount(); // FALSE !== 0
2198 }
2199 catch (PDOException $e)
2200 {
3fb56626 2201 throw convertPDOException ($e);
5f054512 2202 }
8198f2c6
DO
2203}
2204
d0dadd80
DO
2205function usePreparedSelectBlade ($query, $args = array())
2206{
2207 global $dbxlink;
2208 $prepared = $dbxlink->prepare ($query);
2209 if (!$prepared->execute ($args))
2210 return FALSE;
2211 return $prepared;
2212}
2213
39eadd27
DO
2214// Prepare and execute the statement with parameters, then return number of
2215// rows affected (or FALSE in case of an error).
2216function usePreparedExecuteBlade ($query, $args = array())
2217{
2218 global $dbxlink;
3fb56626
DO
2219 try
2220 {
2221 if (!$prepared = $dbxlink->prepare ($query))
2222 return FALSE;
2223 if (!$prepared->execute ($args))
2224 return FALSE;
2225 return $prepared->rowCount();
2226 }
2227 catch (PDOException $e)
2228 {
2229 throw convertPDOException ($e);
2230 }
39eadd27
DO
2231}
2232
9c0b0016
DO
2233function loadConfigCache ()
2234{
c9066b1c 2235 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
3540d15c 2236 $cache = array();
c9066b1c 2237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3540d15c 2238 $cache[$row['varname']] = $row;
3540d15c
DY
2239 return $cache;
2240}
2241
2242function loadUserConfigCache ($username = NULL)
2243{
2244 if (!strlen ($username))
2245 throw new InvalidArgException ('$username', $username);
c9066b1c 2246 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
9c0b0016
DO
2247 $cache = array();
2248 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2249 $cache[$row['varname']] = $row;
9c0b0016
DO
2250 return $cache;
2251}
2252
3540d15c
DY
2253function deleteUserConfigVar ($username = NULL, $varname = NULL)
2254{
c9066b1c 2255 usePreparedDeleteBlade ('UserConfig', array ('varname' => $varname, 'user' => $username));
3540d15c
DY
2256}
2257
3540d15c
DY
2258function storeUserConfigVar ($username = NULL, $varname = NULL, $varvalue = NULL)
2259{
3540d15c
DY
2260 if (!strlen ($username))
2261 throw new InvalidArgException ('$username', $username);
2262 if (!strlen ($varname))
2263 throw new InvalidArgException ('$varname', $varname);
2264 if ($varvalue === NULL)
2265 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2266 return usePreparedExecuteBlade
2267 (
2268 'REPLACE UserConfig SET varvalue=?, varname=?, user=?',
2269 array ($varvalue, $varname, $username)
e5925cee 2270 );
3540d15c
DY
2271}
2272
9c0b0016
DO
2273// setConfigVar() is expected to perform all necessary filtering
2274function storeConfigVar ($varname = NULL, $varvalue = NULL)
2275{
c5f84f48
DY
2276 if ($varvalue === NULL)
2277 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2278 return usePreparedExecuteBlade
2279 (
2280 'UPDATE Config SET varvalue=? WHERE varname=?',
2281 array ($varvalue, $varname)
2282 );
9c0b0016
DO
2283}
2284
fbbb74fb
DO
2285// Database version detector. Should behave corretly on any
2286// working dataset a user might have.
2287function getDatabaseVersion ()
2288{
a5c589d2 2289 $result = usePreparedSelectBlade ('SELECT varvalue FROM Config WHERE varname = "DB_VERSION" and vartype = "string"');
fbbb74fb
DO
2290 if ($result == NULL)
2291 {
a5c589d2 2292 global $dbxlink;
fbbb74fb
DO
2293 $errorInfo = $dbxlink->errorInfo();
2294 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2295 return '0.14.4';
4d2e93f2 2296 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2297 }
2298 $rows = $result->fetchAll (PDO::FETCH_NUM);
59a83bd8 2299 if (count ($rows) != 1 || !strlen ($rows[0][0]))
fbbb74fb
DO
2300 {
2301 $result->closeCursor();
4d2e93f2 2302 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2303 }
2304 $ret = $rows[0][0];
2305 $result->closeCursor();
2306 return $ret;
2307}
2308
da04825a
DO
2309// Return an array of virtual services. For each of them list real server pools
2310// with their load balancers and other stats.
62a1dcb5
DO
2311function getSLBSummary ()
2312{
c9066b1c
DO
2313 $result = usePreparedSelectBlade
2314 (
2315 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
6fec9f39 2316 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2317 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2318 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2319 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
c9066b1c
DO
2320 'group by vs.id, object_id order by vs.vip, object_id'
2321 );
c3bdc503
DO
2322 $ret = array();
2323 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2324 {
4cadac8f 2325 $vsid = $row['vsid'];
da04825a 2326 $object_id = $row['object_id'];
4cadac8f
DO
2327 if (!isset ($ret[$vsid]))
2328 {
2329 $ret[$vsid] = array();
13bffb29 2330 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2331 $ret[$vsid][$cname] = $row[$cname];
da04825a 2332 $ret[$vsid]['lblist'] = array();
4cadac8f 2333 }
6fec9f39
DO
2334 // There's only one assigned RS pool possible for each LB-VS combination.
2335 $ret[$vsid]['lblist'][$row['object_id']] = array
2336 (
2337 'id' => $row['rspool_id'],
2338 'size' => $row['rscount'],
2339 'name' => $row['pool_name']
2340 );
c3bdc503
DO
2341 }
2342 return $ret;
62a1dcb5
DO
2343}
2344
7e7a8387 2345function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2346{
a5c589d2 2347 return usePreparedExecuteBlade
ca461127 2348 (
a5c589d2 2349 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
ca461127
DO
2350 array
2351 (
a5c589d2
DO
2352 $rsip,
2353 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2354 $pool_id,
2355 $inservice == 'yes' ? 'yes' : 'no',
2356 !strlen ($rsconfig) ? NULL : $rsconfig
3241551e
DO
2357 )
2358 );
2359}
2360
c63a8d6e 2361function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21 2362{
c5f84f48
DY
2363 if (!strlen ($vip))
2364 throw new InvalidArgException ('$vip', $vip);
2365 if ($vport <= 0)
2366 throw new InvalidArgException ('$vport', $vport);
2367 if (!strlen ($proto))
2368 throw new InvalidArgException ('$proto', $proto);
a5c589d2 2369 if (FALSE === usePreparedExecuteBlade
d6517a21 2370 (
a5c589d2 2371 'INSERT INTO IPv4VS (vip, vport, proto, name, vsconfig, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?, ?)',
d6517a21
DO
2372 array
2373 (
a5c589d2
DO
2374 $vip,
2375 $vport,
2376 $proto,
2377 !strlen ($name) ? NULL : $name,
2378 !strlen ($vsconfig) ? NULL : $vsconfig,
2379 !strlen ($rsconfig) ? NULL : $rsconfig,
d6517a21 2380 )
c63a8d6e
DO
2381 ))
2382 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2383 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2384}
2385
c1ca768c 2386function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2387{
c9066b1c 2388 return usePreparedInsertBlade
3241551e 2389 (
706ce117 2390 'IPv4LB',
3241551e
DO
2391 array
2392 (
2393 'object_id' => $object_id,
2394 'rspool_id' => $pool_id,
c1ca768c 2395 'vs_id' => $vs_id,
c9066b1c
DO
2396 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2397 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
3241551e 2398 )
ca461127
DO
2399 );
2400}
2401
fb1c4a54
DO
2402function commitDeleteRS ($id = 0)
2403{
c9066b1c 2404 return usePreparedDeleteBlade ('IPv4RS', array ('id' => $id));
fb1c4a54
DO
2405}
2406
d6517a21
DO
2407function commitDeleteVS ($id = 0)
2408{
6657739e 2409 releaseFiles ('ipv4vs', $id);
0da3bf00 2410 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2411}
2412
c1ca768c 2413function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e 2414{
c9066b1c 2415 return usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id, 'rspool_id' => $pool_id, 'vs_id' => $vs_id));
3241551e
DO
2416}
2417
fb1c4a54
DO
2418function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2419{
fb1c4a54 2420 if (long2ip (ip2long ($rsip)) !== $rsip)
c5f84f48 2421 throw new InvalidArgException ('$rsip', $rsip);
a5c589d2
DO
2422 return usePreparedExecuteBlade
2423 (
2424 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2425 array
2426 (
2427 $rsip,
2428 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2429 !strlen ($rsconfig) ? NULL : $rsconfig,
2430 $rsid,
2431 )
2432 );
fb1c4a54
DO
2433}
2434
c1ca768c 2435function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2436{
a5c589d2
DO
2437 return usePreparedExecuteBlade
2438 (
2439 'UPDATE IPv4LB SET vsconfig=?, rsconfig=? WHERE object_id=? AND rspool_id=? AND vs_id=?',
2440 array
2441 (
2442 !strlen ($vsconfig) ? NULL : $vsconfig,
2443 !strlen ($rsconfig) ? NULL : $rsconfig,
2444 $object_id,
2445 $pool_id,
2446 $vs_id,
2447 )
2448 );
3241551e
DO
2449}
2450
d6517a21
DO
2451function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2452{
c5f84f48
DY
2453 if (!strlen ($vip))
2454 throw new InvalidArgException ('$vip', $vip);
2455 if ($vport <= 0)
2456 throw new InvalidArgException ('$vport', $vport);
2457 if (!strlen ($proto))
2458 throw new InvalidArgException ('$proto', $proto);
a5c589d2
DO
2459 return usePreparedExecuteBlade
2460 (
2461 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2462 array
2463 (
2464 $vip,
2465 $vport,
2466 $proto,
2467 !strlen ($name) ? NULL : $name,
2468 !strlen ($vsconfig) ? NULL : $vsconfig,
2469 !strlen ($rsconfig) ? NULL : $rsconfig,
2470 $vsid,
2471 )
2472 );
d6517a21
DO
2473}
2474
5a1680d2
DO
2475function loadThumbCache ($rack_id = 0)
2476{
5a1680d2 2477 $ret = NULL;
c9066b1c 2478 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
5a1680d2
DO
2479 $row = $result->fetch (PDO::FETCH_ASSOC);
2480 if ($row)
2481 $ret = base64_decode ($row['thumb_data']);
5a1680d2
DO
2482 return $ret;
2483}
2484
2485function saveThumbCache ($rack_id = 0, $cache = NULL)
2486{
178fda20 2487 if ($cache == NULL)
c5f84f48 2488 throw new InvalidArgException ('$cache', $cache);
a5c589d2 2489 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=? WHERE id=?', array (base64_encode ($cache), $rack_id));
5a1680d2 2490}
9a81d416 2491
c7fe33be
DO
2492function resetThumbCache ($rack_id = 0)
2493{
a5c589d2 2494 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=NULL WHERE id=?', array ($rack_id));
c7fe33be
DO
2495}
2496
748805bf 2497// Return the list of attached RS pools for the given object. As long as we have
706ce117 2498// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2499// by vs_id, because there will be only one RS pool listed for each VS of the
2500// current object.
78e7b769
DO
2501function getRSPoolsForObject ($object_id = 0)
2502{
c9066b1c
DO
2503 $result = usePreparedSelectBlade
2504 (
2505 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2506 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2507 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2508 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2509 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
c9066b1c
DO
2510 'where lb.object_id = ? ' .
2511 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2512 array ($object_id)
2513 );
748805bf 2514 $ret = array ();
78e7b769 2515 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2516 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2517 $ret[$row['vs_id']][$cname] = $row[$cname];
748805bf 2518 return $ret;
78e7b769
DO
2519}
2520
c63a8d6e 2521function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2522{
59a83bd8 2523 if (!strlen ($name))
c5f84f48 2524 throw new InvalidArgException ('$name', $name);
c9066b1c 2525 if (!usePreparedInsertBlade
5ad76f01 2526 (
706ce117 2527 'IPv4RSPool',
5ad76f01
DO
2528 array
2529 (
c9066b1c
DO
2530 'name' => (!strlen ($name) ? NULL : $name),
2531 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2532 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
5ad76f01 2533 )
c63a8d6e
DO
2534 ))
2535 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2536 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2537}
2538
2539function commitDeleteRSPool ($pool_id = 0)
2540{
6657739e 2541 releaseFiles ('ipv4rspool', $pool_id);
c9066b1c 2542 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2543}
2544
2545function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2546{
a5c589d2
DO
2547 return usePreparedExecuteBlade
2548 (
2549 'UPDATE IPv4RSPool SET name=?, vsconfig=?, rsconfig=? WHERE id=?',
2550 array
2551 (
2552 !strlen ($name) ? NULL : $name,
2553 !strlen ($vsconfig) ? NULL : $vsconfig,
2554 !strlen ($rsconfig) ? NULL : $rsconfig,
2555 $pool_id,
2556 )
2557 );
5ad76f01
DO
2558}
2559
8253d9f0
DO
2560function getRSList ()
2561{
c9066b1c
DO
2562 $result = usePreparedSelectBlade
2563 (
2564 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2565 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2566 );
4b0932b6 2567 $ret = array ();
8253d9f0 2568 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2569 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6 2570 $ret[$row['id']][$cname] = $row[$cname];
4b0932b6
DO
2571 return $ret;
2572}
2573
2574// Return the list of all currently configured load balancers with their pool count.
2575function getLBList ()
2576{
c9066b1c
DO
2577 $result = usePreparedSelectBlade
2578 (
2579 "select object_id, count(rspool_id) as poolcount " .
2580 "from IPv4LB group by object_id order by object_id"
2581 );
4b0932b6
DO
2582 $ret = array ();
2583 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2584 $ret[$row['object_id']] = $row['poolcount'];
4b0932b6 2585 return $ret;
8253d9f0
DO
2586}
2587
178fda20 2588// For the given object return: its vsconfig/rsconfig; the list of RS pools
9e677cbd
DO
2589// attached (each with vsconfig/rsconfig in turn), each with the list of
2590// virtual services terminating the pool. Each pool also lists all real
2591// servers with rsconfig.
2987fc1f 2592function getSLBConfig ($object_id)
9e677cbd 2593{
9e677cbd 2594 $ret = array();
e34dac4f
DO
2595 $result = usePreparedSelectBlade
2596 (
2597 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
d91f08f3
DO
2598 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2599 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2600 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2601 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2602 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2603 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2604 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
e34dac4f
DO
2605 "where lb.object_id = ? and rs.inservice = 'yes' " .
2606 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2607 array ($object_id)
2608 );
9e677cbd
DO
2609 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2610 {
d91f08f3
DO
2611 $vs_id = $row['vs_id'];
2612 if (!isset ($ret[$vs_id]))
2613 {
2614 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name') as $c)
2615 $ret[$vs_id][$c] = $row[$c];
2616 $ret[$vs_id]['rslist'] = array();
2617 }
2618 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2619 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd 2620 }
9e677cbd
DO
2621 return $ret;
2622}
1f7d18fa
DO
2623
2624function commitSetInService ($rs_id = 0, $inservice = '')
2625{
c5f84f48
DY
2626 if (!strlen ($inservice))
2627 throw new InvalidArgException ('$inservice', $inservice);
a5c589d2 2628 return usePreparedExecuteBlade ('UPDATE IPv4RS SET inservice=? WHERE id=?', array ($inservice, $rs_id));
1f7d18fa
DO
2629}
2630
ad0e4754
DO
2631function executeAutoPorts ($object_id = 0, $type_id = 0)
2632{
c5f84f48
DY
2633 if ($object_id == 0)
2634 throw new InvalidArgException ('$object_id', $object_id);
2635 if ($type_id == 0)
2636 throw new InvalidArgException ('$type_id', $type_id);
f3f0161f 2637 $ret = TRUE;
118e4c38 2638 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2639 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2640 return $ret;
ad0e4754
DO
2641}
2642
6e49bd1f 2643// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2644// generated/deducted later at higher levels.
aab37bc0 2645// Result is a chain: randomly indexed taginfo list.
f9bc186f 2646function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2647{
a6e8d544 2648 $ret = array();
e34dac4f
DO
2649 $result = usePreparedSelectBlade
2650 (
2651 "select tt.id, tag from " .
edf0993c 2652 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
e34dac4f
DO
2653 "where entity_realm = ? and entity_id = ? " .
2654 "order by tt.tag",
2655 array ($entity_realm, $entity_id)
2656 );
5967b83d 2657 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2658 $ret[$row['id']] = $row;
aab37bc0 2659 return getExplicitTagsOnly ($ret);
5967b83d
DO
2660}
2661
351c0966 2662// Return a tag chain with all DB tags on it.
5967b83d
DO
2663function getTagList ()
2664{
20c901a7 2665 $ret = array();
e34dac4f
DO
2666 $result = usePreparedSelectBlade
2667 (
2668 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2669 "from TagTree left join TagStorage on id = tag_id " .
e34dac4f
DO
2670 "group by id, entity_realm order by tag"
2671 );
2672 // Collation index. The resulting rows are ordered according to default collation,
fb7a4967 2673 // which is utf8_general_ci for UTF-8.
e34dac4f 2674 $ci = 0;
5967b83d 2675 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2676 {
7cc02fc1 2677 if (!isset ($ret[$row['id']]))
20c901a7 2678 $ret[$row['id']] = array
5b7bd02e
DO
2679 (
2680 'id' => $row['id'],
2681 'tag' => $row['tag'],
fb7a4967 2682 'ci' => $ci++,
5b7bd02e 2683 'parent_id' => $row['parent_id'],
9e51318b 2684 'refcnt' => array ('total' => 0)
5b7bd02e
DO
2685 );
2686 if ($row['realm'])
9e51318b 2687 {
20c901a7 2688 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
9e51318b
DO
2689 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2690 }
5b7bd02e 2691 }
20c901a7 2692 return $ret;
5967b83d
DO
2693}
2694
fe7044ad
DO
2695function commitCreateTag ($tagname = '', $parent_id = 0)
2696{
2697 if ($tagname == '' or $parent_id === 0)
2698 return "Invalid args to " . __FUNCTION__;
e34dac4f 2699 $result = usePreparedInsertBlade
fe7044ad
DO
2700 (
2701 'TagTree',
2702 array
2703 (
e34dac4f 2704 'tag' => $tagname,
fe7044ad
DO
2705 'parent_id' => $parent_id
2706 )
2707 );
2708 if ($result)
2709 return '';
9f572fb5
DO
2710 global $dbxlink;
2711 if ($dbxlink->errorCode() == 23000) // integrity constraint violation
2712 {
2713 $ei = $dbxlink->errorInfo();
2714 if ($ei[1] == 1062)
2715 return 'tag name must be unique';
2716 if ($ei[1] == 1452)
2717 return "parent tag id ${parent_id} does not exist";
2718 }
2719 return "SQL query failed in " . __FUNCTION__;
fe7044ad
DO
2720}
2721
2722function commitDestroyTag ($tagid = 0)
2723{
e34dac4f 2724 if (usePreparedDeleteBlade ('TagTree', array ('id' => $tagid)))
fe7044ad 2725 return '';
e34dac4f 2726 return 'usePreparedDeleteBlade() failed in ' . __FUNCTION__;
fe7044ad 2727}
f9bc186f 2728
49fb1027 2729function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2730{
a5c589d2
DO
2731 return usePreparedExecuteBlade
2732 (
2733 'UPDATE TagTree SET tag=?, parent_id=? WHERE id=?',
2734 array
2735 (
2736 $tag_name,
2737 $parent_id == 0 ? NULL : $parent_id,
2738 $tag_id,
2739 )
2740 );
f9bc186f
DO
2741}
2742
01b6b4d6
DO
2743// Drop the whole chain stored.
2744function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af 2745{
e34dac4f 2746 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
aedf18af
DO
2747}
2748
01b6b4d6 2749// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
29c3a4d8
DO
2750// FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2751// but not now.
01b6b4d6
DO
2752function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2753{
e34dac4f 2754 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
01b6b4d6
DO
2755}
2756
351c0966 2757// Push a record into TagStorage unconditionally.
3355ca56 2758function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2759{
e34dac4f 2760 if (!in_array ($realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
3355ca56 2761 return FALSE;
e34dac4f 2762 return usePreparedInsertBlade
eb6ea26f
DO
2763 (
2764 'TagStorage',
2765 array
2766 (
e34dac4f 2767 'entity_realm' => $realm,
120e9ddd 2768 'entity_id' => $entity_id,
eb6ea26f
DO
2769 'tag_id' => $tag_id,
2770 )
2771 );
2772}
2773
351c0966 2774// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
2775// on the implicit list already). Then remove any other records, which
2776// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
2777// that both the tag base is still minimal and all requested tags appear on
2778// the resulting tag chain.
abef7149
DO
2779// Return TRUE, if any changes were committed.
2780function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2781{
2782 // Put the current explicit sub-chain into a buffer and merge all tags from
2783 // the extra chain, which aren't there yet.
2784 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2785 foreach ($extrachain as $extratag)
2786 if (!tagOnChain ($extratag, $newchain))
2787 $newchain[] = $extratag;
2788 // Then minimize the working buffer and check if it differs from the original
2789 // chain we started with. If it is so, save the work and signal the upper layer.
2790 $newchain = getExplicitTagsOnly ($newchain);
2791 if (tagChainCmp ($oldchain, $newchain))
2792 {
01b6b4d6 2793 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
2794 foreach ($newchain as $taginfo)
2795 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2796 return TRUE;
2797 }
2798 return FALSE;
351c0966
DO
2799}
2800
2801// Presume, that the target record has no tags attached.
2802function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2803{
2804 if (!count ($tagidlist))
c63a8d6e
DO
2805 return '';
2806 if (!$last_insert_id)
2807 $last_insert_id = lastInsertID();
2808 $errcount = 0;
abef7149 2809 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 2810 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
2811 $errcount++;
2812 if (!$errcount)
2813 return '';
2814 else
2815 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2816}
2817
42023f03
DO
2818function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2819{
2820 // $range is in x.x.x.x/x format, split into ip/mask vars
2821 $rangeArray = explode('/', $range);
2822 if (count ($rangeArray) != 2)
2823 return "Invalid IPv4 prefix '${range}'";
2824 $ip = $rangeArray[0];
2825 $mask = $rangeArray[1];
2826
59a83bd8 2827 if (!strlen ($ip) or !strlen ($mask))
42023f03
DO
2828 return "Invalid IPv4 prefix '${range}'";
2829 $ipL = ip2long($ip);
2830 $maskL = ip2long($mask);
2831 if ($ipL == -1 || $ipL === FALSE)
2832 return 'Bad IPv4 address';
2833 if ($mask < 32 && $mask > 0)
2834 $maskL = $mask;
2835 else
2836 {
2837 $maskB = decbin($maskL);
2838 if (strlen($maskB)!=32)
2839 return 'Invalid netmask';
2840 $ones=0;
2841 $zeroes=FALSE;
2842 foreach( str_split ($maskB) as $digit)
2843 {
2844 if ($digit == '0')
2845 $zeroes = TRUE;
2846 if ($digit == '1')
2847 {
2848 $ones++;
2849 if ($zeroes == TRUE)
2850 return 'Invalid netmask';
2851 }
2852 }
2853 $maskL = $ones;
2854 }
2855 $binmask = binMaskFromDec($maskL);
2856 $ipL = $ipL & $binmask;
357eb2ea 2857 $result = usePreparedInsertBlade
42023f03 2858 (
706ce117 2859 'IPv4Network',
42023f03
DO
2860 array
2861 (
2862 'ip' => sprintf ('%u', $ipL),
357eb2ea
DO
2863 'mask' => $maskL,
2864 'name' => $name
42023f03
DO
2865 )
2866 );
e782fca4
DO
2867 if ($result != TRUE)
2868 return "Could not add ${range} (already exists?).";
42023f03
DO
2869
2870 if ($is_bcast and $maskL < 31)
2871 {
2872 $network_addr = long2ip ($ipL);
2873 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2874 updateAddress ($network_addr, 'network', 'yes');
2875 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2876 }
351c0966 2877 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
2878}
2879
706ce117 2880// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
2881function destroyIPv4Prefix ($id = 0)
2882{
6657739e 2883 releaseFiles ('ipv4net', $id);
e34dac4f 2884 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
42023f03 2885 return __FUNCTION__ . ': SQL query #1 failed';
0da3bf00 2886 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
2887 return __FUNCTION__ . ': SQL query #2 failed';
2888 return '';
2889}
2890
ebae41b3
DO
2891function loadScript ($name)
2892{
e34dac4f 2893 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
ebae41b3 2894 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
2895 if ($row !== FALSE)
2896 return $row[0];
2897 else
2898 return NULL;
ebae41b3
DO
2899}
2900
178fda20 2901function saveScript ($name = '', $text)
ebae41b3 2902{
59a83bd8 2903 if (!strlen ($name))
c5f84f48 2904 throw new InvalidArgException ('$name', $name);
4a6a28f1 2905 // delete regardless of existence
e34dac4f
DO
2906 usePreparedDeleteBlade ('Script', array ('script_name' => $name));
2907 return usePreparedInsertBlade
ebae41b3
DO
2908 (
2909 'Script',
2910 array
2911 (
e34dac4f
DO
2912 'script_name' => $name,
2913 'script_text' => $text,
ebae41b3
DO
2914 )
2915 );
2916}
2917
d983f70a
DO
2918function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2919{
2920 if (NULL === getIPv4AddressNetworkId ($localip))
2921 return "$localip: Non existant ip";
0929db7f 2922 if (NULL === getIPv4AddressNetworkId ($remoteip))
d983f70a
DO
2923 return "$remoteip: Non existant ip";
2924 if ( ($localport <= 0) or ($localport >= 65536) )
2925 return "$localport: invaild port";
2926 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
2927 return "$remoteport: invaild port";
2928
a5c589d2 2929 $result = usePreparedExecuteBlade
d983f70a 2930 (
a5c589d2
DO
2931 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
2932 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
d983f70a
DO
2933 array
2934 (
a5c589d2
DO
2935 $object_id,
2936 $localip,
2937 $remoteip,
2938 $localport,
2939 $remoteport,
2940 $proto,
2941 $description,
d983f70a
DO
2942 )
2943 );
a5c589d2 2944 return $result !== FALSE ? '' : (__FUNCTION__ . '(): failed to insert the rule');
d983f70a
DO
2945}
2946
2947function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
2948{
a5c589d2
DO
2949 return usePreparedExecuteBlade
2950 (
2951 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
2952 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
2953 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2954 );
d983f70a
DO
2955}
2956
2957function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2958{
a5c589d2
DO
2959 return usePreparedExecuteBlade
2960 (
2961 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
2962 'AND localport=? AND remoteport=? AND proto=?',
2963 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2964 );
d983f70a
DO
2965}
2966
2967function getNATv4ForObject ($object_id)
2968{
2969 $ret = array();
2970 $ret['out'] = array();
2971 $ret['in'] = array();
e34dac4f
DO
2972 $result = usePreparedSelectBlade
2973 (
d983f70a
DO
2974 "select ".
2975 "proto, ".
2976 "INET_NTOA(localip) as localip, ".
2977 "localport, ".
2978 "INET_NTOA(remoteip) as remoteip, ".
2979 "remoteport, ".
2980 "ipa1.name as local_addr_name, " .
2981 "ipa2.name as remote_addr_name, " .
2982 "description ".
706ce117
DO
2983 "from IPv4NAT ".
2984 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
2985 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
e34dac4f
DO
2986 "where object_id=? ".
2987 "order by localip, localport, proto, remoteip, remoteport",
2988 array ($object_id)
2989 );
d983f70a
DO
2990 $count=0;
2991 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2992 {
2993 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
2994 $ret['out'][$count][$cname] = $row[$cname];
2995 $count++;
2996 }
d983f70a
DO
2997 unset ($result);
2998
e34dac4f
DO
2999 $result = usePreparedSelectBlade
3000 (
d983f70a
DO
3001 "select ".
3002 "proto, ".
3003 "INET_NTOA(localip) as localip, ".
3004 "localport, ".
3005 "INET_NTOA(remoteip) as remoteip, ".
3006 "remoteport, ".
706ce117 3007 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
3008 "RackObject.name as object_name, ".
3009 "description ".
706ce117 3010 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
e34dac4f
DO
3011 "where IPv4Allocation.object_id=? ".
3012 "order by remoteip, remoteport, proto, localip, localport",
3013 array ($object_id)
3014 );
d983f70a
DO
3015 $count=0;
3016 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3017 {
3018 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3019 $ret['in'][$count][$cname] = $row[$cname];
3020 $count++;
3021 }
d983f70a
DO
3022 return $ret;
3023}
3024
178fda20 3025// Return a list of files, which are not linked to the specified record. This list
121496b6 3026// will be used by printSelect().
e1ae3fb4
AD
3027function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3028{
e34dac4f
DO
3029 $query = usePreparedSelectBlade
3030 (
121496b6 3031 'SELECT id, name FROM File ' .
e1ae3fb4 3032 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
e34dac4f
DO
3033 'ORDER BY name, id',
3034 array ($entity_type, $entity_id)
3035 );
e1ae3fb4 3036 $ret=array();
e1ae3fb4 3037 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3038 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3039 return $ret;
3040}
3041
6df2025d
DO
3042// FIXME: return a standard cell list, so upper layer can iterate over
3043// it conveniently.
e1ae3fb4
AD
3044function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3045{
e34dac4f
DO
3046 $query = usePreparedSelectBlade
3047 (
e1ae3fb4
AD
3048 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3049 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
e34dac4f
DO
3050 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3051 array ($entity_type, $entity_id)
3052 );
e1ae3fb4
AD
3053 $ret = array();
3054 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3055 $ret[$row['file_id']] = array (
b3567368 3056 'id' => $row['file_id'],
e1ae3fb4
AD
3057 'link_id' => $row['link_id'],
3058 'name' => $row['name'],
3059 'type' => $row['type'],
3060 'size' => $row['size'],
3061 'ctime' => $row['ctime'],
3062 'mtime' => $row['mtime'],
3063 'atime' => $row['atime'],
3064 'comment' => $row['comment'],
3065 );
3066 return $ret;
3067}
3068
3069function getFile ($file_id = 0)
3070{
e1ae3fb4
AD
3071 global $dbxlink;
3072 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3073 $query->bindParam(1, $file_id);
3074 $query->execute();
3075 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3076 {
0cc24e9a 3077 showWarning ('Query succeeded, but returned no data', __FUNCTION__);
e1ae3fb4
AD
3078 $ret = NULL;
3079 }
3080 else
3081 {
3082 $ret = array();
3083 $ret['id'] = $row['id'];
3084 $ret['name'] = $row['name'];
3085 $ret['type'] = $row['type'];
3086 $ret['size'] = $row['size'];
3087 $ret['ctime'] = $row['ctime'];
3088 $ret['mtime'] = $row['mtime'];
3089 $ret['atime'] = $row['atime'];
3090 $ret['contents'] = $row['contents'];
3091 $ret['comment'] = $row['comment'];
bed9cd76 3092 $query->closeCursor();
e1ae3fb4 3093
deb3da1b 3094 // Someone accessed this file, update atime
e1ae3fb4
AD
3095 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3096 $q_atime->bindParam(1, date('YmdHis'));
3097 $q_atime->bindParam(2, $file_id);
3098 $q_atime->execute();
3099 }
e1ae3fb4
AD
3100 return $ret;
3101}
3102
e1ae3fb4
AD
3103function getFileLinks ($file_id = 0)
3104{
e1ae3fb4 3105 global $dbxlink;
8bc5d1e4 3106 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ? ORDER BY entity_type, entity_id');
e1ae3fb4
AD
3107 $query->bindParam(1, $file_id);
3108 $query->execute();
da3302ab 3109 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3110 $ret = array();
da3302ab 3111 foreach ($rows as $row)
e1ae3fb4
AD
3112 {
3113 // get info of the parent
3114 switch ($row['entity_type'])
3115 {
3116 case 'ipv4net':
3117 $page = 'ipv4net';
3118 $id_name = 'id';
d724d290 3119 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3120 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3121 break;
3122 case 'ipv4rspool':
3854af78 3123 $page = 'ipv4rspool';
e1ae3fb4 3124 $id_name = 'pool_id';
a6e91ac2 3125 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3126 $name = $parent['name'];
3127 break;
3128 case 'ipv4vs':
3129 $page = 'ipv4vs';
3130 $id_name = 'vs_id';
7c38462f 3131 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3132 $name = $parent['name'];
3133 break;
3134 case 'object':
3135 $page = 'object';
3136 $id_name = 'object_id';
6297d584 3137 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
7ddbcf59 3138 $name = $parent['dname'];
e1ae3fb4
AD
3139 break;
3140 case 'rack':
3141 $page = 'rack';
3142 $id_name = 'rack_id';
61a1d996 3143 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3144 $name = $parent['name'];
3145 break;
3146 case 'user':
3147 $page = 'user';
3148 $id_name = 'user_id';
0b2c74cb
DO
3149 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3150 $name = $parent['user_name'];
e1ae3fb4
AD
3151 break;
3152 }
3153
17d95c32 3154 // name needs to have some value for hrefs to work
59a83bd8 3155 if (!strlen ($name))
17d95c32
AD
3156 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3157
e1ae3fb4
AD
3158 $ret[$row['id']] = array(
3159 'page' => $page,
3160 'id_name' => $id_name,
3161 'entity_type' => $row['entity_type'],
3162 'entity_id' => $row['entity_id'],
3163 'name' => $name
3164 );
3165 }
3166 return $ret;
3167}
3168
0b97b8f0 3169function getFileStats ()
e1ae3fb4 3170{
e34dac4f 3171 $result = usePreparedSelectBlade ('SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type');
e1ae3fb4 3172 $ret = array();
e1ae3fb4
AD
3173 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3174 if ($row['count'] > 0)
0b97b8f0
DO
3175 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3176 unset ($result);
e1ae3fb4
AD
3177
3178 // Find number of files without any linkage
e34dac4f
DO
3179 $result = usePreparedSelectBlade
3180 (
e1ae3fb4
AD
3181 'SELECT COUNT(*) ' .
3182 'FROM File ' .
27b2ae0d 3183 'WHERE id NOT IN (SELECT file_id FROM FileLink)'
e34dac4f 3184 );
0b97b8f0
DO
3185 $ret["Unattached files"] = $result->fetchColumn ();
3186 unset ($result);
e1ae3fb4
AD
3187
3188 // Find total number of files
e34dac4f 3189 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM File');
0b97b8f0 3190 $ret["Total files"] = $result->fetchColumn ();
e1ae3fb4 3191
e1ae3fb4
AD
3192 return $ret;
3193}
3194
3195function commitAddFile ($name, $type, $size, $contents, $comment)
3196{
3197 $now = date('YmdHis');
3198
3199 global $dbxlink;
3200 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3201 $query->bindParam(1, $name);
3202 $query->bindParam(2, $type);
3203 $query->bindParam(3, $size);
3204 $query->bindParam(4, $now);
3205 $query->bindParam(5, $now);
3206 $query->bindParam(6, $now);
3207 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3208 $query->bindParam(8, $comment);
3209
3210 $result = $query->execute();
3211
3212
3213 if ($result)
3214 return '';
590e1281 3215 elseif ($query->errorCode() == 23000)
13edfa1c 3216 return "commitAddFile: File named '${name}' already exists";
e1ae3fb4
AD
3217 else
3218 return 'commitAddFile: SQL query failed';
3219}
3220
4a2c6c6b 3221function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4
AD
3222{
3223 global $dbxlink;
3224 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3225 $query->bindParam(1, $file_id);
4a2c6c6b
AD
3226 $query->bindParam(2, $entity_type);
3227 $query->bindParam(3, $entity_id);
e1ae3fb4
AD
3228
3229 $result = $query->execute();
3230
3231 if ($result)
3232 return '';
3233 else
3234 return 'commitLinkFile: SQL query failed';
3235}
3236
f8874cdb 3237function commitReplaceFile ($file_id = 0, $contents)
fd1fb420 3238{
fd1fb420 3239 global $dbxlink;
f8874cdb
DO
3240 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3241 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3242 $query->bindParam(2, $file_id);
fd1fb420
AD
3243
3244 $result = $query->execute();
fd1fb420
AD
3245 return '';
3246}
3247
9db67d95 3248function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
e1ae3fb4 3249{
c5f84f48
DY
3250 if (!strlen ($new_name))
3251 throw new InvalidArgException ('$new_name', $new_name);
3252 if (!strlen ($new_type))
3253 throw new InvalidArgException ('$new_type', $new_type);
e1ae3fb4 3254 global $dbxlink;
9db67d95 3255 $query = $dbxlink->prepare('UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?');
6ee41bd4 3256 $query->bindParam(1, $new_name);
9db67d95
DO
3257 $query->bindParam(2, $new_type);
3258 $query->bindParam(3, $new_comment);
3259 $query->bindParam(4, $file_id);
e1ae3fb4
AD
3260
3261 $result = $query->execute();
3262 if (!$result)
6ee41bd4 3263 return 'SQL query failed in ' . __FUNCTION__;
e1ae3fb4
AD
3264 return '';
3265}
3266
3267function commitUnlinkFile ($link_id)
3268{
e34dac4f 3269 if (usePreparedDeleteBlade ('FileLink', array ('id' => $link_id)) === FALSE)
9589714d 3270 return __FUNCTION__ . '(): query failed';
e1ae3fb4
AD
3271 return '';
3272}
3273
3274function commitDeleteFile ($file_id)
3275{
29c3a4d8 3276 destroyTagsForEntity ('file', $file_id);
e34dac4f 3277 if (usePreparedDeleteBlade ('File', array ('id' => $file_id)) === FALSE)
9589714d 3278 return __FUNCTION__ . '(): query failed';
e1ae3fb4
AD
3279 return '';
3280}
3281
4034ab9e
DO
3282function getChapterList ()
3283{
3284 $ret = array();
e34dac4f
DO
3285 $result = usePreparedSelectBlade
3286 (
3287 'SELECT id, sticky, name, count(chapter_id) as wordc ' .
3288 'FROM Chapter LEFT JOIN Dictionary ON Chapter.id = chapter_id ' .
3289 'GROUP BY id ORDER BY name'
3290 );
4034ab9e 3291 while ($row = $result->fetch (PDO::FETCH_ASSOC))
c4d0dc30 3292 $ret[$row['id']] = $row;
4034ab9e
DO
3293 return $ret;
3294}
3295
2d1e6b63 3296// Return file id by file name.
72d2a7ee
DO
3297function findFileByName ($filename)
3298{
2d1e6b63
AD
3299 global $dbxlink;
3300 $query = $dbxlink->prepare('SELECT id FROM File WHERE name = ?');
3301 $query->bindParam(1, $filename);
3302 $query->execute();
3303 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
72d2a7ee 3304 return $row['id'];
2d1e6b63
AD
3305
3306 return NULL;
72d2a7ee
DO
3307}
3308
9133d2c5
DO
3309function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3310{
3311 global $dbxlink;
3312 $dbxlink->beginTransaction();
e34dac4f
DO
3313 $result = usePreparedSelectBlade
3314 (
3315 'SELECT TIMESTAMPDIFF(SECOND, first_success, now()) AS success_age, ' .
3316 'TIMESTAMPDIFF(SECOND, last_retry, now()) AS retry_age, displayed_name, memberof ' .
3317 'FROM LDAPCache WHERE presented_username = ? AND successful_hash = ? ' .
3318 'HAVING success_age < ? FOR UPDATE',
3319 array ($form_username, $password_hash, $expiry)
3320 );
9133d2c5
DO
3321 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3322 {
3323 $row['memberof'] = unserialize (base64_decode ($row['memberof']));
3324 return $row;
3325 }
3326 return NULL;
3327}
3328
3329function releaseLDAPCache ()
3330{
3331 global $dbxlink;
3332 $dbxlink->commit();
3333}
3334
3335// This actually changes only last_retry.
3336function touchLDAPCacheRecord ($form_username)
3337{
a5c589d2 3338 return usePreparedExecuteBlade ('UPDATE LDAPCache SET last_retry=NOW() WHERE presented_username=?', array ($form_username));
9133d2c5
DO
3339}
3340
3341function replaceLDAPCacheRecord ($form_username, $password_hash, $dname, $memberof)
3342{
3343 deleteLDAPCacheRecord ($form_username);
e34dac4f 3344 usePreparedInsertBlade ('LDAPCache',
9133d2c5
DO
3345 array
3346 (
e34dac4f
DO
3347 'presented_username' => $form_username,
3348 'successful_hash' => $password_hash,
3349 'displayed_name' => $dname,
3350 'memberof' => base64_encode (serialize ($memberof)),
9133d2c5
DO
3351 )
3352 );
3353}
3354
3355function deleteLDAPCacheRecord ($form_username)
3356{
e34dac4f 3357 return usePreparedDeleteBlade ('LDAPCache', array ('presented_username' => $form_username));
9133d2c5
DO
3358}
3359
f3371850
DO
3360// Age all records older, than cache_expiry seconds, and all records made in future.
3361// Calling this function w/o argument purges the whole LDAP cache.
3362function discardLDAPCache ($maxage = 0)
ef44d4a3 3363{
a5c589d2 3364 return usePreparedExecuteBlade ('DELETE from LDAPCache WHERE TIMESTAMPDIFF(SECOND, first_success, NOW()) >= ? or NOW() < first_success', array ($maxage));
ef44d4a3
DO
3365}
3366
b82cce3f
DO
3367function getUserIDByUsername ($username)
3368{
e34dac4f 3369 $result = usePreparedSelectBlade ('SELECT user_id FROM UserAccount WHeRE user_name = ?', array ($username));
b82cce3f
DO
3370 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3371 return $row['user_id'];
3372 return NULL;
3373}
3374
029a14bc
DO
3375// Return TRUE, if the given address is assigned to a port of any object
3376// except the current object. Using this function as a constraint makes
3377// it possible to reuse L2 addresses within one object, yet keeping them
3378// universally unique on the other hand.
3379function alreadyUsedL2Address ($address, $my_object_id)
3380{
e34dac4f
DO
3381 $result = usePreparedSelectBlade
3382 (
3383 'SELECT COUNT(*) FROM Port WHERE BINARY l2address = ? AND object_id != ?',
3384 array ($address, $my_object_id)
3385 );
029a14bc
DO
3386 $row = $result->fetch (PDO::FETCH_NUM);
3387 return $row[0] != 0;
3388}
3389
2dfa1b73 3390function getPortInterfaceCompat()
3153a326 3391{
e34dac4f
DO
3392 $result = usePreparedSelectBlade
3393 (
3394 'SELECT iif_id, iif_name, oif_id, dict_value AS oif_name ' .
3153a326
DO
3395 'FROM PortInterfaceCompat INNER JOIN PortInnerInterface ON id = iif_id ' .
3396 'INNER JOIN Dictionary ON dict_key = oif_id ' .
e34dac4f
DO
3397 'ORDER BY iif_name, oif_name'
3398 );
2dfa1b73 3399 return $result->fetchAll (PDO::FETCH_ASSOC);
3153a326
DO
3400}
3401
3402// Return a set of options for a plain SELECT. These options include the current
3403// OIF of the given port and all OIFs of its permanent IIF.
3404function getExistingPortTypeOptions ($port_id)
3405{
e34dac4f
DO
3406 $result = usePreparedSelectBlade
3407 (
3408 'SELECT oif_id, dict_value AS oif_name ' .
3153a326 3409 'FROM PortInterfaceCompat INNER JOIN Dictionary ON oif_id = dict_key ' .
e34dac4f
DO
3410 'WHERE iif_id = (SELECT iif_id FROM Port WHERE id = ?) ' .
3411 'ORDER BY oif_name',
3412 array ($port_id)
3413 );
3153a326
DO
3414 $ret = array();
3415 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3416 $ret[$row['oif_id']] = $row['oif_name'];
3417 return $ret;
3418}
3419
2dfa1b73
DO
3420function getPortIIFOptions()
3421{
3422 $ret = array();
e34dac4f 3423 $result = usePreparedSelectBlade ('SELECT id, iif_name FROM PortInnerInterface ORDER BY iif_name');
2dfa1b73
DO
3424 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3425 $ret[$row['id']] = $row['iif_name'];
3426 return $ret;
3427}
3428
3429function commitSupplementPIC ($iif_id, $oif_id)
3430{
e34dac4f 3431 return usePreparedInsertBlade
2dfa1b73
DO
3432 (
3433 'PortInterfaceCompat',
3434 array ('iif_id' => $iif_id, 'oif_id' => $oif_id)
3435 );
3436}
3437
3438function commitReducePIC ($iif_id, $oif_id)
3439{
e34dac4f 3440 return usePreparedDeleteBlade ('PortInterfaceCompat', array ('iif_id' => $iif_id, 'oif_id' => $oif_id));
2dfa1b73
DO
3441}
3442
27ec21b2
DO
3443function getPortIIFStats ($args)
3444{
e34dac4f
DO
3445 $result = usePreparedSelectBlade
3446 (
3447 'SELECT dict_value AS title, COUNT(id) AS max, ' .
27ec21b2
DO
3448 'COUNT(reservation_comment) + ' .
3449 'SUM((SELECT COUNT(*) FROM Link WHERE id IN (porta, portb))) AS current ' .
3450 'FROM Port INNER JOIN Dictionary ON type = dict_key ' .
e34dac4f
DO
3451 'WHERE iif_id = ? GROUP BY type',
3452 array (current ($args))
3453 );
27ec21b2
DO
3454 return $result->fetchAll (PDO::FETCH_ASSOC);
3455}
3456
cd3775e9
DO
3457function getPortInfo ($port_id)
3458{
e34dac4f
DO
3459 $result = usePreparedSelectBlade
3460 (
3461 "SELECT object_id, name, iif_id, type AS oif_id, l2address, ".
cd3775e9 3462 "(SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, " .
b3247480 3463 "(SELECT COUNT(*) FROM Link WHERE id IN (porta, portb)) AS linked, " .
cd3775e9 3464 "(SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name " .
e34dac4f
DO
3465 "FROM Port WHERE id = ?",
3466 array ($port_id)
3467 );
cd3775e9
DO
3468 return $result->fetch (PDO::FETCH_ASSOC);
3469}
3470
87cca0c2 3471function getVLANDomainStats ()
8198f2c6 3472{
e34dac4f
DO
3473 $result = usePreparedSelectBlade
3474 (
3475 'SELECT id, description, ' .
8198f2c6 3476 '(SELECT COUNT(vlan_id) FROM VLANDescription WHERE domain_id = id) AS vlanc, ' .
b5ac48d0 3477 '(SELECT COUNT(ipv4net_id) FROM VLANIPv4 WHERE domain_id = id) AS ipv4netc, ' .
6affe3b9
DO
3478 '(SELECT COUNT(object_id) FROM VLANSwitch WHERE domain_id = id) AS switchc, ' .
3479 '(SELECT COUNT(port_name) FROM VLANSwitch AS VS INNER JOIN PortVLANMode AS PVM ON VS.object_id = PVM.object_id WHERE domain_id = id) AS portc ' .
e34dac4f
DO
3480 'FROM VLANDomain ORDER BY description'
3481 );
8198f2c6
DO
3482 $ret = array();
3483 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3484 $ret[$row['id']] = $row;
3485 return $ret;
3486}
3487
e829e76b
DO
3488function getVLANDomainOptions()
3489{
e34dac4f 3490 $result = usePreparedSelectBlade ('SELECT id, description FROM VLANDomain ORDER BY description');
e829e76b
DO
3491 $ret = array();
3492 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3493 $ret[$row['id']] = $row['description'];