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