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