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