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