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