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