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