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