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