r4044 list Catalyst 2960S series
[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
DO
1517 foreach ($byname as $row)
1518 $ret[] = 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)
1534 $ret[] = spotEntity ('ipv6net', $row['id']);
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))
1552 $ret[] = $row;
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))
1570 $ret[] = $row;
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
DO
1585 foreach ($byname as $row)
1586 $ret[] = 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
DO
1601 foreach ($byname as $row)
1602 $ret[] = 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 );
1624 // Filter out dupes.
1625 foreach ($byUsername as $res1)
1626 foreach (array_keys ($byRealname) as $key2)
1627 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1628 {
1629 unset ($byRealname[$key2]);
1630 continue 2;
1631 }
573214e0
DO
1632 $ret = array_merge ($byUsername, $byRealname);
1633 // Set realm, so it's renderable.
1634 foreach (array_keys ($ret) as $key)
1635 $ret[$key]['realm'] = 'user';
1636 return $ret;
6a88e734
DO
1637}
1638
e1ae3fb4
AD
1639function getFileSearchResult ($terms)
1640{
e531b4d6 1641 $byName = getSearchResultByField
e1ae3fb4
AD
1642 (
1643 'File',
6df2025d 1644 array ('id'),
e1ae3fb4
AD
1645 'name',
1646 $terms,
1647 'name'
1648 );
1649 $byComment = getSearchResultByField
1650 (
1651 'File',
6df2025d 1652 array ('id'),
e1ae3fb4
AD
1653 'comment',
1654 $terms,
1655 'name'
1656 );
1657 // Filter out dupes.
e531b4d6 1658 foreach ($byName as $res1)
e1ae3fb4
AD
1659 foreach (array_keys ($byComment) as $key2)
1660 if ($res1['id'] == $byComment[$key2]['id'])
1661 {
1662 unset ($byComment[$key2]);
1663 continue 2;
1664 }
6df2025d 1665 $ret = array();
e531b4d6 1666 foreach (array_merge ($byName, $byComment) as $row)
6df2025d
DO
1667 $ret[] = spotEntity ('file', $row['id']);
1668 return $ret;
e1ae3fb4
AD
1669}
1670
e531b4d6
DO
1671function getRackSearchResult ($terms)
1672{
1673 $byName = getSearchResultByField
1674 (
1675 'Rack',
1676 array ('id'),
1677 'name',
1678 $terms,
1679 'name'
1680 );
1681 $byComment = getSearchResultByField
1682 (
1683 'Rack',
1684 array ('id'),
1685 'comment',
1686 $terms,
1687 'name'
1688 );
1689 // Filter out dupes.
1690 foreach ($byName as $res1)
1691 foreach (array_keys ($byComment) as $key2)
1692 if ($res1['id'] == $byComment[$key2]['id'])
1693 {
1694 unset ($byComment[$key2]);
1695 continue 2;
1696 }
1697 $ret = array();
1698 foreach (array_merge ($byName, $byComment) as $row)
1699 $ret[] = spotEntity ('rack', $row['id']);
1700 return $ret;
1701}
1702
1f54e1ba
DO
1703function getVLANSearchResult ($terms)
1704{
1705 $ret = array();
1706 $matches = array();
9f178aa9 1707 if (preg_match ('/^vlan\s*(\d+)$/i', $terms, $matches))
1f54e1ba
DO
1708 {
1709 $byID = getSearchResultByField
1710 (
1711 'VLANDescription',
1712 array ('domain_id', 'vlan_id'),
1713 'vlan_id',
1714 $matches[1],
1715 'domain_id',
1716 1
1717 );
1718 foreach ($byID as $row)
1719 $ret[] = $row['domain_id'] . '-' . $row['vlan_id'];
1720 }
9f178aa9 1721 else
1f54e1ba 1722 {
9f178aa9
AA
1723 $byDescr = getSearchResultByField
1724 (
1725 'VLANDescription',
1726 array ('domain_id', 'vlan_id'),
1727 'vlan_descr',
1728 $terms
1729 );
1730 foreach ($byDescr as $row)
1731 {
1732 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1733 if (!in_array ($vlan_ck, $ret))
1734 $ret[] = $vlan_ck;
1735 }
1f54e1ba
DO
1736 }
1737 return $ret;
1738}
1739
dfd80d8e 1740function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
6a88e734
DO
1741{
1742 $pfx = '';
1743 $query = 'select ';
a685e6d7 1744 $qparams = array();
6a88e734
DO
1745 foreach ($rcolumns as $col)
1746 {
1747 $query .= $pfx . $col;
1748 $pfx = ', ';
1749 }
1750 $pfx = '';
1751 $query .= " from ${tname} where ";
1752 foreach (explode (' ', $terms) as $term)
1753 {
dfd80d8e
DO
1754 switch ($exactness)
1755 {
1756 case 2: // does this work as expected?
a685e6d7
DO
1757 $query .= $pfx . "binary ${scolumn} = ?";
1758 $qparams[] = $term;
dfd80d8e
DO
1759 break;
1760 case 1:
a685e6d7
DO
1761 $query .= $pfx . "${scolumn} = ?";
1762 $qparams[] = $term;
dfd80d8e
DO
1763 break;
1764 default:
a685e6d7
DO
1765 $query .= $pfx . "${scolumn} like ?";
1766 $qparams[] = "%${term}%";
dfd80d8e
DO
1767 break;
1768 }
6a88e734
DO
1769 $pfx = ' or ';
1770 }
1771 if ($ocolumn != '')
1772 $query .= " order by ${ocolumn}";
a685e6d7 1773 $result = usePreparedSelectBlade ($query, $qparams);
6a88e734
DO
1774 $ret = array();
1775 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1776 $ret[] = $row;
1777 return $ret;
1778}
1779
b1f60545 1780function getObjectSearchResults ($what)
323edbbf
DO
1781{
1782 $ret = array();
1b4a0a6a
DO
1783 global $searchfunc;
1784 foreach ($searchfunc['object'] as $method => $func)
1785 foreach ($func ($what) as $objRecord)
1786 {
1787 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1788 $ret[$objRecord['id']][$method] = $objRecord[$method];
1789 }
b1f60545
DO
1790 return $ret;
1791}
1792
1793function getObjectAttrsSearchResults ($what)
1794{
1795 $ret = array();
1796 foreach (array ('name', 'label', 'asset_no', 'barcode') as $column)
1797 {
1798 $tmp = getSearchResultByField
1799 (
1800 'RackObject',
1801 array ('id'),
1802 $column,
1803 $what,
1804 $column
1805 );
1806 foreach ($tmp as $row)
1807 {
1808 $ret[$row['id']]['id'] = $row['id'];
1809 $ret[$row['id']]['by_attr'][] = $column;
1810 }
1811 }
323edbbf
DO
1812 return $ret;
1813}
1814
1815// Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1816// which matched. A partilar object_id could be returned more, than once, if it has
1817// multiple matching stickers. Search is only performed on "string" attributes.
1818function getStickerSearchResults ($what, $exactness = 0)
1819{
1820 $stickers = getSearchResultByField
1821 (
1822 'AttributeValue',
1823 array ('object_id', 'attr_id'),
1824 'string_value',
1825 $what,
1826 'object_id',
1827 $exactness
1828 );
1829 $map = getAttrMap();
1830 $ret = array();
1831 foreach ($stickers as $sticker)
1832 if ($map[$sticker['attr_id']]['type'] == 'string')
1833 {
1834 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
1835 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
1836 }
1837 return $ret;
1838}
1839
f1b5f68d 1840// search in port "reservation comment", "label" and "L2 address" columns
d516d719 1841function getPortSearchResults ($what)
323edbbf 1842{
f1b5f68d 1843 $ret = array();
323edbbf
DO
1844 $ports = getSearchResultByField
1845 (
1846 'Port',
1b4a0a6a 1847 array ('object_id', 'id', 'reservation_comment'),
323edbbf
DO
1848 'reservation_comment',
1849 $what,
1850 'object_id',
1851 0
1852 );
323edbbf
DO
1853 foreach ($ports as $port)
1854 {
1855 $ret[$port['object_id']]['id'] = $port['object_id'];
1b4a0a6a 1856 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
d516d719 1857 }
f1b5f68d
DO
1858 $ports = getSearchResultByField
1859 (
1860 'Port',
1861 array ('object_id', 'id', 'label'),
1862 'label',
1863 $what,
1864 'object_id',
1865 0
1866 );
1867 foreach ($ports as $port)
1868 {
1869 $ret[$port['object_id']]['id'] = $port['object_id'];
1870 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1871 }
d516d719
DO
1872 if (NULL === ($db_l2address = l2addressForDatabase ($what)))
1873 return $ret;
1874 $ports = getSearchResultByField
1875 (
1876 'Port',
1b4a0a6a 1877 array ('object_id', 'id', 'l2address'),
d516d719
DO
1878 'l2address',
1879 $db_l2address,
1880 'object_id',
1881 2
1882 );
1883 foreach ($ports as $port)
1884 {
1885 $ret[$port['object_id']]['id'] = $port['object_id'];
1b4a0a6a 1886 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
323edbbf
DO
1887 }
1888 return $ret;
1889}
1890
5fd2a004
DO
1891// search in IPv4 allocations
1892function getObjectIfacesSearchResults ($what)
1893{
1894 $ret = array();
21ee3351 1895 $ifaces4 = getSearchResultByField
5fd2a004
DO
1896 (
1897 'IPv4Allocation',
1898 array ('object_id', 'name'),
1899 'name',
1900 $what,
1901 'object_id'
1902 );
21ee3351
AA
1903 $ifaces6 = getSearchResultByField
1904 (
1905 'IPv6Allocation',
1906 array ('object_id', 'name'),
1907 'name',
1908 $what,
1909 'object_id'
1910 );
1911 foreach (array_merge ($ifaces4, $ifaces6) as $row)
5fd2a004
DO
1912 {
1913 $ret[$row['object_id']]['id'] = $row['object_id'];
1914 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1915 }
1916 return $ret;
1917}
1918
1919function getObjectNATSearchResults ($what)
1920{
1921 $ret = array();
1922 $ifaces = getSearchResultByField
1923 (
1924 'IPv4NAT',
1925 array ('object_id', 'description'),
1926 'description',
1927 $what,
1928 'object_id'
1929 );
1930 foreach ($ifaces as $row)
1931 {
1932 $ret[$row['object_id']]['id'] = $row['object_id'];
1933 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1934 }
1935 return $ret;
1936}
1937
1938// This function returns either port ID or NULL for specified arguments.
e9d357e1 1939function getPortIDs ($object_id, $port_name)
e673ee24 1940{
e9d357e1
DO
1941 $ret = array();
1942 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
1943 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1944 $ret[] = $row['id'];
1945 return $ret;
1946}
1947
1948// Search in "FQDN" attribute only, and return object ID, when there is exactly
1949// one result found (and NULL in any other case).
1950function searchByMgmtHostname ($string)
1951{
1952 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
e673ee24
DO
1953 $rows = $result->fetchAll (PDO::FETCH_NUM);
1954 if (count ($rows) != 1)
1955 return NULL;
e9d357e1 1956 return $rows[0][0];
e673ee24
DO
1957}
1958
1959function commitCreateUserAccount ($username, $realname, $password)
1960{
c9066b1c 1961 return usePreparedInsertBlade
e673ee24
DO
1962 (
1963 'UserAccount',
1964 array
1965 (
654e4636
DO
1966 'user_name' => $username,
1967 'user_realname' => $realname,
1968 'user_password_hash' => $password,
e673ee24
DO
1969 )
1970 );
1971}
1972
1973function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1974{
32832c0e
DO
1975 return usePreparedExecuteBlade
1976 (
1977 'UPDATE UserAccount SET user_name=?, user_realname=?, user_password_hash=? ' .
1978 'WHERE user_id=?',
1979 array ($new_username, $new_realname, $new_password, $id)
1980 );
e673ee24
DO
1981}
1982
e673ee24 1983// This function returns an array of all port type pairs from PortCompat table.
27ec21b2 1984function getPortOIFCompat ()
e673ee24 1985{
e673ee24
DO
1986 $query =
1987 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1988 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
27ec21b2
DO
1989 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1990 'ORDER BY type1name, type2name';
c9066b1c 1991 $result = usePreparedSelectBlade ($query);
27ec21b2 1992 return $result->fetchAll (PDO::FETCH_ASSOC);
e673ee24
DO
1993}
1994
a310dd80
DO
1995// Add a pair to the PortCompat table.
1996function commitSupplementPOIFC ($type1, $type2)
e673ee24 1997{
0cc24e9a
DY
1998 if ($type1 <= 0)
1999 throw new InvalidArgException ('type1', $type1);
2000 if ($type2 <= 0)
2001 throw new InvalidArgException ('type2', $type2);
c9066b1c 2002 return usePreparedInsertBlade
a310dd80
DO
2003 (
2004 'PortCompat',
2005 array ('type1' => $type1, 'type2' => $type2)
2006 );
e673ee24
DO
2007}
2008
a310dd80
DO
2009// Remove a pair from the PortCompat table.
2010function commitReducePOIFC ($type1, $type2)
e673ee24 2011{
c9066b1c 2012 return usePreparedDeleteBlade ('PortCompat', array ('type1' => $type1, 'type2' => $type2));
e673ee24
DO
2013}
2014
da95280e
DO
2015function getDictStats ()
2016{
63811a09 2017 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
c9066b1c
DO
2018 $result = usePreparedSelectBlade
2019 (
10bac82a 2020 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
c9066b1c
DO
2021 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
2022 );
da95280e 2023 $tc = $tw = $uc = $uw = 0;
89fa639f 2024 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
2025 {
2026 $tc++;
2027 $tw += $row['wc'];;
2028 if (in_array ($row['chapter_no'], $stock_chapters))
2029 continue;
2030 $uc++;
2031 $uw += $row['wc'];;
2032 }
89fa639f 2033 unset ($result);
c9066b1c
DO
2034 $result = usePreparedSelectBlade
2035 (
2036 "select count(object_id) as attrc from RackObject as ro left join " .
2037 "AttributeValue as av on ro.id = av.object_id group by ro.id"
2038 );
08b4cb24 2039 $to = $ta = $so = 0;
89fa639f 2040 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
2041 {
2042 $to++;
2043 if ($row['attrc'] != 0)
2044 {
2045 $so++;
2046 $ta += $row['attrc'];
2047 }
2048 }
d2eb8399 2049 unset ($result);
da95280e
DO
2050 $ret = array();
2051 $ret['Total chapters in dictionary'] = $tc;
2052 $ret['Total words in dictionary'] = $tw;
2053 $ret['User chapters'] = $uc;
2054 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
2055 $ret['Total objects'] = $to;
2056 $ret['Objects with stickers'] = $so;
2057 $ret['Total stickers attached'] = $ta;
da95280e
DO
2058 return $ret;
2059}
2060
6807f0be 2061function getIPv4Stats ()
9ec5fdf1 2062{
9ec5fdf1
DO
2063 $ret = array();
2064 $subject = array();
706ce117
DO
2065 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
2066 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
2067 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
2068 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
2069 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
2070 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
2071 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
2072 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
9ec5fdf1
DO
2073
2074 foreach ($subject as $item)
2075 {
c9066b1c 2076 $result = usePreparedSelectBlade ($item['q']);
9ec5fdf1
DO
2077 $row = $result->fetch (PDO::FETCH_NUM);
2078 $ret[$item['txt']] = $row[0];
9ec5fdf1
DO
2079 unset ($result);
2080 }
2081 return $ret;
2082}
2083
21ee3351
AA
2084function getIPv6Stats ()
2085{
2086 $ret = array();
2087 $subject = array();
2088 $subject[] = array ('q' => 'select count(id) from IPv6Network', 'txt' => 'Networks');
2089 $subject[] = array ('q' => 'select count(ip) from IPv6Address', 'txt' => 'Addresses commented/reserved');
2090 $subject[] = array ('q' => 'select count(ip) from IPv6Allocation', 'txt' => 'Addresses allocated');
2091
2092 foreach ($subject as $item)
2093 {
2094 $result = usePreparedSelectBlade ($item['q']);
2095 $row = $result->fetch (PDO::FETCH_NUM);
2096 $ret[$item['txt']] = $row[0];
2097 unset ($result);
2098 }
2099 return $ret;
2100}
2101
6807f0be 2102function getRackspaceStats ()
9ec5fdf1 2103{
9ec5fdf1
DO
2104 $ret = array();
2105 $subject = array();
10bac82a 2106 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
9ec5fdf1
DO
2107 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
2108 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
2109 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
2110
2111 foreach ($subject as $item)
2112 {
c9066b1c 2113 $result = usePreparedSelectBlade ($item['q']);
9ec5fdf1 2114 $row = $result->fetch (PDO::FETCH_NUM);
59a83bd8 2115 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
2116 unset ($result);
2117 }
2118 return $ret;
2119}
2120
6807f0be
DO
2121/*
2122
2123The following allows figuring out records in TagStorage, which refer to non-existing entities:
2124
120e9ddd
DO
2125mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
2126mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
2127mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
2128mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
2129mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
2130mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
2131mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
6807f0be
DO
2132
2133Accordingly, these are the records, which refer to non-existent tags:
2134
2135mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
2136
2137*/
2138
826c3dbd 2139// chapter_no is a must, see at @commitReduceDictionary() why
e673ee24
DO
2140function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
2141{
32832c0e
DO
2142 return usePreparedExecuteBlade
2143 (
2144 'UPDATE Dictionary SET dict_value=? WHERE chapter_id=? AND dict_key=?',
2145 array ($dict_value, $chapter_no, $dict_key)
2146 );
e673ee24
DO
2147}
2148
2149function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
2150{
c5f84f48
DY
2151 if ($chapter_no <= 0)
2152 throw new InvalidArgException ('$chapter_no', $chapter_no);
2153 if (!strlen ($dict_value))
2154 throw new InvalidArgException ('$dict_value', $dict_value);
c9066b1c 2155 return usePreparedInsertBlade
e673ee24
DO
2156 (
2157 'Dictionary',
c9066b1c 2158 array ('chapter_id' => $chapter_no, 'dict_value' => $dict_value)
e673ee24
DO
2159 );
2160}
2161
178fda20
DO
2162// Technically dict_key is enough to delete, but including chapter_id into
2163// WHERE clause makes sure, that the action actually happends for the same
2164// chapter, which authorization was granted for.
e673ee24
DO
2165function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
2166{
c9066b1c 2167 return usePreparedDeleteBlade ('Dictionary', array ('chapter_id' => $chapter_no, 'dict_key' => $dict_key));
e673ee24
DO
2168}
2169
2170function commitAddChapter ($chapter_name = '')
2171{
59a83bd8 2172 if (!strlen ($chapter_name))
c5f84f48 2173 throw new InvalidArgException ('$chapter_name', $chapter_name);
c9066b1c 2174 return usePreparedInsertBlade
e673ee24
DO
2175 (
2176 'Chapter',
c9066b1c 2177 array ('name' => $chapter_name)
e673ee24
DO
2178 );
2179}
2180
2181function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
2182{
178fda20 2183 if (!strlen ($chapter_name))
c5f84f48 2184 throw new InvalidArgException ('$chapter_name', $chapter_name);
32832c0e
DO
2185 return usePreparedExecuteBlade
2186 (
2187 'UPDATE Chapter SET name=? WHERE id=? AND sticky="no"',
2188 array ($chapter_name, $chapter_no)
2189 );
e673ee24
DO
2190}
2191
2192function commitDeleteChapter ($chapter_no = 0)
2193{
c9066b1c 2194 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
e673ee24
DO
2195}
2196
4c330a14
DO
2197// This is a dictionary accessor. We perform link rendering, so the user sees
2198// nice <select> drop-downs.
7fa7047a 2199function readChapter ($chapter_id = 0, $style = '')
e673ee24 2200{
c9066b1c
DO
2201 $result = usePreparedSelectBlade
2202 (
7fa7047a 2203 "select dict_key, dict_value from Dictionary " .
c9066b1c
DO
2204 "where chapter_id = ?",
2205 array ($chapter_id)
2206 );
e673ee24
DO
2207 $chapter = array();
2208 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7fa7047a 2209 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
4aa8609b
DO
2210 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2211 asort ($chapter);
e673ee24
DO
2212 return $chapter;
2213}
2214
7fa7047a
DO
2215// Return refcounters for all given keys of the given chapter.
2216function getChapterRefc ($chapter_id, $keylist)
2217{
afdb3cf5
DO
2218 $ret = array();
2219 foreach ($keylist as $key)
2220 $ret[$key] = 0;
7fa7047a
DO
2221 switch ($chapter_id)
2222 {
2223 case CHAP_OBJTYPE:
2224 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
2225 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
c9066b1c 2226 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
7fa7047a
DO
2227 break;
2228 case CHAP_PORTTYPE:
93a83f51 2229 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
7fa7047a 2230 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
93a83f51 2231 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
c9066b1c 2232 "from Dictionary where chapter_id = ?";
7fa7047a
DO
2233 break;
2234 default:
2235 // Find the list of all assigned values of dictionary-addressed attributes, each with
2236 // chapter/word keyed reference counters.
2237 $query = "select uint_value, count(object_id) as refcnt " .
2238 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
2239 "inner join AttributeValue as av on a.id = av.attr_id " .
2240 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
c9066b1c 2241 "where a.type = 'dict' and am.chapter_id = ? group by uint_value";
7fa7047a
DO
2242 break;
2243 }
c9066b1c 2244 $result = usePreparedSelectBlade ($query, array ($chapter_id));
7fa7047a
DO
2245 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2246 $ret[$row['uint_value']] = $row['refcnt'];
2247 return $ret;
2248}
2249
e4e9e2a1
DO
2250// Return a list of all stickers with sticker map applied. Each sticker records will
2251// list all its ways on the map with refcnt set.
e673ee24
DO
2252function getAttrMap ()
2253{
c9066b1c
DO
2254 $result = usePreparedSelectBlade
2255 (
978dc510
DO
2256 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
2257 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
7fa7047a 2258 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
e4e9e2a1 2259 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
c9066b1c
DO
2260 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
2261 );
e673ee24
DO
2262 $ret = array();
2263 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2264 {
e4e9e2a1
DO
2265 if (!isset ($ret[$row['id']]))
2266 $ret[$row['id']] = array
2267 (
2268 'id' => $row['id'],
2269 'type' => $row['type'],
2270 'name' => $row['name'],
2271 'application' => array(),
2272 );
e673ee24
DO
2273 if ($row['objtype_id'] == '')
2274 continue;
e4e9e2a1
DO
2275 $application = array
2276 (
2277 'objtype_id' => $row['objtype_id'],
e4e9e2a1
DO
2278 'refcnt' => $row['refcnt'],
2279 );
2280 if ($row['type'] == 'dict')
e673ee24 2281 {
50393983 2282 $application['chapter_no'] = $row['chapter_id'];
e673ee24
DO
2283 $application['chapter_name'] = $row['chapter_name'];
2284 }
e4e9e2a1 2285 $ret[$row['id']]['application'][] = $application;
e673ee24 2286 }
e673ee24
DO
2287 return $ret;
2288}
2289
2290function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2291{
32832c0e 2292 return usePreparedExecuteBlade ('UPDATE Attribute SET name=? WHERE id=?', array ($attr_name, $attr_id));
e673ee24
DO
2293}
2294
2295function commitAddAttribute ($attr_name = '', $attr_type = '')
2296{
59a83bd8 2297 if (!strlen ($attr_name))
0cc24e9a 2298 throw new InvalidArgException ('$attr_name', $attr_name);
e673ee24
DO
2299 switch ($attr_type)
2300 {
2301 case 'uint':
2302 case 'float':
2303 case 'string':
2304 case 'dict':
2305 break;
2306 default:
0cc24e9a 2307 throw new InvalidArgException ('$attr_type', $attr_type, 'Attribute type not supported');
e673ee24 2308 }
c9066b1c 2309 return usePreparedInsertBlade
e673ee24
DO
2310 (
2311 'Attribute',
c9066b1c 2312 array ('name' => $attr_name, 'type' => $attr_type)
e673ee24
DO
2313 );
2314}
2315
2316function commitDeleteAttribute ($attr_id = 0)
2317{
c9066b1c 2318 return usePreparedDeleteBlade ('Attribute', array ('id' => $attr_id));
e673ee24
DO
2319}
2320
2321// FIXME: don't store garbage in chapter_no for non-dictionary types.
2322function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2323{
0cc24e9a
DY
2324 if ($attr_id <= 0)
2325 throw new InvalidArgException ('$attr_id', $attr_id);
2326 if ($objtype_id <= 0)
2327 throw new InvalidArgException ('$objtype_id', $objtype_id);
2328
c9066b1c 2329 return usePreparedInsertBlade
e673ee24
DO
2330 (
2331 'AttributeMap',
2332 array
2333 (
2334 'attr_id' => $attr_id,
2335 'objtype_id' => $objtype_id,
10bac82a 2336 'chapter_id' => $chapter_no
e673ee24
DO
2337 )
2338 );
2339}
2340
2341function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2342{
c9066b1c 2343 return usePreparedDeleteBlade ('AttributeMap', array ('attr_id' => $attr_id, 'objtype_id' => $objtype_id));
e673ee24
DO
2344}
2345
1f54e1ba
DO
2346function cacheAllObjectsAttributes()
2347{
2348 global $object_attribute_cache;
2349 $object_attribute_cache = fetchAttrsForObjects(NULL);
2350}
2351
2352// Fetches a list of attributes for each object in $object_set array.
2353// If $object_set is not set, returns attributes for all objects in DB
2354// Returns an array with object_id keys
2355function fetchAttrsForObjects($object_set)
e673ee24 2356{
e673ee24 2357 $ret = array();
1f54e1ba 2358 $query =
98b52735 2359 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
1f54e1ba 2360 "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
2361 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2362 "inner join Attribute as A on AM.attr_id = A.id " .
e673ee24 2363 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
10bac82a 2364 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
1f54e1ba
DO
2365 "left join Chapter as C on AM.chapter_id = C.id";
2366 if (is_array ($object_set) && !empty ($object_set))
2367 {
2368 $query .= ' WHERE RO.id IN (';
2369 foreach ($object_set as $object_id)
2370 $query .= intval ($object_id) . ', ';
2371 $query = trim ($query, ', ') . ')';
2372 }
98b52735 2373 $query .= " order by A.name, A.type";
1f54e1ba
DO
2374
2375 $result = usePreparedSelectBlade ($query);
e673ee24
DO
2376 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2377 {
1f54e1ba
DO
2378 $object_id = $row['object_id'];
2379 $attr_id = $row['attr_id'];
2380 if (!array_key_exists ($object_id, $ret))
2381 $ret[$object_id] = array();
1f54e1ba 2382
e673ee24
DO
2383 $record = array();
2384 $record['id'] = $row['attr_id'];
2385 $record['name'] = $row['attr_name'];
2386 $record['type'] = $row['attr_type'];
2387 switch ($row['attr_type'])
2388 {
7fa7047a
DO
2389 case 'dict':
2390 $record['chapter_id'] = $row['chapter_id'];
2391 $record['chapter_name'] = $row['chapter_name'];
2392 $record['key'] = $row['uint_value'];
2393 // fall through
e673ee24
DO
2394 case 'uint':
2395 case 'float':
2396 case 'string':
24cbe8af 2397 $record['value'] = $row[$row['attr_type'] . '_value'];
7fa7047a 2398 $record['o_value'] = parseWikiLink ($record['value'], 'o');
24cbe8af
DO
2399 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2400 break;
e673ee24
DO
2401 default:
2402 $record['value'] = NULL;
2403 break;
2404 }
1f54e1ba 2405 $ret[$object_id][$attr_id] = $record;
e673ee24 2406 }
e673ee24
DO
2407 return $ret;
2408}
2409
1f54e1ba 2410// This function returns all optional attributes for requested object
98b52735
DO
2411// as an array of records.
2412// Empty array is returned, if there are no attributes found.
1f54e1ba
DO
2413function getAttrValues ($object_id)
2414{
2415 global $object_attribute_cache;
2416 if (isset ($object_attribute_cache[$object_id]))
2417 return $object_attribute_cache[$object_id];
2418
2419 $ret = fetchAttrsForObjects(array($object_id));
2420 $attrs = array();
98b52735 2421 if (isset ($ret[$object_id]))
1f54e1ba
DO
2422 {
2423 $attrs = $ret[$object_id];
2424 $object_attribute_cache[$object_id] = $attrs;
1f54e1ba 2425 }
98b52735 2426 return $attrs;
1f54e1ba
DO
2427}
2428
e673ee24
DO
2429function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2430{
c9066b1c 2431 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
e673ee24
DO
2432}
2433
e673ee24
DO
2434function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2435{
0cc24e9a
DY
2436 if ($object_id <= 0)
2437 throw new InvalidArgException ('$objtype_id', $objtype_id);
2438 if ($attr_id <= 0)
2439 throw new InvalidArgException ('$attr_id', $attr_id);
59a83bd8 2440 if (!strlen ($value))
e673ee24 2441 return commitResetAttrValue ($object_id, $attr_id);
c9066b1c 2442 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
e673ee24 2443 $row = $result->fetch (PDO::FETCH_NUM);
e673ee24 2444 $attr_type = $row[0];
c9066b1c 2445 unset ($result);
e673ee24
DO
2446 switch ($attr_type)
2447 {
2448 case 'uint':
2449 case 'float':
2450 case 'string':
2451 $column = $attr_type . '_value';
2452 break;
2453 case 'dict':
2454 $column = 'uint_value';
2455 break;
2456 default:
0cc24e9a 2457 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
e673ee24 2458 }
c9066b1c 2459 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
e673ee24 2460 // We know $value isn't empty here.
c9066b1c
DO
2461 usePreparedInsertBlade
2462 (
2463 'AttributeValue',
2464 array
2465 (
2466 $column => $value,
2467 'object_id' => $object_id,
2468 'attr_id' => $attr_id,
2469 )
2470 );
e673ee24
DO
2471 return TRUE;
2472}
2473
2474function commitUseupPort ($port_id = 0)
2475{
32832c0e 2476 return usePreparedExecuteBlade ('UPDATE Port SET reservation_comment=NULL WHERE id=?', array ($port_id));
e673ee24
DO
2477}
2478
3fb56626
DO
2479function convertPDOException ($e)
2480{
ec523868 2481 switch ($e->getCode() . '-' . $e->errorInfo[1])
3fb56626 2482 {
ec523868
DO
2483 case '23000-1062':
2484 $text = 'such record already exists';
2485 break;
2486 case '23000-1205':
3fb56626
DO
2487 $text = 'such record already exists';
2488 break;
ec523868
DO
2489 case '23000-1451':
2490 case '23000-1452':
3fb56626
DO
2491 $text = 'foreign key violation';
2492 break;
ec523868
DO
2493 case 'HY000-1205':
2494 $text = 'lock wait timeout';
3fb56626 2495 break;
ec523868
DO
2496 default:
2497 return $e;
3fb56626 2498 }
ec523868 2499 return new RTDatabaseError ($text);
3fb56626
DO
2500}
2501
e673ee24
DO
2502// This is a swiss-knife blade to insert a record into a table.
2503// The first argument is table name.
2504// The second argument is an array of "name" => "value" pairs.
357eb2ea
DO
2505function usePreparedInsertBlade ($tablename, $columns)
2506{
2507 global $dbxlink;
2508 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
ec523868 2509 $query .= ') VALUES (' . questionMarks (count ($columns)) . ')';
357eb2ea
DO
2510 // Now the query should be as follows:
2511 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
5f054512
DO
2512 try
2513 {
3fb56626 2514 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2515 if (!$prepared->execute (array_values ($columns)))
2516 return FALSE;
2517 return $prepared->rowCount() == 1;
2518 }
2519 catch (PDOException $e)
2520 {
3fb56626 2521 throw convertPDOException ($e);
5f054512 2522 }
357eb2ea
DO
2523}
2524
9589714d
DO
2525// This swiss-knife blade deletes any number of records from the specified table
2526// using the specified key names and values.
bbae3611 2527function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
8198f2c6
DO
2528{
2529 global $dbxlink;
bbae3611
DO
2530 $conj = '';
2531 $query = "DELETE FROM ${tablename} WHERE ";
2532 foreach ($columns as $colname => $colvalue)
2533 {
de47b574 2534 $query .= " ${conj} ${colname}=?";
bbae3611
DO
2535 $conj = $conjunction;
2536 }
5f054512
DO
2537 try
2538 {
3fb56626 2539 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2540 if (!$prepared->execute (array_values ($columns)))
2541 return FALSE;
2542 return $prepared->rowCount(); // FALSE !== 0
2543 }
2544 catch (PDOException $e)
2545 {
3fb56626 2546 throw convertPDOException ($e);
5f054512 2547 }
8198f2c6
DO
2548}
2549
d0dadd80
DO
2550function usePreparedSelectBlade ($query, $args = array())
2551{
2552 global $dbxlink;
2553 $prepared = $dbxlink->prepare ($query);
ec523868
DO
2554 try
2555 {
2556 if (!$prepared->execute ($args))
2557 return FALSE;
2558 return $prepared;
2559 }
2560 catch (PDOException $e)
2561 {
2562 throw convertPDOException ($e);
2563 }
d0dadd80
DO
2564}
2565
39eadd27
DO
2566// Prepare and execute the statement with parameters, then return number of
2567// rows affected (or FALSE in case of an error).
2568function usePreparedExecuteBlade ($query, $args = array())
2569{
2570 global $dbxlink;
3fb56626
DO
2571 try
2572 {
2573 if (!$prepared = $dbxlink->prepare ($query))
2574 return FALSE;
2575 if (!$prepared->execute ($args))
2576 return FALSE;
2577 return $prepared->rowCount();
2578 }
2579 catch (PDOException $e)
2580 {
2581 throw convertPDOException ($e);
2582 }
39eadd27
DO
2583}
2584
9c0b0016
DO
2585function loadConfigCache ()
2586{
c9066b1c 2587 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
3540d15c 2588 $cache = array();
c9066b1c 2589 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3540d15c 2590 $cache[$row['varname']] = $row;
3540d15c
DY
2591 return $cache;
2592}
2593
2594function loadUserConfigCache ($username = NULL)
2595{
2596 if (!strlen ($username))
2597 throw new InvalidArgException ('$username', $username);
c9066b1c 2598 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
9c0b0016
DO
2599 $cache = array();
2600 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2601 $cache[$row['varname']] = $row;
9c0b0016
DO
2602 return $cache;
2603}
2604
3540d15c
DY
2605function deleteUserConfigVar ($username = NULL, $varname = NULL)
2606{
c9066b1c 2607 usePreparedDeleteBlade ('UserConfig', array ('varname' => $varname, 'user' => $username));
3540d15c
DY
2608}
2609
3540d15c
DY
2610function storeUserConfigVar ($username = NULL, $varname = NULL, $varvalue = NULL)
2611{
3540d15c
DY
2612 if (!strlen ($username))
2613 throw new InvalidArgException ('$username', $username);
2614 if (!strlen ($varname))
2615 throw new InvalidArgException ('$varname', $varname);
2616 if ($varvalue === NULL)
2617 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2618 return usePreparedExecuteBlade
2619 (
2620 'REPLACE UserConfig SET varvalue=?, varname=?, user=?',
2621 array ($varvalue, $varname, $username)
e5925cee 2622 );
3540d15c
DY
2623}
2624
9c0b0016
DO
2625// setConfigVar() is expected to perform all necessary filtering
2626function storeConfigVar ($varname = NULL, $varvalue = NULL)
2627{
c5f84f48
DY
2628 if ($varvalue === NULL)
2629 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2630 return usePreparedExecuteBlade
2631 (
2632 'UPDATE Config SET varvalue=? WHERE varname=?',
2633 array ($varvalue, $varname)
2634 );
9c0b0016
DO
2635}
2636
49293c68
DO
2637// Database version detector. Should behave corretly on any
2638// working dataset a user might have.
2639function getDatabaseVersion ()
2640{
2641 $result = usePreparedSelectBlade ('SELECT varvalue FROM Config WHERE varname = "DB_VERSION" and vartype = "string"');
2642 if ($result == NULL)
2643 {
d5add09a 2644 // FIXME: this code is never executed, but an exception thrown instead
49293c68
DO
2645 global $dbxlink;
2646 $errorInfo = $dbxlink->errorInfo();
2647 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2648 return '0.14.4';
2649 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2650 }
2651 $rows = $result->fetchAll (PDO::FETCH_NUM);
d2eb8399 2652 unset ($result);
49293c68 2653 if (count ($rows) != 1 || !strlen ($rows[0][0]))
49293c68 2654 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
49293c68 2655 $ret = $rows[0][0];
49293c68
DO
2656 return $ret;
2657}
2658
da04825a
DO
2659// Return an array of virtual services. For each of them list real server pools
2660// with their load balancers and other stats.
62a1dcb5
DO
2661function getSLBSummary ()
2662{
c9066b1c
DO
2663 $result = usePreparedSelectBlade
2664 (
2665 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
6fec9f39 2666 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2667 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2668 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2669 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
c9066b1c
DO
2670 'group by vs.id, object_id order by vs.vip, object_id'
2671 );
c3bdc503
DO
2672 $ret = array();
2673 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2674 {
4cadac8f 2675 $vsid = $row['vsid'];
da04825a 2676 $object_id = $row['object_id'];
4cadac8f
DO
2677 if (!isset ($ret[$vsid]))
2678 {
2679 $ret[$vsid] = array();
13bffb29 2680 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2681 $ret[$vsid][$cname] = $row[$cname];
da04825a 2682 $ret[$vsid]['lblist'] = array();
4cadac8f 2683 }
6fec9f39
DO
2684 // There's only one assigned RS pool possible for each LB-VS combination.
2685 $ret[$vsid]['lblist'][$row['object_id']] = array
2686 (
2687 'id' => $row['rspool_id'],
2688 'size' => $row['rscount'],
2689 'name' => $row['pool_name']
2690 );
c3bdc503
DO
2691 }
2692 return $ret;
62a1dcb5
DO
2693}
2694
7e7a8387 2695function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2696{
a5c589d2 2697 return usePreparedExecuteBlade
ca461127 2698 (
a5c589d2 2699 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
ca461127
DO
2700 array
2701 (
a5c589d2
DO
2702 $rsip,
2703 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2704 $pool_id,
2705 $inservice == 'yes' ? 'yes' : 'no',
2706 !strlen ($rsconfig) ? NULL : $rsconfig
3241551e
DO
2707 )
2708 );
2709}
2710
c63a8d6e 2711function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21 2712{
c5f84f48
DY
2713 if (!strlen ($vip))
2714 throw new InvalidArgException ('$vip', $vip);
2715 if ($vport <= 0)
2716 throw new InvalidArgException ('$vport', $vport);
2717 if (!strlen ($proto))
2718 throw new InvalidArgException ('$proto', $proto);
a5c589d2 2719 if (FALSE === usePreparedExecuteBlade
d6517a21 2720 (
a5c589d2 2721 'INSERT INTO IPv4VS (vip, vport, proto, name, vsconfig, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?, ?)',
d6517a21
DO
2722 array
2723 (
a5c589d2
DO
2724 $vip,
2725 $vport,
2726 $proto,
2727 !strlen ($name) ? NULL : $name,
2728 !strlen ($vsconfig) ? NULL : $vsconfig,
2729 !strlen ($rsconfig) ? NULL : $rsconfig,
d6517a21 2730 )
c63a8d6e
DO
2731 ))
2732 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2733 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2734}
2735
abd1e9ac 2736function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '', $prio = '')
3241551e 2737{
c9066b1c 2738 return usePreparedInsertBlade
3241551e 2739 (
706ce117 2740 'IPv4LB',
3241551e
DO
2741 array
2742 (
2743 'object_id' => $object_id,
2744 'rspool_id' => $pool_id,
c1ca768c 2745 'vs_id' => $vs_id,
c9066b1c 2746 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
abd1e9ac
DO
2747 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig),
2748 'prio' => (!strlen ($prio) ? NULL : $prio),
3241551e 2749 )
ca461127
DO
2750 );
2751}
2752
fb1c4a54
DO
2753function commitDeleteRS ($id = 0)
2754{
c9066b1c 2755 return usePreparedDeleteBlade ('IPv4RS', array ('id' => $id));
fb1c4a54
DO
2756}
2757
d6517a21
DO
2758function commitDeleteVS ($id = 0)
2759{
6657739e 2760 releaseFiles ('ipv4vs', $id);
0da3bf00 2761 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2762}
2763
c1ca768c 2764function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e 2765{
c9066b1c 2766 return usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id, 'rspool_id' => $pool_id, 'vs_id' => $vs_id));
3241551e
DO
2767}
2768
fb1c4a54
DO
2769function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2770{
fb1c4a54 2771 if (long2ip (ip2long ($rsip)) !== $rsip)
c5f84f48 2772 throw new InvalidArgException ('$rsip', $rsip);
a5c589d2
DO
2773 return usePreparedExecuteBlade
2774 (
2775 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2776 array
2777 (
2778 $rsip,
2779 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2780 !strlen ($rsconfig) ? NULL : $rsconfig,
2781 $rsid,
2782 )
2783 );
fb1c4a54
DO
2784}
2785
1f54e1ba 2786function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '', $prio = '')
3241551e 2787{
a5c589d2
DO
2788 return usePreparedExecuteBlade
2789 (
1f54e1ba 2790 'UPDATE IPv4LB SET vsconfig=?, rsconfig=?, prio=? WHERE object_id=? AND rspool_id=? AND vs_id=?',
a5c589d2
DO
2791 array
2792 (
2793 !strlen ($vsconfig) ? NULL : $vsconfig,
2794 !strlen ($rsconfig) ? NULL : $rsconfig,
1f54e1ba 2795 !strlen ($prio) ? NULL : $prio,
a5c589d2
DO
2796 $object_id,
2797 $pool_id,
2798 $vs_id,
2799 )
2800 );
3241551e
DO
2801}
2802
d6517a21
DO
2803function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2804{
c5f84f48
DY
2805 if (!strlen ($vip))
2806 throw new InvalidArgException ('$vip', $vip);
2807 if ($vport <= 0)
2808 throw new InvalidArgException ('$vport', $vport);
2809 if (!strlen ($proto))
2810 throw new InvalidArgException ('$proto', $proto);
a5c589d2
DO
2811 return usePreparedExecuteBlade
2812 (
2813 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2814 array
2815 (
2816 $vip,
2817 $vport,
2818 $proto,
2819 !strlen ($name) ? NULL : $name,
2820 !strlen ($vsconfig) ? NULL : $vsconfig,
2821 !strlen ($rsconfig) ? NULL : $rsconfig,
2822 $vsid,
2823 )
2824 );
d6517a21
DO
2825}
2826
5a1680d2
DO
2827function loadThumbCache ($rack_id = 0)
2828{
5a1680d2 2829 $ret = NULL;
c9066b1c 2830 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
5a1680d2
DO
2831 $row = $result->fetch (PDO::FETCH_ASSOC);
2832 if ($row)
2833 $ret = base64_decode ($row['thumb_data']);
5a1680d2
DO
2834 return $ret;
2835}
2836
2837function saveThumbCache ($rack_id = 0, $cache = NULL)
2838{
178fda20 2839 if ($cache == NULL)
c5f84f48 2840 throw new InvalidArgException ('$cache', $cache);
a5c589d2 2841 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=? WHERE id=?', array (base64_encode ($cache), $rack_id));
5a1680d2 2842}
9a81d416 2843
c7fe33be
DO
2844function resetThumbCache ($rack_id = 0)
2845{
a5c589d2 2846 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=NULL WHERE id=?', array ($rack_id));
c7fe33be
DO
2847}
2848
748805bf 2849// Return the list of attached RS pools for the given object. As long as we have
706ce117 2850// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2851// by vs_id, because there will be only one RS pool listed for each VS of the
2852// current object.
78e7b769
DO
2853function getRSPoolsForObject ($object_id = 0)
2854{
c9066b1c
DO
2855 $result = usePreparedSelectBlade
2856 (
2857 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
1f54e1ba 2858 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig, lb.prio from ' .
706ce117
DO
2859 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2860 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2861 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
c9066b1c
DO
2862 'where lb.object_id = ? ' .
2863 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2864 array ($object_id)
2865 );
748805bf 2866 $ret = array ();
78e7b769 2867 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f54e1ba 2868 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig', 'prio') as $cname)
748805bf 2869 $ret[$row['vs_id']][$cname] = $row[$cname];
748805bf 2870 return $ret;
78e7b769
DO
2871}
2872
c63a8d6e 2873function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2874{
59a83bd8 2875 if (!strlen ($name))
c5f84f48 2876 throw new InvalidArgException ('$name', $name);
c9066b1c 2877 if (!usePreparedInsertBlade
5ad76f01 2878 (
706ce117 2879 'IPv4RSPool',
5ad76f01
DO
2880 array
2881 (
c9066b1c
DO
2882 'name' => (!strlen ($name) ? NULL : $name),
2883 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2884 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
5ad76f01 2885 )
c63a8d6e
DO
2886 ))
2887 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2888 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2889}
2890
2891function commitDeleteRSPool ($pool_id = 0)
2892{
6657739e 2893 releaseFiles ('ipv4rspool', $pool_id);
c9066b1c 2894 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2895}
2896
2897function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2898{
a5c589d2
DO
2899 return usePreparedExecuteBlade
2900 (
2901 'UPDATE IPv4RSPool SET name=?, vsconfig=?, rsconfig=? WHERE id=?',
2902 array
2903 (
2904 !strlen ($name) ? NULL : $name,
2905 !strlen ($vsconfig) ? NULL : $vsconfig,
2906 !strlen ($rsconfig) ? NULL : $rsconfig,
2907 $pool_id,
2908 )
2909 );
5ad76f01
DO
2910}
2911
8253d9f0
DO
2912function getRSList ()
2913{
c9066b1c
DO
2914 $result = usePreparedSelectBlade
2915 (
2916 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2917 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2918 );
4b0932b6 2919 $ret = array ();
8253d9f0 2920 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2921 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6 2922 $ret[$row['id']][$cname] = $row[$cname];
4b0932b6
DO
2923 return $ret;
2924}
2925
2926// Return the list of all currently configured load balancers with their pool count.
2927function getLBList ()
2928{
c9066b1c
DO
2929 $result = usePreparedSelectBlade
2930 (
2931 "select object_id, count(rspool_id) as poolcount " .
2932 "from IPv4LB group by object_id order by object_id"
2933 );
4b0932b6
DO
2934 $ret = array ();
2935 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2936 $ret[$row['object_id']] = $row['poolcount'];
4b0932b6 2937 return $ret;
8253d9f0
DO
2938}
2939
178fda20 2940// For the given object return: its vsconfig/rsconfig; the list of RS pools
9e677cbd
DO
2941// attached (each with vsconfig/rsconfig in turn), each with the list of
2942// virtual services terminating the pool. Each pool also lists all real
2943// servers with rsconfig.
2987fc1f 2944function getSLBConfig ($object_id)
9e677cbd 2945{
9e677cbd 2946 $ret = array();
e34dac4f
DO
2947 $result = usePreparedSelectBlade
2948 (
2949 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
d91f08f3 2950 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
1f54e1ba 2951 '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 2952 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2953 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2954 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2955 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2956 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
e34dac4f
DO
2957 "where lb.object_id = ? and rs.inservice = 'yes' " .
2958 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2959 array ($object_id)
2960 );
9e677cbd
DO
2961 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2962 {
d91f08f3
DO
2963 $vs_id = $row['vs_id'];
2964 if (!isset ($ret[$vs_id]))
2965 {
1f54e1ba 2966 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
2967 $ret[$vs_id][$c] = $row[$c];
2968 $ret[$vs_id]['rslist'] = array();
2969 }
2970 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2971 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd 2972 }
9e677cbd
DO
2973 return $ret;
2974}
1f7d18fa 2975
1f54e1ba
DO
2976function commitUpdateSLBDefConf ($data)
2977{
2978 return saveScript('DefaultVSConfig', $data['vs']) &&
2979 saveScript('DefaultRSConfig', $data['rs']);
2980}
2981
2982function getSLBDefaults ($do_cache_result = FALSE) {
2983 static $ret = array();
2984
2985 if (! $do_cache_result)
2986 $ret = array();
2987 elseif (! empty ($ret))
2988 return $ret;
2989
2990 $ret['vs'] = loadScript('DefaultVSConfig');
2991 $ret['rs'] = loadScript('DefaultRSConfig');
2992 return $ret;
2993}
2994
1f7d18fa
DO
2995function commitSetInService ($rs_id = 0, $inservice = '')
2996{
c5f84f48
DY
2997 if (!strlen ($inservice))
2998 throw new InvalidArgException ('$inservice', $inservice);
a5c589d2 2999 return usePreparedExecuteBlade ('UPDATE IPv4RS SET inservice=? WHERE id=?', array ($inservice, $rs_id));
1f7d18fa
DO
3000}
3001
ad0e4754
DO
3002function executeAutoPorts ($object_id = 0, $type_id = 0)
3003{
c5f84f48
DY
3004 if ($object_id == 0)
3005 throw new InvalidArgException ('$object_id', $object_id);
3006 if ($type_id == 0)
3007 throw new InvalidArgException ('$type_id', $type_id);
f3f0161f 3008 $ret = TRUE;
118e4c38 3009 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
3010 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
3011 return $ret;
ad0e4754
DO
3012}
3013
6e49bd1f 3014// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 3015// generated/deducted later at higher levels.
aab37bc0 3016// Result is a chain: randomly indexed taginfo list.
f9bc186f 3017function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 3018{
a6e8d544 3019 $ret = array();
e34dac4f
DO
3020 $result = usePreparedSelectBlade
3021 (
3022 "select tt.id, tag from " .
edf0993c 3023 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
e34dac4f
DO
3024 "where entity_realm = ? and entity_id = ? " .
3025 "order by tt.tag",
3026 array ($entity_realm, $entity_id)
3027 );
5967b83d 3028 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 3029 $ret[$row['id']] = $row;
aab37bc0 3030 return getExplicitTagsOnly ($ret);
5967b83d
DO
3031}
3032
351c0966 3033// Return a tag chain with all DB tags on it.
5967b83d
DO
3034function getTagList ()
3035{
20c901a7 3036 $ret = array();
e34dac4f
DO
3037 $result = usePreparedSelectBlade
3038 (
3039 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 3040 "from TagTree left join TagStorage on id = tag_id " .
e34dac4f
DO
3041 "group by id, entity_realm order by tag"
3042 );
3043 // Collation index. The resulting rows are ordered according to default collation,
fb7a4967 3044 // which is utf8_general_ci for UTF-8.
e34dac4f 3045 $ci = 0;
5967b83d 3046 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 3047 {
7cc02fc1 3048 if (!isset ($ret[$row['id']]))
20c901a7 3049 $ret[$row['id']] = array
5b7bd02e
DO
3050 (
3051 'id' => $row['id'],
3052 'tag' => $row['tag'],
fb7a4967 3053 'ci' => $ci++,
5b7bd02e 3054 'parent_id' => $row['parent_id'],
9e51318b 3055 'refcnt' => array ('total' => 0)
5b7bd02e
DO
3056 );
3057 if ($row['realm'])
9e51318b 3058 {
20c901a7 3059 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
9e51318b 3060 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
21ee3351
AA
3061 // introduce the 'pseudo'-ream 'ipnet' which combines 'ipv4net' and 'ipv6net' realms.
3062 if ($row['realm'] == 'ipv4net' || $row['realm'] == 'ipv6net')
3063 if (isset ($ret[$row['id']]['refcnt']['ipnet']))
3064 $ret[$row['id']]['refcnt']['ipnet'] += $row['refcnt'];
3065 else
3066 $ret[$row['id']]['refcnt']['ipnet'] = $row['refcnt'];
9e51318b 3067 }
5b7bd02e 3068 }
20c901a7 3069 return $ret;
5967b83d
DO
3070}
3071
fe7044ad
DO
3072function commitCreateTag ($tagname = '', $parent_id = 0)
3073{
6cfedb71
DO
3074 if ($tagname == '')
3075 throw new InvalidArgException ('tagname', $tagname);
3076 return usePreparedInsertBlade
fe7044ad
DO
3077 (
3078 'TagTree',
3079 array
3080 (
e34dac4f 3081 'tag' => $tagname,
fe7044ad
DO
3082 'parent_id' => $parent_id
3083 )
3084 );
fe7044ad
DO
3085}
3086
3087function commitDestroyTag ($tagid = 0)
3088{
e34dac4f 3089 if (usePreparedDeleteBlade ('TagTree', array ('id' => $tagid)))
fe7044ad 3090 return '';
e34dac4f 3091 return 'usePreparedDeleteBlade() failed in ' . __FUNCTION__;
fe7044ad 3092}
f9bc186f 3093
49fb1027 3094function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 3095{
a5c589d2
DO
3096 return usePreparedExecuteBlade
3097 (
3098 'UPDATE TagTree SET tag=?, parent_id=? WHERE id=?',
3099 array
3100 (
3101 $tag_name,
3102 $parent_id == 0 ? NULL : $parent_id,
3103 $tag_id,
3104 )
3105 );
f9bc186f
DO
3106}
3107
01b6b4d6
DO
3108// Drop the whole chain stored.
3109function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af 3110{
e34dac4f 3111 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
aedf18af
DO
3112}
3113
01b6b4d6 3114// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
29c3a4d8
DO
3115// FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
3116// but not now.
01b6b4d6
DO
3117function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
3118{
e34dac4f 3119 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
01b6b4d6
DO
3120}
3121
351c0966 3122// Push a record into TagStorage unconditionally.
3355ca56 3123function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 3124{
21ee3351
AA
3125 global $SQLSchema;
3126 if (! isset ($SQLSchema[$realm]))
3355ca56 3127 return FALSE;
e34dac4f 3128 return usePreparedInsertBlade
eb6ea26f
DO
3129 (
3130 'TagStorage',
3131 array
3132 (
e34dac4f 3133 'entity_realm' => $realm,
120e9ddd 3134 'entity_id' => $entity_id,
eb6ea26f
DO
3135 'tag_id' => $tag_id,
3136 )
3137 );
3138}
3139
351c0966 3140// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
3141// on the implicit list already). Then remove any other records, which
3142// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
3143// that both the tag base is still minimal and all requested tags appear on
3144// the resulting tag chain.
abef7149
DO
3145// Return TRUE, if any changes were committed.
3146function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3147{
3148 // Put the current explicit sub-chain into a buffer and merge all tags from
3149 // the extra chain, which aren't there yet.
3150 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3151 foreach ($extrachain as $extratag)
3152 if (!tagOnChain ($extratag, $newchain))
3153 $newchain[] = $extratag;
3154 // Then minimize the working buffer and check if it differs from the original
3155 // chain we started with. If it is so, save the work and signal the upper layer.
3156 $newchain = getExplicitTagsOnly ($newchain);
3157 if (tagChainCmp ($oldchain, $newchain))
3158 {
01b6b4d6 3159 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
3160 foreach ($newchain as $taginfo)
3161 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3162 return TRUE;
3163 }
3164 return FALSE;
351c0966
DO
3165}
3166
3167// Presume, that the target record has no tags attached.
3168function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3169{
3170 if (!count ($tagidlist))
c63a8d6e
DO
3171 return '';
3172 if (!$last_insert_id)
3173 $last_insert_id = lastInsertID();
3174 $errcount = 0;
abef7149 3175 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 3176 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
3177 $errcount++;
3178 if (!$errcount)
3179 return '';
3180 else
3181 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3182}
3183
42023f03
DO
3184function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3185{
3186 // $range is in x.x.x.x/x format, split into ip/mask vars
3187 $rangeArray = explode('/', $range);
3188 if (count ($rangeArray) != 2)
3189 return "Invalid IPv4 prefix '${range}'";
3190 $ip = $rangeArray[0];
3191 $mask = $rangeArray[1];
3192
59a83bd8 3193 if (!strlen ($ip) or !strlen ($mask))
42023f03
DO
3194 return "Invalid IPv4 prefix '${range}'";
3195 $ipL = ip2long($ip);
3196 $maskL = ip2long($mask);
3197 if ($ipL == -1 || $ipL === FALSE)
3198 return 'Bad IPv4 address';
3199 if ($mask < 32 && $mask > 0)
3200 $maskL = $mask;
3201 else
3202 {
3203 $maskB = decbin($maskL);
3204 if (strlen($maskB)!=32)
3205 return 'Invalid netmask';
3206 $ones=0;
3207 $zeroes=FALSE;
3208 foreach( str_split ($maskB) as $digit)
3209 {
3210 if ($digit == '0')
3211 $zeroes = TRUE;
3212 if ($digit == '1')
3213 {
3214 $ones++;
3215 if ($zeroes == TRUE)
3216 return 'Invalid netmask';
3217 }
3218 }
3219 $maskL = $ones;
3220 }
3221 $binmask = binMaskFromDec($maskL);
3222 $ipL = $ipL & $binmask;
357eb2ea 3223 $result = usePreparedInsertBlade
42023f03 3224 (
706ce117 3225 'IPv4Network',
42023f03
DO
3226 array
3227 (
3228 'ip' => sprintf ('%u', $ipL),
357eb2ea
DO
3229 'mask' => $maskL,
3230 'name' => $name
42023f03
DO
3231 )
3232 );
e782fca4
DO
3233 if ($result != TRUE)
3234 return "Could not add ${range} (already exists?).";
42023f03
DO
3235
3236 if ($is_bcast and $maskL < 31)
3237 {
3238 $network_addr = long2ip ($ipL);
3239 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
21ee3351
AA
3240 updateV4Address ($network_addr, 'network', 'yes');
3241 updateV4Address ($broadcast_addr, 'broadcast', 'yes');
42023f03 3242 }
351c0966 3243 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
3244}
3245
21ee3351
AA
3246function createIPv6Prefix ($range = '', $name = '', $taglist = array())
3247{
3248 // $range is in aaa0:b::c:d/x format, split into ip/mask vars
3249 $rangeArray = explode ('/', $range);
3250 if (count ($rangeArray) != 2)
3251 return "Invalid IPv6 prefix '${range}'";
3252 $ip = $rangeArray[0];
3253 $mask = $rangeArray[1];
3254 $address = new IPv6Address;
3255 if (!strlen ($ip) or !strlen ($mask) or ! $address->parse ($ip))
3256 return "Invalid IPv6 prefix '${range}'";
3257 $network_addr = $address->get_first_subnet_address ($mask);
3258 $broadcast_addr = $address->get_last_subnet_address ($mask);
3259 if (! $network_addr || ! $broadcast_addr)
3260 return 'Invalid netmask';
3261 $result = usePreparedInsertBlade
3262 (
3263 'IPv6Network',
3264 array
3265 (
3266 'ip' => $network_addr,
3267 'last_ip' => $broadcast_addr,
3268 'mask' => $mask,
3269 'name' => $name
3270 )
3271 );
3272 if ($result != TRUE)
3273 return "Could not add ${range} (already exists?).";
3274
3275 return produceTagsForLastRecord ('ipv6net', $taglist);
3276}
3277
706ce117 3278// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
3279function destroyIPv4Prefix ($id = 0)
3280{
6657739e 3281 releaseFiles ('ipv4net', $id);
e34dac4f 3282 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
42023f03 3283 return __FUNCTION__ . ': SQL query #1 failed';
0da3bf00 3284 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
3285 return __FUNCTION__ . ': SQL query #2 failed';
3286 return '';
3287}
3288
21ee3351
AA
3289// FIXME: This function doesn't wipe relevant records from IPv6Address table.
3290function destroyIPv6Prefix ($id = 0)
3291{
3292 releaseFiles ('ipv6net', $id);
3293 if (FALSE === usePreparedDeleteBlade ('IPv6Network', array ('id' => $id)))
3294 return __FUNCTION__ . ': SQL query #1 failed';
3295 if (FALSE === destroyTagsForEntity ('ipv6net', $id))
3296 return __FUNCTION__ . ': SQL query #2 failed';
3297 return '';
3298}
3299
ebae41b3
DO
3300function loadScript ($name)
3301{
e34dac4f 3302 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
ebae41b3 3303 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
3304 if ($row !== FALSE)
3305 return $row[0];
3306 else
3307 return NULL;
ebae41b3
DO
3308}
3309
178fda20 3310function saveScript ($name = '', $text)
ebae41b3 3311{
59a83bd8 3312 if (!strlen ($name))
c5f84f48 3313 throw new InvalidArgException ('$name', $name);
bb09f49c 3314 return usePreparedExecuteBlade
ebae41b3 3315 (
bb09f49c
DO
3316 'INSERT INTO Script (script_name, script_text) VALUES (?, ?) ' .
3317 'ON DUPLICATE KEY UPDATE script_text=?',
3318 array ($name, $text, $text)
ebae41b3
DO
3319 );
3320}
3321
d983f70a
DO
3322function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3323{
3324 if (NULL === getIPv4AddressNetworkId ($localip))
3325 return "$localip: Non existant ip";
0929db7f 3326 if (NULL === getIPv4AddressNetworkId ($remoteip))
d983f70a
DO
3327 return "$remoteip: Non existant ip";
3328 if ( ($localport <= 0) or ($localport >= 65536) )
3329 return "$localport: invaild port";
3330 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3331 return "$remoteport: invaild port";
3332
a5c589d2 3333 $result = usePreparedExecuteBlade
d983f70a 3334 (
a5c589d2
DO
3335 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
3336 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
d983f70a
DO
3337 array
3338 (
a5c589d2
DO
3339 $object_id,
3340 $localip,
3341 $remoteip,
3342 $localport,
3343 $remoteport,
3344 $proto,
3345 $description,
d983f70a
DO
3346 )
3347 );
a5c589d2 3348 return $result !== FALSE ? '' : (__FUNCTION__ . '(): failed to insert the rule');
d983f70a
DO
3349}
3350
3351function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3352{
a5c589d2
DO
3353 return usePreparedExecuteBlade
3354 (
3355 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
3356 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
3357 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
3358 );
d983f70a
DO
3359}
3360
3361function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3362{
a5c589d2
DO
3363 return usePreparedExecuteBlade
3364 (
3365 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
3366 'AND localport=? AND remoteport=? AND proto=?',
3367 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
3368 );
d983f70a
DO
3369}
3370
3371function getNATv4ForObject ($object_id)
3372{
3373 $ret = array();
3374 $ret['out'] = array();
3375 $ret['in'] = array();
e34dac4f
DO
3376 $result = usePreparedSelectBlade
3377 (
d983f70a
DO
3378 "select ".
3379 "proto, ".
3380 "INET_NTOA(localip) as localip, ".
3381 "localport, ".
3382 "INET_NTOA(remoteip) as remoteip, ".
3383 "remoteport, ".
3384 "ipa1.name as local_addr_name, " .
3385 "ipa2.name as remote_addr_name, " .
3386 "description ".
706ce117
DO
3387 "from IPv4NAT ".
3388 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3389 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
e34dac4f
DO
3390 "where object_id=? ".
3391 "order by localip, localport, proto, remoteip, remoteport",
3392 array ($object_id)
3393 );
d983f70a
DO
3394 $count=0;
3395 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3396 {
3397 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3398 $ret['out'][$count][$cname] = $row[$cname];
3399 $count++;
3400 }
d983f70a
DO
3401 unset ($result);
3402
e34dac4f
DO
3403 $result = usePreparedSelectBlade
3404 (
d983f70a
DO
3405 "select ".
3406 "proto, ".
3407 "INET_NTOA(localip) as localip, ".
3408 "localport, ".
3409 "INET_NTOA(remoteip) as remoteip, ".
3410 "remoteport, ".
706ce117 3411 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
3412 "RackObject.name as object_name, ".
3413 "description ".
706ce117 3414 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
e34dac4f
DO
3415 "where IPv4Allocation.object_id=? ".
3416 "order by remoteip, remoteport, proto, localip, localport",
3417 array ($object_id)
3418 );
d983f70a
DO
3419 $count=0;
3420 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3421 {
3422 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3423 $ret['in'][$count][$cname] = $row[$cname];
3424 $count++;
3425 }
d983f70a
DO
3426 return $ret;
3427}
3428
178fda20 3429// Return a list of files, which are not linked to the specified record. This list
121496b6 3430// will be used by printSelect().
e1ae3fb4
AD
3431function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3432{
e34dac4f
DO
3433 $query = usePreparedSelectBlade
3434 (
121496b6 3435 'SELECT id, name FROM File ' .
e1ae3fb4 3436 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
e34dac4f
DO
3437 'ORDER BY name, id',
3438 array ($entity_type, $entity_id)
3439 );
e1ae3fb4 3440 $ret=array();
e1ae3fb4 3441 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3442 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3443 return $ret;
3444}
3445
6df2025d
DO
3446// FIXME: return a standard cell list, so upper layer can iterate over
3447// it conveniently.
e1ae3fb4
AD
3448function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3449{
e34dac4f
DO
3450 $query = usePreparedSelectBlade
3451 (
e1ae3fb4
AD
3452 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3453 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
e34dac4f
DO
3454 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3455 array ($entity_type, $entity_id)
3456 );
e1ae3fb4
AD
3457 $ret = array();
3458 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3459 $ret[$row['file_id']] = array (
b3567368 3460 'id' => $row['file_id'],
e1ae3fb4
AD
3461 'link_id' => $row['link_id'],
3462 'name' => $row['name'],
3463 'type' => $row['type'],
3464 'size' => $row['size'],
3465 'ctime' => $row['ctime'],
3466 'mtime' => $row['mtime'],
3467 'atime' => $row['atime'],
3468 'comment' => $row['comment'],
3469 );
3470 return $ret;
3471}
3472
3473function getFile ($file_id = 0)
3474{
6cfedb71
DO
3475 $query = usePreparedSelectBlade
3476 (
3477 'SELECT id, name, type, size, ctime, mtime, atime, contents, comment ' .
3478 'FROM File WHERE id = ?',
3479 array ($file_id)
3480 );
e1ae3fb4
AD
3481 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3482 {
0cc24e9a 3483 showWarning ('Query succeeded, but returned no data', __FUNCTION__);
e1ae3fb4
AD
3484 $ret = NULL;
3485 }
3486 else
3487 {
3488 $ret = array();
3489 $ret['id'] = $row['id'];
3490 $ret['name'] = $row['name'];
3491 $ret['type'] = $row['type'];
3492 $ret['size'] = $row['size'];
3493 $ret['ctime'] = $row['ctime'];
3494 $ret['mtime'] = $row['mtime'];
3495 $ret['atime'] = $row['atime'];
3496 $ret['contents'] = $row['contents'];
3497 $ret['comment'] = $row['comment'];
d2eb8399 3498 unset ($query);
e1ae3fb4 3499
deb3da1b 3500 // Someone accessed this file, update atime
6cfedb71 3501 usePreparedExecuteBlade ('UPDATE File SET atime = ? WHERE id = ?', array (date ('YmdHis'), $file_id));
e1ae3fb4 3502 }
e1ae3fb4
AD
3503 return $ret;
3504}
3505
d3346ce2
DO
3506function getFileCache ($file_id = 0)
3507{
3508 $query = usePreparedSelectBlade
3509 (
3510 'SELECT File.thumbnail FROM File ' .
3511 'WHERE File.id = ? and File.thumbnail IS NOT NULL',
3512 array ($file_id)
3513 );
3514 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3515 return FALSE;
3516 $ret = $row['contents'];
3517 $query->CloseCursor();
3518 usePreparedExecuteBlade ('UPDATE File SET atime = ? WHERE id = ?', array (date ('YmdHis'), $file_id));