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