r3801 printPDOException(): don't call printPageHeaders(), which indirectly accesses...
[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]))
c5f84f48 242 throw new RealmNotFoundException ($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]))
c5f84f48 336 throw new RealmNotFoundException ($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{
05771508
DO
842 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
843 return "Invalid L2 address ${port_l2address}";
029a14bc
DO
844 global $dbxlink;
845 $dbxlink->exec ('LOCK TABLES Port WRITE');
846 if (alreadyUsedL2Address ($db_l2address, $object_id))
847 {
848 $dbxlink->exec ('UNLOCK TABLES');
849 return "address ${db_l2address} belongs to another object";
850 }
3153a326
DO
851 $matches = array();
852 switch (1)
853 {
854 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
855 $iif_id = $matches[1];
856 $oif_id = $matches[2];
857 break;
858 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
859 $iif_id = 1;
860 $oif_id = $matches[1];
861 break;
862 default:
863 $dbxlink->exec ('UNLOCK TABLES');
864 return "invalid port type id '${port_type_id}'";
865 }
298d2375 866 $result = usePreparedInsertBlade
e673ee24
DO
867 (
868 'Port',
869 array
870 (
298d2375 871 'name' => $port_name,
3153a326 872 'object_id' => $object_id,
298d2375 873 'label' => $port_label,
3153a326
DO
874 'iif_id' => $iif_id,
875 'type' => $oif_id,
298d2375 876 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
e673ee24
DO
877 )
878 );
029a14bc 879 $dbxlink->exec ('UNLOCK TABLES');
e673ee24
DO
880 if ($result)
881 return '';
882 else
883 return 'SQL query failed';
884}
885
d0a69ce8
DO
886// The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
887// string value. In case it is omitted, we just assign it its current value.
888// It would be nice to simplify this semantics later.
6be06cbb 889function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
e673ee24 890{
05771508
DO
891 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
892 return "Invalid L2 address ${port_l2address}";
029a14bc
DO
893 global $dbxlink;
894 $dbxlink->exec ('LOCK TABLES Port WRITE');
895 if (alreadyUsedL2Address ($db_l2address, $object_id))
896 {
897 $dbxlink->exec ('UNLOCK TABLES');
898 return "address ${db_l2address} belongs to another object";
899 }
a5c589d2
DO
900 $result = usePreparedExecuteBlade
901 (
902 'UPDATE Port SET name=?, type=?, label=?, reservation_comment=?, ' .
903 'l2address=? WHERE id=? AND object_id=?',
904 array
905 (
906 $port_name,
907 $port_type_id,
908 $port_label,
909 $port_reservation_comment,
910 ($db_l2address === '') ? NULL : $db_l2address,
911 $port_id,
912 $object_id
913 )
914 );
029a14bc 915 $dbxlink->exec ('UNLOCK TABLES');
e673ee24
DO
916 if ($result == 1)
917 return '';
918 $errorInfo = $dbxlink->errorInfo();
919 // We could update nothing.
920 if ($errorInfo[0] == '00000')
921 return '';
922 return $errorInfo[2];
923}
924
925function delObjectPort ($port_id)
926{
298d2375
DO
927 if (usePreparedDeleteBlade ('Port', array ('id' => $port_id)) != TRUE)
928 return __FUNCTION__ . ': usePreparedDeleteBlade() failed';
e673ee24
DO
929 return '';
930}
931
6ef9683b 932function getAllIPv4Allocations ()
e673ee24 933{
298d2375
DO
934 $result = usePreparedSelectBlade
935 (
e673ee24
DO
936 "select object_id as object_id, ".
937 "RackObject.name as object_name, ".
706ce117 938 "IPv4Allocation.name as name, ".
e673ee24 939 "INET_NTOA(ip) as ip ".
298d2375
DO
940 "from IPv4Allocation join RackObject on id=object_id "
941 );
e673ee24 942 $ret = array();
e673ee24 943 while ($row = $result->fetch (PDO::FETCH_ASSOC))
298d2375 944 $ret[] = $row;
e673ee24
DO
945 return $ret;
946}
947
e673ee24
DO
948function linkPorts ($porta, $portb)
949{
950 if ($porta == $portb)
32832c0e 951 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
e673ee24
DO
952 if ($porta > $portb)
953 {
954 $tmp = $porta;
955 $porta = $portb;
956 $portb = $tmp;
957 }
32832c0e
DO
958 $ret = FALSE !== usePreparedInsertBlade ('Link', array ('porta' => $porta, 'portb' => $portb));
959 $ret = $ret and FALSE !== usePreparedExecuteBlade
960 (
961 'UPDATE Port SET reservation_comment=NULL WHERE id IN(?, ?)',
962 array ($porta, $portb)
963 );
964 return $ret ? '' : 'query failed';
e673ee24
DO
965}
966
cd3775e9 967function unlinkPort ($port_id)
e673ee24 968{
298d2375 969 usePreparedDeleteBlade ('Link', array ('porta' => $port_id, 'portb' => $port_id), 'OR');
e673ee24 970 return '';
e673ee24
DO
971}
972
2c817354
DO
973// Return all IPv4 addresses allocated to the objects. Attach detailed
974// info about address to each alocation records. Index result by dotted-quad
975// address.
0ab782bc
DO
976function getObjectIPv4Allocations ($object_id = 0)
977{
978 $ret = array();
298d2375
DO
979 $result = usePreparedSelectBlade
980 (
981 'SELECT name AS osif, type, inet_ntoa(ip) AS dottedquad FROM IPv4Allocation ' .
982 'WHERE object_id = ? ORDER BY ip',
983 array ($object_id)
650ef981 984 );
85970da2 985 // don't spawn a sub-query with unfetched buffer, it may fail
0ab782bc 986 while ($row = $result->fetch (PDO::FETCH_ASSOC))
85970da2
DO
987 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
988 unset ($result);
989 foreach (array_keys ($ret) as $dottedquad)
990 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
0ab782bc
DO
991 return $ret;
992}
993
e6ca609a
DO
994// Return minimal IPv4 address, optionally with "ip" key set, if requested.
995function constructIPv4Address ($dottedquad = NULL)
a910829d 996{
e6ca609a 997 $ret = array
a910829d
DO
998 (
999 'name' => '',
1000 'reserved' => 'no',
a910829d
DO
1001 'outpf' => array(),
1002 'inpf' => array(),
a910829d 1003 'rslist' => array(),
2d318652 1004 'allocs' => array(),
a910829d
DO
1005 'lblist' => array()
1006 );
e6ca609a
DO
1007 if ($dottedquad != NULL)
1008 $ret['ip'] = $dottedquad;
1009 return $ret;
1010}
1011
1012// Check the range requested for meaningful IPv4 records, build them
1013// into a list and return. Return an empty list if nothing matched.
1014// Both arguments are expected in signed int32 form. The resulting list
1015// is keyed by uint32 form of each IP address, items aren't sorted.
f7414fa5
DO
1016// LATER: accept a list of pairs and build WHERE sub-expression accordingly
1017function scanIPv4Space ($pairlist)
e6ca609a
DO
1018{
1019 $ret = array();
f7414fa5 1020 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
178fda20 1021 return $ret;
f7414fa5
DO
1022 // FIXME: this is a copy-and-paste prototype
1023 $or = '';
1024 $whereexpr1 = '(';
1025 $whereexpr2 = '(';
1026 $whereexpr3 = '(';
1027 $whereexpr4 = '(';
1028 $whereexpr5a = '(';
1029 $whereexpr5b = '(';
a5c589d2 1030 $qparams = array();
f7414fa5
DO
1031 foreach ($pairlist as $tmp)
1032 {
1033 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
1034 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
a5c589d2
DO
1035 $whereexpr1 .= $or . "ip between ? and ?";
1036 $whereexpr2 .= $or . "ip between ? and ?";
1037 $whereexpr3 .= $or . "vip between ? and ?";
1038 $whereexpr4 .= $or . "rsip between ? and ?";
1039 $whereexpr5a .= $or . "remoteip between ? and ?";
1040 $whereexpr5b .= $or . "localip between ? and ?";
f7414fa5 1041 $or = ' or ';
a5c589d2
DO
1042 $qparams[] = $db_first;
1043 $qparams[] = $db_last;
f7414fa5
DO
1044 }
1045 $whereexpr1 .= ')';
1046 $whereexpr2 .= ')';
1047 $whereexpr3 .= ')';
1048 $whereexpr4 .= ')';
1049 $whereexpr5a .= ')';
1050 $whereexpr5b .= ')';
a910829d
DO
1051
1052 // 1. collect labels and reservations
706ce117 1053 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
f7414fa5 1054 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
a5c589d2 1055 $result = usePreparedSelectBlade ($query, $qparams);
a910829d
DO
1056 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1057 {
2d318652
DO
1058 $ip_bin = ip2long ($row['ip']);
1059 if (!isset ($ret[$ip_bin]))
e6ca609a 1060 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
2d318652
DO
1061 $ret[$ip_bin]['name'] = $row['name'];
1062 $ret[$ip_bin]['reserved'] = $row['reserved'];
a910829d
DO
1063 }
1064 unset ($result);
1065
1066 // 2. check for allocations
1067 $query =
a1f97745
DO
1068 "select INET_NTOA(ip) as ip, object_id, name, type " .
1069 "from IPv4Allocation where ${whereexpr2} order by type";
a5c589d2 1070 $result = usePreparedSelectBlade ($query, $qparams);
a1f97745
DO
1071 // release DBX early to avoid issues with nested spotEntity() calls
1072 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1073 unset ($result);
1074 foreach ($allRows as $row)
a910829d 1075 {
2d318652
DO
1076 $ip_bin = ip2long ($row['ip']);
1077 if (!isset ($ret[$ip_bin]))
e6ca609a 1078 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a1f97745
DO
1079 $oinfo = spotEntity ('object', $row['object_id']);
1080 $ret[$ip_bin]['allocs'][] = array
1081 (
1082 'type' => $row['type'],
1083 'name' => $row['name'],
1084 'object_id' => $row['object_id'],
1085 'object_name' => $oinfo['dname'],
1086 );
a910829d 1087 }
a910829d
DO
1088
1089 // 3. look for virtual services and related LB
a1f97745
DO
1090 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, object_id " .
1091 "from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1092 "where ${whereexpr3} order by vport, proto, object_id";
a5c589d2 1093 $result = usePreparedSelectBlade ($query, $qparams);
a1f97745
DO
1094 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1095 unset ($result);
1096 foreach ($allRows as $row)
a910829d 1097 {
2d318652 1098 $ip_bin = ip2long ($row['ip']);
f3d0cb20 1099 if (!isset ($ret[$ip_bin]))
e6ca609a 1100 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a1f97745
DO
1101 $oinfo = spotEntity ('object', $row['object_id']);
1102 $ret[$ip_bin]['lblist'][] = array
1103 (
1104 'vport' => $row['vport'],
1105 'proto' => $row['proto'],
1106 'vs_id' => $row['vs_id'],
1107 'name' => $row['name'],
1108 'vip' => $row['ip'],
1109 'object_id' => $row['object_id'],
1110 'object_name' => $oinfo['dname'],
1111 );
a910829d 1112 }
a910829d
DO
1113
1114 // 4. don't forget about real servers along with pools
2d318652 1115 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
706ce117 1116 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
f7414fa5 1117 "where ${whereexpr4} " .
a910829d 1118 "order by ip, rsport, rspool_id";
a5c589d2 1119 $result = usePreparedSelectBlade ($query, $qparams);
a910829d
DO
1120 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1121 {
2d318652
DO
1122 $ip_bin = ip2long ($row['ip']);
1123 if (!isset ($ret[$ip_bin]))
e6ca609a 1124 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1125 $tmp = array();
1126 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1127 $tmp[$cname] = $row[$cname];
2d318652 1128 $ret[$ip_bin]['rslist'][] = $tmp;
a910829d
DO
1129 }
1130 unset ($result);
1131
1132 // 5. add NAT rules, part 1
1133 $query =
1134 "select " .
1135 "proto, " .
1136 "INET_NTOA(localip) as localip, " .
1137 "localport, " .
1138 "INET_NTOA(remoteip) as remoteip, " .
1139 "remoteport, " .
1140 "description " .
706ce117 1141 "from IPv4NAT " .
51332e78 1142 "where ${whereexpr5a} " .
a910829d 1143 "order by localip, localport, remoteip, remoteport, proto";
a5c589d2 1144 $result = usePreparedSelectBlade ($query, $qparams);
a910829d
DO
1145 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1146 {
2d318652 1147 $remoteip_bin = ip2long ($row['remoteip']);
51332e78
DO
1148 if (!isset ($ret[$remoteip_bin]))
1149 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1150 $ret[$remoteip_bin]['inpf'][] = $row;
1151 }
1152 unset ($result);
1153 // 5. add NAT rules, part 2
1154 $query =
1155 "select " .
1156 "proto, " .
1157 "INET_NTOA(localip) as localip, " .
1158 "localport, " .
1159 "INET_NTOA(remoteip) as remoteip, " .
1160 "remoteport, " .
1161 "description " .
706ce117 1162 "from IPv4NAT " .
51332e78
DO
1163 "where ${whereexpr5b} " .
1164 "order by localip, localport, remoteip, remoteport, proto";
a5c589d2 1165 $result = usePreparedSelectBlade ($query, $qparams);
51332e78
DO
1166 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1167 {
2d318652 1168 $localip_bin = ip2long ($row['localip']);
51332e78
DO
1169 if (!isset ($ret[$localip_bin]))
1170 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1171 $ret[$localip_bin]['outpf'][] = $row;
a910829d 1172 }
51332e78 1173 unset ($result);
a910829d
DO
1174 return $ret;
1175}
1176
2d318652
DO
1177function getIPv4Address ($dottedquad = '')
1178{
1179 if ($dottedquad == '')
c5f84f48 1180 throw new InvalidArgException ('$dottedquad', $dottedquad);
2d318652 1181 $i32 = ip2long ($dottedquad); // signed 32 bit
f7414fa5 1182 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
2d318652 1183 if (!isset ($scanres[$i32]))
8b980e24 1184 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
e6ca609a 1185 return constructIPv4Address ($dottedquad);
2d318652
DO
1186 markupIPv4AddrList ($scanres);
1187 return $scanres[$i32];
a910829d
DO
1188}
1189
5222f192
DO
1190function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1191{
a5c589d2 1192 $result = usePreparedExecuteBlade
5222f192 1193 (
a5c589d2
DO
1194 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1195 array ($ip, $object_id, $name, $type)
5222f192 1196 );
a5c589d2 1197 return $result ? '' : (__FUNCTION__ . '(): query failed');
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{
2119 if ($e->getCode() != 23000)
2120 return $e;
2121 switch ($e->errorInfo[1])
2122 {
2123 case 1062:
2124 $text = 'such record already exists';
2125 break;
2126 case 1451:
2127 case 1452:
2128 $text = 'foreign key violation';
2129 break;
2130 default:
2131 $text = 'unknown error code ' . $e->errorInfo[1];
2132 break;
2133 }
2134 return new Exception ($text, E_DB_CONSTRAINT);
2135}
2136
e673ee24
DO
2137// This is a swiss-knife blade to insert a record into a table.
2138// The first argument is table name.
2139// The second argument is an array of "name" => "value" pairs.
357eb2ea
DO
2140function usePreparedInsertBlade ($tablename, $columns)
2141{
2142 global $dbxlink;
2143 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2144 $query .= ') VALUES (' . implode (', ', array_fill (0, count ($columns), '?')) . ')';
2145 // Now the query should be as follows:
2146 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
5f054512
DO
2147 try
2148 {
3fb56626 2149 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2150 if (!$prepared->execute (array_values ($columns)))
2151 return FALSE;
2152 return $prepared->rowCount() == 1;
2153 }
2154 catch (PDOException $e)
2155 {
3fb56626 2156 throw convertPDOException ($e);
5f054512 2157 }
357eb2ea
DO
2158}
2159
9589714d
DO
2160// This swiss-knife blade deletes any number of records from the specified table
2161// using the specified key names and values.
bbae3611 2162function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
8198f2c6
DO
2163{
2164 global $dbxlink;
bbae3611
DO
2165 $conj = '';
2166 $query = "DELETE FROM ${tablename} WHERE ";
2167 foreach ($columns as $colname => $colvalue)
2168 {
de47b574 2169 $query .= " ${conj} ${colname}=?";
bbae3611
DO
2170 $conj = $conjunction;
2171 }
5f054512
DO
2172 try
2173 {
3fb56626 2174 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2175 if (!$prepared->execute (array_values ($columns)))
2176 return FALSE;
2177 return $prepared->rowCount(); // FALSE !== 0
2178 }
2179 catch (PDOException $e)
2180 {
3fb56626 2181 throw convertPDOException ($e);
5f054512 2182 }
8198f2c6
DO
2183}
2184
d0dadd80
DO
2185function usePreparedSelectBlade ($query, $args = array())
2186{
2187 global $dbxlink;
2188 $prepared = $dbxlink->prepare ($query);
2189 if (!$prepared->execute ($args))
2190 return FALSE;
2191 return $prepared;
2192}
2193
39eadd27
DO
2194// Prepare and execute the statement with parameters, then return number of
2195// rows affected (or FALSE in case of an error).
2196function usePreparedExecuteBlade ($query, $args = array())
2197{
2198 global $dbxlink;
3fb56626
DO
2199 try
2200 {
2201 if (!$prepared = $dbxlink->prepare ($query))
2202 return FALSE;
2203 if (!$prepared->execute ($args))
2204 return FALSE;
2205 return $prepared->rowCount();
2206 }
2207 catch (PDOException $e)
2208 {
2209 throw convertPDOException ($e);
2210 }
39eadd27
DO
2211}
2212
9c0b0016
DO
2213function loadConfigCache ()
2214{
c9066b1c 2215 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
3540d15c 2216 $cache = array();
c9066b1c 2217 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3540d15c 2218 $cache[$row['varname']] = $row;
3540d15c
DY
2219 return $cache;
2220}
2221
2222function loadUserConfigCache ($username = NULL)
2223{
2224 if (!strlen ($username))
2225 throw new InvalidArgException ('$username', $username);
c9066b1c 2226 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
9c0b0016
DO
2227 $cache = array();
2228 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2229 $cache[$row['varname']] = $row;
9c0b0016
DO
2230 return $cache;
2231}
2232
3540d15c
DY
2233function deleteUserConfigVar ($username = NULL, $varname = NULL)
2234{
c9066b1c 2235 usePreparedDeleteBlade ('UserConfig', array ('varname' => $varname, 'user' => $username));
3540d15c
DY
2236}
2237
3540d15c
DY
2238function storeUserConfigVar ($username = NULL, $varname = NULL, $varvalue = NULL)
2239{
3540d15c
DY
2240 if (!strlen ($username))
2241 throw new InvalidArgException ('$username', $username);
2242 if (!strlen ($varname))
2243 throw new InvalidArgException ('$varname', $varname);
2244 if ($varvalue === NULL)
2245 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2246 return usePreparedExecuteBlade
2247 (
2248 'REPLACE UserConfig SET varvalue=?, varname=?, user=?',
2249 array ($varvalue, $varname, $username)
e5925cee 2250 );
3540d15c
DY
2251}
2252
9c0b0016
DO
2253// setConfigVar() is expected to perform all necessary filtering
2254function storeConfigVar ($varname = NULL, $varvalue = NULL)
2255{
c5f84f48
DY
2256 if ($varvalue === NULL)
2257 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2258 return usePreparedExecuteBlade
2259 (
2260 'UPDATE Config SET varvalue=? WHERE varname=?',
2261 array ($varvalue, $varname)
2262 );
9c0b0016
DO
2263}
2264
da04825a
DO
2265// Return an array of virtual services. For each of them list real server pools
2266// with their load balancers and other stats.
62a1dcb5
DO
2267function getSLBSummary ()
2268{
c9066b1c
DO
2269 $result = usePreparedSelectBlade
2270 (
2271 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
6fec9f39 2272 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2273 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2274 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2275 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
c9066b1c
DO
2276 'group by vs.id, object_id order by vs.vip, object_id'
2277 );
c3bdc503
DO
2278 $ret = array();
2279 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2280 {
4cadac8f 2281 $vsid = $row['vsid'];
da04825a 2282 $object_id = $row['object_id'];
4cadac8f
DO
2283 if (!isset ($ret[$vsid]))
2284 {
2285 $ret[$vsid] = array();
13bffb29 2286 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2287 $ret[$vsid][$cname] = $row[$cname];
da04825a 2288 $ret[$vsid]['lblist'] = array();
4cadac8f 2289 }
6fec9f39
DO
2290 // There's only one assigned RS pool possible for each LB-VS combination.
2291 $ret[$vsid]['lblist'][$row['object_id']] = array
2292 (
2293 'id' => $row['rspool_id'],
2294 'size' => $row['rscount'],
2295 'name' => $row['pool_name']
2296 );
c3bdc503
DO
2297 }
2298 return $ret;
62a1dcb5
DO
2299}
2300
7e7a8387 2301function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2302{
a5c589d2 2303 return usePreparedExecuteBlade
ca461127 2304 (
a5c589d2 2305 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
ca461127
DO
2306 array
2307 (
a5c589d2
DO
2308 $rsip,
2309 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2310 $pool_id,
2311 $inservice == 'yes' ? 'yes' : 'no',
2312 !strlen ($rsconfig) ? NULL : $rsconfig
3241551e
DO
2313 )
2314 );
2315}
2316
c63a8d6e 2317function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21 2318{
c5f84f48
DY
2319 if (!strlen ($vip))
2320 throw new InvalidArgException ('$vip', $vip);
2321 if ($vport <= 0)
2322 throw new InvalidArgException ('$vport', $vport);
2323 if (!strlen ($proto))
2324 throw new InvalidArgException ('$proto', $proto);
a5c589d2 2325 if (FALSE === usePreparedExecuteBlade
d6517a21 2326 (
a5c589d2 2327 'INSERT INTO IPv4VS (vip, vport, proto, name, vsconfig, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?, ?)',
d6517a21
DO
2328 array
2329 (
a5c589d2
DO
2330 $vip,
2331 $vport,
2332 $proto,
2333 !strlen ($name) ? NULL : $name,
2334 !strlen ($vsconfig) ? NULL : $vsconfig,
2335 !strlen ($rsconfig) ? NULL : $rsconfig,
d6517a21 2336 )
c63a8d6e
DO
2337 ))
2338 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2339 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2340}
2341
c1ca768c 2342function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2343{
c9066b1c 2344 return usePreparedInsertBlade
3241551e 2345 (
706ce117 2346 'IPv4LB',
3241551e
DO
2347 array
2348 (
2349 'object_id' => $object_id,
2350 'rspool_id' => $pool_id,
c1ca768c 2351 'vs_id' => $vs_id,
c9066b1c
DO
2352 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2353 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
3241551e 2354 )
ca461127
DO
2355 );
2356}
2357
fb1c4a54
DO
2358function commitDeleteRS ($id = 0)
2359{
c9066b1c 2360 return usePreparedDeleteBlade ('IPv4RS', array ('id' => $id));
fb1c4a54
DO
2361}
2362
d6517a21
DO
2363function commitDeleteVS ($id = 0)
2364{
6657739e 2365 releaseFiles ('ipv4vs', $id);
0da3bf00 2366 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2367}
2368
c1ca768c 2369function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e 2370{
c9066b1c 2371 return usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id, 'rspool_id' => $pool_id, 'vs_id' => $vs_id));
3241551e
DO
2372}
2373
fb1c4a54
DO
2374function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2375{
fb1c4a54 2376 if (long2ip (ip2long ($rsip)) !== $rsip)
c5f84f48 2377 throw new InvalidArgException ('$rsip', $rsip);
a5c589d2
DO
2378 return usePreparedExecuteBlade
2379 (
2380 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2381 array
2382 (
2383 $rsip,
2384 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2385 !strlen ($rsconfig) ? NULL : $rsconfig,
2386 $rsid,
2387 )
2388 );
fb1c4a54
DO
2389}
2390
c1ca768c 2391function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2392{
a5c589d2
DO
2393 return usePreparedExecuteBlade
2394 (
2395 'UPDATE IPv4LB SET vsconfig=?, rsconfig=? WHERE object_id=? AND rspool_id=? AND vs_id=?',
2396 array
2397 (
2398 !strlen ($vsconfig) ? NULL : $vsconfig,
2399 !strlen ($rsconfig) ? NULL : $rsconfig,
2400 $object_id,
2401 $pool_id,
2402 $vs_id,
2403 )
2404 );
3241551e
DO
2405}
2406
d6517a21
DO
2407function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2408{
c5f84f48
DY
2409 if (!strlen ($vip))
2410 throw new InvalidArgException ('$vip', $vip);
2411 if ($vport <= 0)
2412 throw new InvalidArgException ('$vport', $vport);
2413 if (!strlen ($proto))
2414 throw new InvalidArgException ('$proto', $proto);
a5c589d2
DO
2415 return usePreparedExecuteBlade
2416 (
2417 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2418 array
2419 (
2420 $vip,
2421 $vport,
2422 $proto,
2423 !strlen ($name) ? NULL : $name,
2424 !strlen ($vsconfig) ? NULL : $vsconfig,
2425 !strlen ($rsconfig) ? NULL : $rsconfig,
2426 $vsid,
2427 )
2428 );
d6517a21
DO
2429}
2430
5a1680d2
DO
2431function loadThumbCache ($rack_id = 0)
2432{
5a1680d2 2433 $ret = NULL;
c9066b1c 2434 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
5a1680d2
DO
2435 $row = $result->fetch (PDO::FETCH_ASSOC);
2436 if ($row)
2437 $ret = base64_decode ($row['thumb_data']);
5a1680d2
DO
2438 return $ret;
2439}
2440
2441function saveThumbCache ($rack_id = 0, $cache = NULL)
2442{
178fda20 2443 if ($cache == NULL)
c5f84f48 2444 throw new InvalidArgException ('$cache', $cache);
a5c589d2 2445 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=? WHERE id=?', array (base64_encode ($cache), $rack_id));
5a1680d2 2446}
9a81d416 2447
c7fe33be
DO
2448function resetThumbCache ($rack_id = 0)
2449{
a5c589d2 2450 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=NULL WHERE id=?', array ($rack_id));
c7fe33be
DO
2451}
2452
748805bf 2453// Return the list of attached RS pools for the given object. As long as we have
706ce117 2454// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2455// by vs_id, because there will be only one RS pool listed for each VS of the
2456// current object.
78e7b769
DO
2457function getRSPoolsForObject ($object_id = 0)
2458{
c9066b1c
DO
2459 $result = usePreparedSelectBlade
2460 (
2461 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2462 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2463 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2464 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2465 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
c9066b1c
DO
2466 'where lb.object_id = ? ' .
2467 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2468 array ($object_id)
2469 );
748805bf 2470 $ret = array ();
78e7b769 2471 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2472 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2473 $ret[$row['vs_id']][$cname] = $row[$cname];
748805bf 2474 return $ret;
78e7b769
DO
2475}
2476
c63a8d6e 2477function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2478{
59a83bd8 2479 if (!strlen ($name))
c5f84f48 2480 throw new InvalidArgException ('$name', $name);
c9066b1c 2481 if (!usePreparedInsertBlade
5ad76f01 2482 (
706ce117 2483 'IPv4RSPool',
5ad76f01
DO
2484 array
2485 (
c9066b1c
DO
2486 'name' => (!strlen ($name) ? NULL : $name),
2487 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2488 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
5ad76f01 2489 )
c63a8d6e
DO
2490 ))
2491 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2492 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2493}
2494
2495function commitDeleteRSPool ($pool_id = 0)
2496{
6657739e 2497 releaseFiles ('ipv4rspool', $pool_id);
c9066b1c 2498 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2499}
2500
2501function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2502{
a5c589d2
DO
2503 return usePreparedExecuteBlade
2504 (
2505 'UPDATE IPv4RSPool SET name=?, vsconfig=?, rsconfig=? WHERE id=?',
2506 array
2507 (
2508 !strlen ($name) ? NULL : $name,
2509 !strlen ($vsconfig) ? NULL : $vsconfig,
2510 !strlen ($rsconfig) ? NULL : $rsconfig,
2511 $pool_id,
2512 )
2513 );
5ad76f01
DO
2514}
2515
8253d9f0
DO
2516function getRSList ()
2517{
c9066b1c
DO
2518 $result = usePreparedSelectBlade
2519 (
2520 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2521 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2522 );
4b0932b6 2523 $ret = array ();
8253d9f0 2524 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2525 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6 2526 $ret[$row['id']][$cname] = $row[$cname];
4b0932b6
DO
2527 return $ret;
2528}
2529
2530// Return the list of all currently configured load balancers with their pool count.
2531function getLBList ()
2532{
c9066b1c
DO
2533 $result = usePreparedSelectBlade
2534 (
2535 "select object_id, count(rspool_id) as poolcount " .
2536 "from IPv4LB group by object_id order by object_id"
2537 );
4b0932b6
DO
2538 $ret = array ();
2539 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2540 $ret[$row['object_id']] = $row['poolcount'];
4b0932b6 2541 return $ret;
8253d9f0
DO
2542}
2543
178fda20 2544// For the given object return: its vsconfig/rsconfig; the list of RS pools
9e677cbd
DO
2545// attached (each with vsconfig/rsconfig in turn), each with the list of
2546// virtual services terminating the pool. Each pool also lists all real
2547// servers with rsconfig.
2987fc1f 2548function getSLBConfig ($object_id)
9e677cbd 2549{
9e677cbd 2550 $ret = array();
e34dac4f
DO
2551 $result = usePreparedSelectBlade
2552 (
2553 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
d91f08f3
DO
2554 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2555 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2556 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2557 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2558 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2559 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2560 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
e34dac4f
DO
2561 "where lb.object_id = ? and rs.inservice = 'yes' " .
2562 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2563 array ($object_id)
2564 );
9e677cbd
DO
2565 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2566 {
d91f08f3
DO
2567 $vs_id = $row['vs_id'];
2568 if (!isset ($ret[$vs_id]))
2569 {
2570 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)
2571 $ret[$vs_id][$c] = $row[$c];
2572 $ret[$vs_id]['rslist'] = array();
2573 }
2574 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2575 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd 2576 }
9e677cbd
DO
2577 return $ret;
2578}
1f7d18fa
DO
2579
2580function commitSetInService ($rs_id = 0, $inservice = '')
2581{
c5f84f48
DY
2582 if (!strlen ($inservice))
2583 throw new InvalidArgException ('$inservice', $inservice);
a5c589d2 2584 return usePreparedExecuteBlade ('UPDATE IPv4RS SET inservice=? WHERE id=?', array ($inservice, $rs_id));
1f7d18fa
DO
2585}
2586
ad0e4754
DO
2587function executeAutoPorts ($object_id = 0, $type_id = 0)
2588{
c5f84f48
DY
2589 if ($object_id == 0)
2590 throw new InvalidArgException ('$object_id', $object_id);
2591 if ($type_id == 0)
2592 throw new InvalidArgException ('$type_id', $type_id);
f3f0161f 2593 $ret = TRUE;
118e4c38 2594 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2595 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2596 return $ret;
ad0e4754
DO
2597}
2598
6e49bd1f 2599// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2600// generated/deducted later at higher levels.
aab37bc0 2601// Result is a chain: randomly indexed taginfo list.
f9bc186f 2602function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2603{
a6e8d544 2604 $ret = array();
e34dac4f
DO
2605 $result = usePreparedSelectBlade
2606 (
2607 "select tt.id, tag from " .
edf0993c 2608 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
e34dac4f
DO
2609 "where entity_realm = ? and entity_id = ? " .
2610 "order by tt.tag",
2611 array ($entity_realm, $entity_id)
2612 );
5967b83d 2613 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2614 $ret[$row['id']] = $row;
aab37bc0 2615 return getExplicitTagsOnly ($ret);
5967b83d
DO
2616}
2617
351c0966 2618// Return a tag chain with all DB tags on it.
5967b83d
DO
2619function getTagList ()
2620{
20c901a7 2621 $ret = array();
e34dac4f
DO
2622 $result = usePreparedSelectBlade
2623 (
2624 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2625 "from TagTree left join TagStorage on id = tag_id " .
e34dac4f
DO
2626 "group by id, entity_realm order by tag"
2627 );
2628 // Collation index. The resulting rows are ordered according to default collation,
fb7a4967 2629 // which is utf8_general_ci for UTF-8.
e34dac4f 2630 $ci = 0;
5967b83d 2631 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2632 {
7cc02fc1 2633 if (!isset ($ret[$row['id']]))
20c901a7 2634 $ret[$row['id']] = array
5b7bd02e
DO
2635 (
2636 'id' => $row['id'],
2637 'tag' => $row['tag'],
fb7a4967 2638 'ci' => $ci++,
5b7bd02e 2639 'parent_id' => $row['parent_id'],
9e51318b 2640 'refcnt' => array ('total' => 0)
5b7bd02e
DO
2641 );
2642 if ($row['realm'])
9e51318b 2643 {
20c901a7 2644 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
9e51318b
DO
2645 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2646 }
5b7bd02e 2647 }
20c901a7 2648 return $ret;
5967b83d
DO
2649}
2650
fe7044ad
DO
2651function commitCreateTag ($tagname = '', $parent_id = 0)
2652{
6cfedb71
DO
2653 if ($tagname == '')
2654 throw new InvalidArgException ('tagname', $tagname);
2655 return usePreparedInsertBlade
fe7044ad
DO
2656 (
2657 'TagTree',
2658 array
2659 (
e34dac4f 2660 'tag' => $tagname,
fe7044ad
DO
2661 'parent_id' => $parent_id
2662 )
2663 );
fe7044ad
DO
2664}
2665
2666function commitDestroyTag ($tagid = 0)
2667{
e34dac4f 2668 if (usePreparedDeleteBlade ('TagTree', array ('id' => $tagid)))
fe7044ad 2669 return '';
e34dac4f 2670 return 'usePreparedDeleteBlade() failed in ' . __FUNCTION__;
fe7044ad 2671}
f9bc186f 2672
49fb1027 2673function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2674{
a5c589d2
DO
2675 return usePreparedExecuteBlade
2676 (
2677 'UPDATE TagTree SET tag=?, parent_id=? WHERE id=?',
2678 array
2679 (
2680 $tag_name,
2681 $parent_id == 0 ? NULL : $parent_id,
2682 $tag_id,
2683 )
2684 );
f9bc186f
DO
2685}
2686
01b6b4d6
DO
2687// Drop the whole chain stored.
2688function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af 2689{
e34dac4f 2690 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
aedf18af
DO
2691}
2692
01b6b4d6 2693// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
29c3a4d8
DO
2694// FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2695// but not now.
01b6b4d6
DO
2696function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2697{
e34dac4f 2698 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
01b6b4d6
DO
2699}
2700
351c0966 2701// Push a record into TagStorage unconditionally.
3355ca56 2702function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2703{
e34dac4f 2704 if (!in_array ($realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
3355ca56 2705 return FALSE;
e34dac4f 2706 return usePreparedInsertBlade
eb6ea26f
DO
2707 (
2708 'TagStorage',
2709 array
2710 (
e34dac4f 2711 'entity_realm' => $realm,
120e9ddd 2712 'entity_id' => $entity_id,
eb6ea26f
DO
2713 'tag_id' => $tag_id,
2714 )
2715 );
2716}
2717
351c0966 2718// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
2719// on the implicit list already). Then remove any other records, which
2720// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
2721// that both the tag base is still minimal and all requested tags appear on
2722// the resulting tag chain.
abef7149
DO
2723// Return TRUE, if any changes were committed.
2724function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2725{
2726 // Put the current explicit sub-chain into a buffer and merge all tags from
2727 // the extra chain, which aren't there yet.
2728 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2729 foreach ($extrachain as $extratag)
2730 if (!tagOnChain ($extratag, $newchain))
2731 $newchain[] = $extratag;
2732 // Then minimize the working buffer and check if it differs from the original
2733 // chain we started with. If it is so, save the work and signal the upper layer.
2734 $newchain = getExplicitTagsOnly ($newchain);
2735 if (tagChainCmp ($oldchain, $newchain))
2736 {
01b6b4d6 2737 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
2738 foreach ($newchain as $taginfo)
2739 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2740 return TRUE;
2741 }
2742 return FALSE;
351c0966
DO
2743}
2744
2745// Presume, that the target record has no tags attached.
2746function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2747{
2748 if (!count ($tagidlist))
c63a8d6e
DO
2749 return '';
2750 if (!$last_insert_id)
2751 $last_insert_id = lastInsertID();
2752 $errcount = 0;
abef7149 2753 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 2754 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
2755 $errcount++;
2756 if (!$errcount)
2757 return '';
2758 else
2759 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2760}
2761
42023f03
DO
2762function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2763{
2764 // $range is in x.x.x.x/x format, split into ip/mask vars
2765 $rangeArray = explode('/', $range);
2766 if (count ($rangeArray) != 2)
2767 return "Invalid IPv4 prefix '${range}'";
2768 $ip = $rangeArray[0];
2769 $mask = $rangeArray[1];
2770
59a83bd8 2771 if (!strlen ($ip) or !strlen ($mask))
42023f03
DO
2772 return "Invalid IPv4 prefix '${range}'";
2773 $ipL = ip2long($ip);
2774 $maskL = ip2long($mask);
2775 if ($ipL == -1 || $ipL === FALSE)
2776 return 'Bad IPv4 address';
2777 if ($mask < 32 && $mask > 0)
2778 $maskL = $mask;
2779 else
2780 {
2781 $maskB = decbin($maskL);
2782 if (strlen($maskB)!=32)
2783 return 'Invalid netmask';
2784 $ones=0;
2785 $zeroes=FALSE;
2786 foreach( str_split ($maskB) as $digit)
2787 {
2788 if ($digit == '0')
2789 $zeroes = TRUE;
2790 if ($digit == '1')
2791 {
2792 $ones++;
2793 if ($zeroes == TRUE)
2794 return 'Invalid netmask';
2795 }
2796 }
2797 $maskL = $ones;
2798 }
2799 $binmask = binMaskFromDec($maskL);
2800 $ipL = $ipL & $binmask;
357eb2ea 2801 $result = usePreparedInsertBlade
42023f03 2802 (
706ce117 2803 'IPv4Network',
42023f03
DO
2804 array
2805 (
2806 'ip' => sprintf ('%u', $ipL),
357eb2ea
DO
2807 'mask' => $maskL,
2808 'name' => $name
42023f03
DO
2809 )
2810 );
e782fca4
DO
2811 if ($result != TRUE)
2812 return "Could not add ${range} (already exists?).";
42023f03
DO
2813
2814 if ($is_bcast and $maskL < 31)
2815 {
2816 $network_addr = long2ip ($ipL);
2817 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2818 updateAddress ($network_addr, 'network', 'yes');
2819 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2820 }
351c0966 2821 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
2822}
2823
706ce117 2824// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
2825function destroyIPv4Prefix ($id = 0)
2826{
6657739e 2827 releaseFiles ('ipv4net', $id);
e34dac4f 2828 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
42023f03 2829 return __FUNCTION__ . ': SQL query #1 failed';
0da3bf00 2830 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
2831 return __FUNCTION__ . ': SQL query #2 failed';
2832 return '';
2833}
2834
ebae41b3
DO
2835function loadScript ($name)
2836{
e34dac4f 2837 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
ebae41b3 2838 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
2839 if ($row !== FALSE)
2840 return $row[0];
2841 else
2842 return NULL;
ebae41b3
DO
2843}
2844
178fda20 2845function saveScript ($name = '', $text)
ebae41b3 2846{
59a83bd8 2847 if (!strlen ($name))
c5f84f48 2848 throw new InvalidArgException ('$name', $name);
4a6a28f1 2849 // delete regardless of existence
e34dac4f
DO
2850 usePreparedDeleteBlade ('Script', array ('script_name' => $name));
2851 return usePreparedInsertBlade
ebae41b3
DO
2852 (
2853 'Script',
2854 array
2855 (
e34dac4f
DO
2856 'script_name' => $name,
2857 'script_text' => $text,
ebae41b3
DO
2858 )
2859 );
2860}
2861
d983f70a
DO
2862function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2863{
2864 if (NULL === getIPv4AddressNetworkId ($localip))
2865 return "$localip: Non existant ip";
0929db7f 2866 if (NULL === getIPv4AddressNetworkId ($remoteip))
d983f70a
DO
2867 return "$remoteip: Non existant ip";
2868 if ( ($localport <= 0) or ($localport >= 65536) )
2869 return "$localport: invaild port";
2870 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
2871 return "$remoteport: invaild port";
2872
a5c589d2 2873 $result = usePreparedExecuteBlade
d983f70a 2874 (
a5c589d2
DO
2875 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
2876 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
d983f70a
DO
2877 array
2878 (
a5c589d2
DO
2879 $object_id,
2880 $localip,
2881 $remoteip,
2882 $localport,
2883 $remoteport,
2884 $proto,
2885 $description,
d983f70a
DO
2886 )
2887 );
a5c589d2 2888 return $result !== FALSE ? '' : (__FUNCTION__ . '(): failed to insert the rule');
d983f70a
DO
2889}
2890
2891function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
2892{
a5c589d2
DO
2893 return usePreparedExecuteBlade
2894 (
2895 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
2896 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
2897 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2898 );
d983f70a
DO
2899}
2900
2901function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2902{
a5c589d2
DO
2903 return usePreparedExecuteBlade
2904 (
2905 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
2906 'AND localport=? AND remoteport=? AND proto=?',
2907 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2908 );
d983f70a
DO
2909}
2910
2911function getNATv4ForObject ($object_id)
2912{
2913 $ret = array();
2914 $ret['out'] = array();
2915 $ret['in'] = array();
e34dac4f
DO
2916 $result = usePreparedSelectBlade
2917 (
d983f70a
DO
2918 "select ".
2919 "proto, ".
2920 "INET_NTOA(localip) as localip, ".
2921 "localport, ".
2922 "INET_NTOA(remoteip) as remoteip, ".
2923 "remoteport, ".
2924 "ipa1.name as local_addr_name, " .
2925 "ipa2.name as remote_addr_name, " .
2926 "description ".
706ce117
DO
2927 "from IPv4NAT ".
2928 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
2929 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
e34dac4f
DO
2930 "where object_id=? ".
2931 "order by localip, localport, proto, remoteip, remoteport",
2932 array ($object_id)
2933 );
d983f70a
DO
2934 $count=0;
2935 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2936 {
2937 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
2938 $ret['out'][$count][$cname] = $row[$cname];
2939 $count++;
2940 }
d983f70a
DO
2941 unset ($result);
2942
e34dac4f
DO
2943 $result = usePreparedSelectBlade
2944 (
d983f70a
DO
2945 "select ".
2946 "proto, ".
2947 "INET_NTOA(localip) as localip, ".
2948 "localport, ".
2949 "INET_NTOA(remoteip) as remoteip, ".
2950 "remoteport, ".
706ce117 2951 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
2952 "RackObject.name as object_name, ".
2953 "description ".
706ce117 2954 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
e34dac4f
DO
2955 "where IPv4Allocation.object_id=? ".
2956 "order by remoteip, remoteport, proto, localip, localport",
2957 array ($object_id)
2958 );
d983f70a
DO
2959 $count=0;
2960 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2961 {
2962 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
2963 $ret['in'][$count][$cname] = $row[$cname];
2964 $count++;
2965 }
d983f70a
DO
2966 return $ret;
2967}
2968
178fda20 2969// Return a list of files, which are not linked to the specified record. This list
121496b6 2970// will be used by printSelect().
e1ae3fb4
AD
2971function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
2972{
e34dac4f
DO
2973 $query = usePreparedSelectBlade
2974 (
121496b6 2975 'SELECT id, name FROM File ' .
e1ae3fb4 2976 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
e34dac4f
DO
2977 'ORDER BY name, id',
2978 array ($entity_type, $entity_id)
2979 );
e1ae3fb4 2980 $ret=array();
e1ae3fb4 2981 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 2982 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
2983 return $ret;
2984}
2985
6df2025d
DO
2986// FIXME: return a standard cell list, so upper layer can iterate over
2987// it conveniently.
e1ae3fb4
AD
2988function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
2989{
e34dac4f
DO
2990 $query = usePreparedSelectBlade
2991 (
e1ae3fb4
AD
2992 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
2993 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
e34dac4f
DO
2994 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
2995 array ($entity_type, $entity_id)
2996 );
e1ae3fb4
AD
2997 $ret = array();
2998 while ($row = $query->fetch (PDO::FETCH_ASSOC))
2999 $ret[$row['file_id']] = array (
b3567368 3000 'id' => $row['file_id'],
e1ae3fb4
AD
3001 'link_id' => $row['link_id'],
3002 'name' => $row['name'],
3003 'type' => $row['type'],
3004 'size' => $row['size'],
3005 'ctime' => $row['ctime'],
3006 'mtime' => $row['mtime'],
3007 'atime' => $row['atime'],
3008 'comment' => $row['comment'],
3009 );
3010 return $ret;
3011}
3012
3013function getFile ($file_id = 0)
3014{
6cfedb71
DO
3015 $query = usePreparedSelectBlade
3016 (
3017 'SELECT id, name, type, size, ctime, mtime, atime, contents, comment ' .
3018 'FROM File WHERE id = ?',
3019 array ($file_id)
3020 );
e1ae3fb4
AD
3021 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3022 {
0cc24e9a 3023 showWarning ('Query succeeded, but returned no data', __FUNCTION__);
e1ae3fb4
AD
3024 $ret = NULL;
3025 }
3026 else
3027 {
3028 $ret = array();
3029 $ret['id'] = $row['id'];
3030 $ret['name'] = $row['name'];
3031 $ret['type'] = $row['type'];
3032 $ret['size'] = $row['size'];
3033 $ret['ctime'] = $row['ctime'];
3034 $ret['mtime'] = $row['mtime'];
3035 $ret['atime'] = $row['atime'];
3036 $ret['contents'] = $row['contents'];
3037 $ret['comment'] = $row['comment'];
bed9cd76 3038 $query->closeCursor();
e1ae3fb4 3039
deb3da1b 3040 // Someone accessed this file, update atime
6cfedb71 3041 usePreparedExecuteBlade ('UPDATE File SET atime = ? WHERE id = ?', array (date ('YmdHis'), $file_id));
e1ae3fb4 3042 }
e1ae3fb4
AD
3043 return $ret;
3044}
3045
e1ae3fb4
AD
3046function getFileLinks ($file_id = 0)
3047{
6cfedb71
DO
3048 $query = usePreparedSelectBlade
3049 (
3050 'SELECT id, file_id, entity_type, entity_id FROM FileLink ' .
3051 'WHERE file_id = ? ORDER BY entity_type, entity_id',
3052 array ($file_id)
3053 );
da3302ab 3054 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3055 $ret = array();
da3302ab 3056 foreach ($rows as $row)
e1ae3fb4
AD
3057 {
3058 // get info of the parent
3059 switch ($row['entity_type'])
3060 {
3061 case 'ipv4net':
3062 $page = 'ipv4net';
3063 $id_name = 'id';
d724d290 3064 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3065 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3066 break;
3067 case 'ipv4rspool':
3854af78 3068 $page = 'ipv4rspool';
e1ae3fb4 3069 $id_name = 'pool_id';
a6e91ac2 3070 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3071 $name = $parent['name'];
3072 break;
3073 case 'ipv4vs':
3074 $page = 'ipv4vs';
3075 $id_name = 'vs_id';
7c38462f 3076 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3077 $name = $parent['name'];
3078 break;
3079 case 'object':
3080 $page = 'object';
3081 $id_name = 'object_id';
6297d584 3082 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
7ddbcf59 3083 $name = $parent['dname'];
e1ae3fb4
AD
3084 break;
3085 case 'rack':
3086 $page = 'rack';
3087 $id_name = 'rack_id';
61a1d996 3088 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3089 $name = $parent['name'];
3090 break;
3091 case 'user':
3092 $page = 'user';
3093 $id_name = 'user_id';
0b2c74cb
DO
3094 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3095 $name = $parent['user_name'];
e1ae3fb4
AD
3096 break;
3097 }
3098
17d95c32 3099 // name needs to have some value for hrefs to work
59a83bd8 3100 if (!strlen ($name))
17d95c32
AD
3101 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3102
e1ae3fb4
AD
3103 $ret[$row['id']] = array(
3104 'page' => $page,
3105 'id_name' => $id_name,
3106 'entity_type' => $row['entity_type'],
3107 'entity_id' => $row['entity_id'],
3108 'name' => $name
3109 );
3110 }
3111 return $ret;
3112}
3113
0b97b8f0 3114function getFileStats ()
e1ae3fb4 3115{
e34dac4f 3116 $result = usePreparedSelectBlade ('SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type');
e1ae3fb4 3117 $ret = array();
e1ae3fb4
AD
3118 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3119 if ($row['count'] > 0)
0b97b8f0
DO
3120 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3121 unset ($result);
e1ae3fb4
AD
3122
3123 // Find number of files without any linkage
e34dac4f
DO
3124 $result = usePreparedSelectBlade
3125 (
e1ae3fb4
AD
3126 'SELECT COUNT(*) ' .
3127 'FROM File ' .
27b2ae0d 3128 'WHERE id NOT IN (SELECT file_id FROM FileLink)'
e34dac4f 3129 );
0b97b8f0
DO
3130 $ret["Unattached files"] = $result->fetchColumn ();
3131 unset ($result);
e1ae3fb4
AD
3132
3133 // Find total number of files
e34dac4f 3134 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM File');
0b97b8f0 3135 $ret["Total files"] = $result->fetchColumn ();
e1ae3fb4 3136
e1ae3fb4
AD
3137 return $ret;
3138}
3139
3140function commitAddFile ($name, $type, $size, $contents, $comment)
3141{
3142 $now = date('YmdHis');
3143
3144 global $dbxlink;
3145 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3146 $query->bindParam(1, $name);
3147 $query->bindParam(2, $type);
3148 $query->bindParam(3, $size);
3149 $query->bindParam(4, $now);
3150 $query->bindParam(5, $now);
3151 $query->bindParam(6, $now);
3152 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3153 $query->bindParam(8, $comment);
6cfedb71
DO
3154 try
3155 {
3156 return $query->execute();
3157 }
3158 catch (PDOException $e)
3159 {
3160 throw convertPDOException ($e);
3161 }
e1ae3fb4
AD
3162}
3163
4a2c6c6b 3164function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4 3165{
6cfedb71
DO
3166 return usePreparedExecuteBlade
3167 (
3168 'INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)',
3169 array ($file_id, $entity_type, $entity_id)
3170 );
e1ae3fb4
AD
3171}
3172
f8874cdb 3173function commitReplaceFile ($file_id = 0, $contents)
fd1fb420 3174{
fd1fb420 3175 global $dbxlink;
f8874cdb
DO
3176 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3177 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3178 $query->bindParam(2, $file_id);
fd1fb420 3179
6cfedb71
DO
3180 try
3181 {
3182 return $query->execute();
3183 }
3184 catch (PDOException $e)
3185 {
3186 throw convertPDOException ($e);
3187 }
fd1fb420
AD
3188}
3189
9db67d95 3190function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
e1ae3fb4 3191{
c5f84f48
DY
3192 if (!strlen ($new_name))
3193 throw new InvalidArgException ('$new_name', $new_name);
3194 if (!strlen ($new_type))
3195 throw new InvalidArgException ('$new_type', $new_type);
6cfedb71
DO
3196 return usePreparedExecuteBlade
3197 (
3198 'UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?',
3199 array ($new_name, $new_type, $new_comment, $file_id)
3200 );
e1ae3fb4
AD
3201}
3202
3203function commitUnlinkFile ($link_id)
3204{
e34dac4f 3205 if (usePreparedDeleteBlade ('FileLink', array ('id' => $link_id)) === FALSE)
9589714d 3206 return __FUNCTION__ . '(): query failed';
e1ae3fb4
AD
3207 return '';
3208}
3209
3210function commitDeleteFile ($file_id)
3211{
29c3a4d8 3212 destroyTagsForEntity ('file', $file_id);
e34dac4f 3213 if (usePreparedDeleteBlade ('File', array ('id' => $file_id)) === FALSE)
9589714d 3214 return __FUNCTION__ . '(): query failed';
e1ae3fb4
AD
3215 return '';
3216}
3217
4034ab9e
DO
3218function getChapterList ()
3219{
3220 $ret = array();
e34dac4f
DO
3221 $result = usePreparedSelectBlade
3222 (
3223 'SELECT id, sticky, name, count(chapter_id) as wordc ' .
3224 'FROM Chapter LEFT JOIN Dictionary ON Chapter.id = chapter_id ' .
3225 'GROUP BY id ORDER BY name'
3226 );
4034ab9e 3227 while ($row = $result->fetch (PDO::FETCH_ASSOC))
c4d0dc30 3228 $ret[$row['id']] = $row;
4034ab9e
DO
3229 return $ret;
3230}
3231
2d1e6b63 3232// Return file id by file name.
72d2a7ee
DO
3233function findFileByName ($filename)
3234{
6cfedb71 3235 $query = usePreparedSelectBlade ('SELECT id FROM File WHERE name = ?', array ($filename));
2d1e6b63 3236 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
72d2a7ee 3237 return $row['id'];
2d1e6b63
AD
3238
3239 return NULL;
72d2a7ee
DO
3240}
3241
9133d2c5
DO
3242function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3243{
3244 global $dbxlink;
3245 $dbxlink->beginTransaction();
e34dac4f
DO
3246 $result = usePreparedSelectBlade
3247 (
3248 'SELECT TIMESTAMPDIFF(SECOND, first_success, now()) AS success_age, ' .
3249 'TIMESTAMPDIFF(SECOND, last_retry, now()) AS retry_age, displayed_name, memberof ' .
3250 'FROM LDAPCache WHERE presented_username = ? AND successful_hash = ? ' .
3251 'HAVING success_age < ? FOR UPDATE',
3252 array ($form_username, $password_hash, $expiry)
3253 );
9133d2c5
DO
3254 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3255 {
3256 $row['memberof'] = unserialize (base64_decode ($row['memberof']));
3257 return $row;
3258 }
3259 return NULL;
3260}
3261
3262function releaseLDAPCache ()
3263{
3264 global $dbxlink;
3265 $dbxlink->commit();
3266}
3267
3268// This actually changes only last_retry.
3269function touchLDAPCacheRecord ($form_username)
3270{
a5c589d2 3271 return usePreparedExecuteBlade ('UPDATE LDAPCache SET last_retry=NOW() WHERE presented_username=?', array ($form_username));
9133d2c5
DO
3272}
3273
3274function replaceLDAPCacheRecord ($form_username, $password_hash, $dname, $memberof)
3275{
3276 deleteLDAPCacheRecord ($form_username);
e34dac4f 3277 usePreparedInsertBlade ('LDAPCache',
9133d2c5
DO
3278 array
3279 (
e34dac4f
DO
3280 'presented_username' => $form_username,
3281 'successful_hash' => $password_hash,
3282 'displayed_name' => $dname,
3283 'memberof' => base64_encode (serialize ($memberof)),
9133d2c5
DO
3284 )
3285 );
3286}
3287
3288function deleteLDAPCacheRecord ($form_username)
3289{
e34dac4f 3290 return usePreparedDeleteBlade ('LDAPCache', array ('presented_username' => $form_username));
9133d2c5
DO
3291}
3292
f3371850
DO
3293// Age all records older, than cache_expiry seconds, and all records made in future.
3294// Calling this function w/o argument purges the whole LDAP cache.
3295function discardLDAPCache ($maxage = 0)
ef44d4a3 3296{
a5c589d2 3297 return usePreparedExecuteBlade ('DELETE from LDAPCache WHERE TIMESTAMPDIFF(SECOND, first_success, NOW()) >= ? or NOW() < first_success', array ($maxage));
ef44d4a3
DO
3298}
3299
b82cce3f
DO
3300function getUserIDByUsername ($username)
3301{
e34dac4f 3302 $result = usePreparedSelectBlade ('SELECT user_id FROM UserAccount WHeRE user_name = ?', array ($username));
b82cce3f
DO
3303 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3304 return $row['user_id'];
3305 return NULL;
3306}
3307
029a14bc
DO
3308// Return TRUE, if the given address is assigned to a port of any object
3309// except the current object. Using this function as a constraint makes
3310// it possible to reuse L2 addresses within one object, yet keeping them
3311// universally unique on the other hand.
3312function alreadyUsedL2Address ($address, $my_object_id)
3313{
e34dac4f
DO
3314 $result = usePreparedSelectBlade
3315 (
3316 'SELECT COUNT(*) FROM Port WHERE BINARY l2address = ? AND object_id != ?',
3317 array ($address, $my_object_id)
3318 );
029a14bc
DO
3319 $row = $result->fetch (PDO::FETCH_NUM);
3320 return $row[0] != 0;
3321}
3322
2dfa1b73 3323function getPortInterfaceCompat()
3153a326 3324{
e34dac4f
DO
3325 $result = usePreparedSelectBlade
3326 (
3327 'SELECT iif_id, iif_name, oif_id, dict_value AS oif_name ' .
3153a326
DO
3328 'FROM PortInterfaceCompat INNER JOIN PortInnerInterface ON id = iif_id ' .
3329 'INNER JOIN Dictionary ON dict_key = oif_id ' .
e34dac4f
DO
3330 'ORDER BY iif_name, oif_name'
3331 );
2dfa1b73 3332 return $result->fetchAll (PDO::FETCH_ASSOC);
3153a326
DO
3333}
3334
3335// Return a set of options for a plain SELECT. These options include the current
3336// OIF of the given port and all OIFs of its permanent IIF.
3337function getExistingPortTypeOptions ($port_id)
3338{
e34dac4f
DO
3339 $result = usePreparedSelectBlade
3340 (
3341 'SELECT oif_id, dict_value AS oif_name ' .
3153a326 3342 'FROM PortInterfaceCompat INNER JOIN Dictionary ON oif_id = dict_key ' .
e34dac4f
DO
3343 'WHERE iif_id = (SELECT iif_id FROM Port WHERE id = ?) ' .
3344 'ORDER BY oif_name',
3345 array ($port_id)
3346 );
3153a326
DO
3347 $ret = array();
3348 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3349 $ret[$row['oif_id']] = $row['oif_name'];
3350 return $ret;
3351}
3352
2dfa1b73
DO
3353function getPortIIFOptions()
3354{
3355 $ret = array();
e34dac4f 3356 $result = usePreparedSelectBlade ('SELECT id, iif_name FROM PortInnerInterface ORDER BY iif_name');
2dfa1b73
DO
3357 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3358 $ret[$row['id']] = $row['iif_name'];
3359 return $ret;
3360}
3361
3362function commitSupplementPIC ($iif_id, $oif_id)
3363{
e34dac4f 3364 return usePreparedInsertBlade
2dfa1b73
DO
3365 (
3366 'PortInterfaceCompat',
3367 array ('iif_id' => $iif_id, 'oif_id' => $oif_id)
3368 );
3369}
3370
3371function commitReducePIC ($iif_id, $oif_id)
3372{
e34dac4f 3373 return usePreparedDeleteBlade ('PortInterfaceCompat', array ('iif_id' => $iif_id, 'oif_id' => $oif_id));
2dfa1b73
DO
3374}
3375
27ec21b2
DO
3376function getPortIIFStats ($args)
3377{
e34dac4f
DO
3378 $result = usePreparedSelectBlade
3379 (
3380 'SELECT dict_value AS title, COUNT(id) AS max, ' .
27ec21b2
DO
3381 'COUNT(reservation_comment) + ' .
3382 'SUM((SELECT COUNT(*) FROM Link WHERE id IN (porta, portb))) AS current ' .
3383 'FROM Port INNER JOIN Dictionary ON type = dict_key ' .
e34dac4f
DO
3384 'WHERE iif_id = ? GROUP BY type',
3385 array (current ($args))
3386 );
27ec21b2
DO
3387 return $result->fetchAll (PDO::FETCH_ASSOC);
3388}
3389
cd3775e9
DO
3390function getPortInfo ($port_id)
3391{
e34dac4f
DO
3392 $result = usePreparedSelectBlade
3393 (
3394 "SELECT object_id, name, iif_id, type AS oif_id, l2address, ".
cd3775e9 3395 "(SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, " .
b3247480 3396 "(SELECT COUNT(*) FROM Link WHERE id IN (porta, portb)) AS linked, " .
cd3775e9 3397 "(SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name " .
e34dac4f
DO
3398 "FROM Port WHERE id = ?",
3399 array ($port_id)
3400 );
cd3775e9
DO
3401 return $result->fetch (PDO::FETCH_ASSOC);
3402}
3403
87cca0c2 3404function getVLANDomainStats ()
8198f2c6 3405{
e34dac4f
DO
3406 $result = usePreparedSelectBlade
3407 (
3408 'SELECT id, description, ' .
8198f2c6 3409 '(SELECT COUNT(vlan_id) FROM VLANDescription WHERE domain_id = id) AS vlanc, ' .
b5ac48d0 3410 '(SELECT COUNT(ipv4net_id) FROM VLANIPv4 WHERE domain_id = id) AS ipv4netc, ' .
6affe3b9
DO
3411 '(SELECT COUNT(object_id) FROM VLANSwitch WHERE domain_id = id) AS switchc, ' .
3412 '(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
3413 'FROM VLANDomain ORDER BY description'
3414 );
8198f2c6
DO
3415 $ret = array();
3416 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3417 $ret[$row['id']] = $row;
3418 return $ret;
3419}
3420
e829e76b
DO
3421function getVLANDomainOptions()
3422{
e34dac4f 3423 $result = usePreparedSelectBlade ('SELECT id, description FROM VLANDomain ORDER BY description');
e829e76b
DO
3424 $ret = array();
3425 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3426 $ret[$row['id']] = $row['description'];
3427 return $ret;
3428}
3429
8877c14a 3430function getVLANDomain ($vdid)
8198f2c6 3431{
8877c14a
DO
3432 $result = usePreparedSelectBlade ('SELECT id, description FROM VLANDomain WHERE id = ?', array ($vdid));
3433 if (!$ret = $result->fetch (PDO::FETCH_ASSOC))
3434 throw new EntityNotFoundException ('VLAN domain', $vdid);
3435 unset ($result);
3436 $ret['vlanlist'] = getDomainVLANs ($vdid);
960ab00b
DO
3437 $ret['switchlist'] = array();
3438 $result = usePreparedSelectBlade
3439 (
3440 'SELECT object_id, template_id, last_errno, out_of_sync, ' .
3441 'TIMESTAMPDIFF(SECOND, last_change, NOW()) AS age_seconds ' .
3442 'FROM VLANSwitch WHERE domain_id = ? ORDER BY object_id',
3443 array ($vdid)
3444 );
3445 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3446 $ret['switchlist'][$row['object_id']] = $row;
8877c14a 3447 return $ret;
8198f2c6
DO
3448}
3449
3450function getDomainVLANs ($vdom_id)
3451{
e34dac4f 3452 $result = usePreparedSelectBlade
cbf78395 3453 (
94496ec7 3454 'SELECT vlan_id, vlan_type, vlan_descr, ' .
49e07479
DO
3455 '(SELECT COUNT(ipv4net_id) FROM VLANIPv4 WHERE domain_id = ? AND vlan_id = VD.vlan_id) AS netc, ' .
3456 '(SELECT COUNT(port_name) FROM VLANSwitch AS VS INNER JOIN PortAllowedVLAN AS PAV ' .
3457 'ON VS.object_id = PAV.object_id WHERE domain_id = ? AND PAV.vlan_id = VD.vlan_id GROUP BY PAV.vlan_id) AS portc ' .
94496ec7
DO
3458 'FROM VLANDescription AS VD ' .
3459 'WHERE domain_id = ? ' .
e34dac4f
DO
3460 'ORDER BY vlan_id',
3461 array ($vdom_id, $vdom_id, $vdom_id)
cbf78395 3462 );
8198f2c6 3463 $ret = array();
35ccd01d 3464 while ($row = $result->fetch (PDO::FETCH_ASSOC))
8198f2c6
DO
3465 $ret[$row['vlan_id']] = $row;
3466 return $ret;
3467}
3468
8198f2c6
DO
3469function commitReduceVLANDescription ($vdom_id, $vlan_id)
3470{
a822926c
DO
3471 return usePreparedDeleteBlade
3472 (
3473 'VLANDescription',
3474 array
3475 (
3476 'domain_id' => $vdom_id,
3477 'vlan_id' => $vlan_id,
3478 )
3479 );
8198f2c6
DO
3480}
3481
0dabdc53 3482function commitUpdateVLANDescription ($vdom_id, $vlan_id, $vlan_type, $vlan_descr)
8198f2c6 3483{
6cfedb71
DO
3484 return usePreparedExecuteBlade
3485 (
3486 'UPDATE VLANDescription SET vlan_descr=?, vlan_type=? WHERE domain_id=? AND vlan_id=?',
3487 array
3488 (
3489 !mb_strlen ($vlan_descr) ? NULL : $vlan_descr,
3490 $vlan_type,
3491 $vdom_id,