r3863 copy Huawei commit into trunk
[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.
995e7d5b 889function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_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,
e8acfc2d 909 mb_strlen ($port_reservation_comment) ? $port_reservation_comment : NULL,
a5c589d2
DO
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{
fc2e1602 1192 return 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 );
5222f192
DO
1197}
1198
bb0a44e9 1199// Return the id of the smallest IPv4 network containing the given IPv4 address
d65353ad
DO
1200// or NULL, if nothing was found. When finding the covering network for
1201// another network, it is important to filter out matched records with longer
1202// masks (they aren't going to be the right pick).
1203function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
e673ee24 1204{
3702d093
DO
1205// N.B. To perform the same for IPv6 address and networks, some pre-requisites
1206// are necessary and a different query. IPv6 addresses are 128 bit long, which
1207// is too much for both PHP and MySQL data types. These values must be split
1208// into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1209// Then each network must have its 128-bit netmask split same way and either
1210// stored right in its record or JOINed from decoder and accessible as m_u32_0,
1211// m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1212// covering the given address would look as follows:
1213// $query = 'select id from IPv6Network as n where ' .
1214// "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1215// "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1216// "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1217// "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1218// "mask < ${masklen} " .
1219// 'order by mask desc limit 1';
1220
706ce117 1221 $query = 'select id from IPv4Network where ' .
650ef981 1222 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
298d2375 1223 "and mask < ? " .
bb0a44e9 1224 'order by mask desc limit 1';
298d2375 1225 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
bb0a44e9
DO
1226 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1227 return $row['id'];
e673ee24
DO
1228 return NULL;
1229}
1230
99ab184f 1231function updateIPv4Network_real ($id = 0, $name = '', $comment = '')
e673ee24 1232{
6cfedb71 1233 return usePreparedExecuteBlade ('UPDATE IPv4Network SET name = ?, comment = ? WHERE id = ?', array ($name, $comment, $id));
e673ee24
DO
1234}
1235
1236// This function is actually used not only to update, but also to create records,
1237// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1238// (MySQL 4.0 workaround).
b4c1ef87 1239function updateAddress ($ip = 0, $name = '', $reserved = 'no')
e673ee24 1240{
32832c0e 1241 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
e673ee24
DO
1242 // INSERT may appear not necessary.
1243 if ($name == '' and $reserved == 'no')
1244 return '';
32832c0e
DO
1245 $ret = usePreparedExecuteBlade
1246 (
1247 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1248 array ($name, $reserved, $ip)
1249 );
1250 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
e673ee24
DO
1251}
1252
e673ee24
DO
1253function updateBond ($ip='', $object_id=0, $name='', $type='')
1254{
32832c0e
DO
1255 return usePreparedExecuteBlade
1256 (
1257 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1258 array ($name, $type, $ip, $object_id)
1259 );
e673ee24
DO
1260}
1261
1262function unbindIpFromObject ($ip='', $object_id=0)
1263{
32832c0e
DO
1264 return usePreparedExecuteBlade
1265 (
1266 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1267 array ($ip, $object_id)
1268 );
e673ee24
DO
1269}
1270
ea5fc465
DO
1271function getIPv4PrefixSearchResult ($terms)
1272{
6df2025d
DO
1273 $byname = getSearchResultByField
1274 (
1275 'IPv4Network',
1276 array ('id'),
1277 'name',
1278 $terms,
1279 'ip'
1280 );
ea5fc465 1281 $ret = array();
6df2025d
DO
1282 foreach ($byname as $row)
1283 $ret[] = spotEntity ('ipv4net', $row['id']);
ea5fc465
DO
1284 return $ret;
1285}
1286
1287function getIPv4AddressSearchResult ($terms)
1288{
706ce117 1289 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
ea5fc465 1290 $or = '';
a685e6d7 1291 $qparams = array();
ea5fc465
DO
1292 foreach (explode (' ', $terms) as $term)
1293 {
a685e6d7 1294 $query .= $or . "name like ?";
ea5fc465 1295 $or = ' or ';
a685e6d7 1296 $qparams[] = "%${term}%";
ea5fc465 1297 }
a685e6d7 1298 $result = usePreparedSelectBlade ($query, $qparams);
ea5fc465
DO
1299 $ret = array();
1300 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1301 $ret[] = $row;
1302 return $ret;
1303}
1304
05411ccd
DO
1305function getIPv4RSPoolSearchResult ($terms)
1306{
6cd32e3c
DO
1307 $byname = getSearchResultByField
1308 (
1309 'IPv4RSPool',
1310 array ('id'),
1311 'name',
1312 $terms,
1313 'name'
1314 );
05411ccd 1315 $ret = array();
6cd32e3c
DO
1316 foreach ($byname as $row)
1317 $ret[] = spotEntity ('ipv4rspool', $row['id']);
05411ccd
DO
1318 return $ret;
1319}
1320
1321function getIPv4VServiceSearchResult ($terms)
1322{
6df2025d
DO
1323 $byname = getSearchResultByField
1324 (
1325 'IPv4VS',
1326 array ('id'),
1327 'name',
1328 $terms,
1329 'vip'
1330 );
05411ccd 1331 $ret = array();
6df2025d
DO
1332 foreach ($byname as $row)
1333 $ret[] = spotEntity ('ipv4vs', $row['id']);
05411ccd
DO
1334 return $ret;
1335}
1336
6a88e734
DO
1337function getAccountSearchResult ($terms)
1338{
ea62d9dc 1339 $byUsername = getSearchResultByField
6a88e734
DO
1340 (
1341 'UserAccount',
1342 array ('user_id', 'user_name', 'user_realname'),
1343 'user_name',
1344 $terms,
1345 'user_name'
1346 );
ea62d9dc
DO
1347 $byRealname = getSearchResultByField
1348 (
1349 'UserAccount',
1350 array ('user_id', 'user_name', 'user_realname'),
1351 'user_realname',
1352 $terms,
1353 'user_name'
1354 );
1355 // Filter out dupes.
1356 foreach ($byUsername as $res1)
1357 foreach (array_keys ($byRealname) as $key2)
1358 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1359 {
1360 unset ($byRealname[$key2]);
1361 continue 2;
1362 }
573214e0
DO
1363 $ret = array_merge ($byUsername, $byRealname);
1364 // Set realm, so it's renderable.
1365 foreach (array_keys ($ret) as $key)
1366 $ret[$key]['realm'] = 'user';
1367 return $ret;
6a88e734
DO
1368}
1369
e1ae3fb4
AD
1370function getFileSearchResult ($terms)
1371{
e531b4d6 1372 $byName = getSearchResultByField
e1ae3fb4
AD
1373 (
1374 'File',
6df2025d 1375 array ('id'),
e1ae3fb4
AD
1376 'name',
1377 $terms,
1378 'name'
1379 );
1380 $byComment = getSearchResultByField
1381 (
1382 'File',
6df2025d 1383 array ('id'),
e1ae3fb4
AD
1384 'comment',
1385 $terms,
1386 'name'
1387 );
1388 // Filter out dupes.
e531b4d6 1389 foreach ($byName as $res1)
e1ae3fb4
AD
1390 foreach (array_keys ($byComment) as $key2)
1391 if ($res1['id'] == $byComment[$key2]['id'])
1392 {
1393 unset ($byComment[$key2]);
1394 continue 2;
1395 }
6df2025d 1396 $ret = array();
e531b4d6 1397 foreach (array_merge ($byName, $byComment) as $row)
6df2025d
DO
1398 $ret[] = spotEntity ('file', $row['id']);
1399 return $ret;
e1ae3fb4
AD
1400}
1401
e531b4d6
DO
1402function getRackSearchResult ($terms)
1403{
1404 $byName = getSearchResultByField
1405 (
1406 'Rack',
1407 array ('id'),
1408 'name',
1409 $terms,
1410 'name'
1411 );
1412 $byComment = getSearchResultByField
1413 (
1414 'Rack',
1415 array ('id'),
1416 'comment',
1417 $terms,
1418 'name'
1419 );
1420 // Filter out dupes.
1421 foreach ($byName as $res1)
1422 foreach (array_keys ($byComment) as $key2)
1423 if ($res1['id'] == $byComment[$key2]['id'])
1424 {
1425 unset ($byComment[$key2]);
1426 continue 2;
1427 }
1428 $ret = array();
1429 foreach (array_merge ($byName, $byComment) as $row)
1430 $ret[] = spotEntity ('rack', $row['id']);
1431 return $ret;
1432}
1433
dfd80d8e 1434function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
6a88e734
DO
1435{
1436 $pfx = '';
1437 $query = 'select ';
a685e6d7 1438 $qparams = array();
6a88e734
DO
1439 foreach ($rcolumns as $col)
1440 {
1441 $query .= $pfx . $col;
1442 $pfx = ', ';
1443 }
1444 $pfx = '';
1445 $query .= " from ${tname} where ";
1446 foreach (explode (' ', $terms) as $term)
1447 {
dfd80d8e
DO
1448 switch ($exactness)
1449 {
1450 case 2: // does this work as expected?
a685e6d7
DO
1451 $query .= $pfx . "binary ${scolumn} = ?";
1452 $qparams[] = $term;
dfd80d8e
DO
1453 break;
1454 case 1:
a685e6d7
DO
1455 $query .= $pfx . "${scolumn} = ?";
1456 $qparams[] = $term;
dfd80d8e
DO
1457 break;
1458 default:
a685e6d7
DO
1459 $query .= $pfx . "${scolumn} like ?";
1460 $qparams[] = "%${term}%";
dfd80d8e
DO
1461 break;
1462 }
6a88e734
DO
1463 $pfx = ' or ';
1464 }
1465 if ($ocolumn != '')
1466 $query .= " order by ${ocolumn}";
a685e6d7 1467 $result = usePreparedSelectBlade ($query, $qparams);
6a88e734
DO
1468 $ret = array();
1469 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1470 $ret[] = $row;
1471 return $ret;
1472}
1473
b1f60545 1474function getObjectSearchResults ($what)
323edbbf
DO
1475{
1476 $ret = array();
1b4a0a6a
DO
1477 global $searchfunc;
1478 foreach ($searchfunc['object'] as $method => $func)
1479 foreach ($func ($what) as $objRecord)
1480 {
1481 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1482 $ret[$objRecord['id']][$method] = $objRecord[$method];
1483 }
b1f60545
DO
1484 return $ret;
1485}
1486
1487function getObjectAttrsSearchResults ($what)
1488{
1489 $ret = array();
1490 foreach (array ('name', 'label', 'asset_no', 'barcode') as $column)
1491 {
1492 $tmp = getSearchResultByField
1493 (
1494 'RackObject',
1495 array ('id'),
1496 $column,
1497 $what,
1498 $column
1499 );
1500 foreach ($tmp as $row)
1501 {
1502 $ret[$row['id']]['id'] = $row['id'];
1503 $ret[$row['id']]['by_attr'][] = $column;
1504 }
1505 }
323edbbf
DO
1506 return $ret;
1507}
1508
1509// Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1510// which matched. A partilar object_id could be returned more, than once, if it has
1511// multiple matching stickers. Search is only performed on "string" attributes.
1512function getStickerSearchResults ($what, $exactness = 0)
1513{
1514 $stickers = getSearchResultByField
1515 (
1516 'AttributeValue',
1517 array ('object_id', 'attr_id'),
1518 'string_value',
1519 $what,
1520 'object_id',
1521 $exactness
1522 );
1523 $map = getAttrMap();
1524 $ret = array();
1525 foreach ($stickers as $sticker)
1526 if ($map[$sticker['attr_id']]['type'] == 'string')
1527 {
1528 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
1529 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
1530 }
1531 return $ret;
1532}
1533
f1b5f68d 1534// search in port "reservation comment", "label" and "L2 address" columns
d516d719 1535function getPortSearchResults ($what)
323edbbf 1536{
f1b5f68d 1537 $ret = array();
323edbbf
DO
1538 $ports = getSearchResultByField
1539 (
1540 'Port',
1b4a0a6a 1541 array ('object_id', 'id', 'reservation_comment'),
323edbbf
DO
1542 'reservation_comment',
1543 $what,
1544 'object_id',
1545 0
1546 );
323edbbf
DO
1547 foreach ($ports as $port)
1548 {
1549 $ret[$port['object_id']]['id'] = $port['object_id'];
1b4a0a6a 1550 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
d516d719 1551 }
f1b5f68d
DO
1552 $ports = getSearchResultByField
1553 (
1554 'Port',
1555 array ('object_id', 'id', 'label'),
1556 'label',
1557 $what,
1558 'object_id',
1559 0
1560 );
1561 foreach ($ports as $port)
1562 {
1563 $ret[$port['object_id']]['id'] = $port['object_id'];
1564 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1565 }
d516d719
DO
1566 if (NULL === ($db_l2address = l2addressForDatabase ($what)))
1567 return $ret;
1568 $ports = getSearchResultByField
1569 (
1570 'Port',
1b4a0a6a 1571 array ('object_id', 'id', 'l2address'),
d516d719
DO
1572 'l2address',
1573 $db_l2address,
1574 'object_id',
1575 2
1576 );
1577 foreach ($ports as $port)
1578 {
1579 $ret[$port['object_id']]['id'] = $port['object_id'];
1b4a0a6a 1580 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
323edbbf
DO
1581 }
1582 return $ret;
1583}
1584
5fd2a004
DO
1585// search in IPv4 allocations
1586function getObjectIfacesSearchResults ($what)
1587{
1588 $ret = array();
1589 $ifaces = getSearchResultByField
1590 (
1591 'IPv4Allocation',
1592 array ('object_id', 'name'),
1593 'name',
1594 $what,
1595 'object_id'
1596 );
1597 foreach ($ifaces as $row)
1598 {
1599 $ret[$row['object_id']]['id'] = $row['object_id'];
1600 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1601 }
1602 return $ret;
1603}
1604
1605function getObjectNATSearchResults ($what)
1606{
1607 $ret = array();
1608 $ifaces = getSearchResultByField
1609 (
1610 'IPv4NAT',
1611 array ('object_id', 'description'),
1612 'description',
1613 $what,
1614 'object_id'
1615 );
1616 foreach ($ifaces as $row)
1617 {
1618 $ret[$row['object_id']]['id'] = $row['object_id'];
1619 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1620 }
1621 return $ret;
1622}
1623
1624// This function returns either port ID or NULL for specified arguments.
e9d357e1 1625function getPortIDs ($object_id, $port_name)
e673ee24 1626{
e9d357e1
DO
1627 $ret = array();
1628 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
1629 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1630 $ret[] = $row['id'];
1631 return $ret;
1632}
1633
1634// Search in "FQDN" attribute only, and return object ID, when there is exactly
1635// one result found (and NULL in any other case).
1636function searchByMgmtHostname ($string)
1637{
1638 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
e673ee24
DO
1639 $rows = $result->fetchAll (PDO::FETCH_NUM);
1640 if (count ($rows) != 1)
1641 return NULL;
e9d357e1 1642 return $rows[0][0];
e673ee24
DO
1643}
1644
1645function commitCreateUserAccount ($username, $realname, $password)
1646{
c9066b1c 1647 return usePreparedInsertBlade
e673ee24
DO
1648 (
1649 'UserAccount',
1650 array
1651 (
654e4636
DO
1652 'user_name' => $username,
1653 'user_realname' => $realname,
1654 'user_password_hash' => $password,
e673ee24
DO
1655 )
1656 );
1657}
1658
1659function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1660{
32832c0e
DO
1661 return usePreparedExecuteBlade
1662 (
1663 'UPDATE UserAccount SET user_name=?, user_realname=?, user_password_hash=? ' .
1664 'WHERE user_id=?',
1665 array ($new_username, $new_realname, $new_password, $id)
1666 );
e673ee24
DO
1667}
1668
e673ee24 1669// This function returns an array of all port type pairs from PortCompat table.
27ec21b2 1670function getPortOIFCompat ()
e673ee24 1671{
e673ee24
DO
1672 $query =
1673 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1674 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
27ec21b2
DO
1675 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1676 'ORDER BY type1name, type2name';
c9066b1c 1677 $result = usePreparedSelectBlade ($query);
27ec21b2 1678 return $result->fetchAll (PDO::FETCH_ASSOC);
e673ee24
DO
1679}
1680
a310dd80
DO
1681// Add a pair to the PortCompat table.
1682function commitSupplementPOIFC ($type1, $type2)
e673ee24 1683{
0cc24e9a
DY
1684 if ($type1 <= 0)
1685 throw new InvalidArgException ('type1', $type1);
1686 if ($type2 <= 0)
1687 throw new InvalidArgException ('type2', $type2);
c9066b1c 1688 return usePreparedInsertBlade
a310dd80
DO
1689 (
1690 'PortCompat',
1691 array ('type1' => $type1, 'type2' => $type2)
1692 );
e673ee24
DO
1693}
1694
a310dd80
DO
1695// Remove a pair from the PortCompat table.
1696function commitReducePOIFC ($type1, $type2)
e673ee24 1697{
c9066b1c 1698 return usePreparedDeleteBlade ('PortCompat', array ('type1' => $type1, 'type2' => $type2));
e673ee24
DO
1699}
1700
da95280e
DO
1701function getDictStats ()
1702{
63811a09 1703 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
c9066b1c
DO
1704 $result = usePreparedSelectBlade
1705 (
10bac82a 1706 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
c9066b1c
DO
1707 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
1708 );
da95280e 1709 $tc = $tw = $uc = $uw = 0;
89fa639f 1710 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1711 {
1712 $tc++;
1713 $tw += $row['wc'];;
1714 if (in_array ($row['chapter_no'], $stock_chapters))
1715 continue;
1716 $uc++;
1717 $uw += $row['wc'];;
1718 }
89fa639f
DO
1719 $result->closeCursor();
1720 unset ($result);
c9066b1c
DO
1721 $result = usePreparedSelectBlade
1722 (
1723 "select count(object_id) as attrc from RackObject as ro left join " .
1724 "AttributeValue as av on ro.id = av.object_id group by ro.id"
1725 );
08b4cb24 1726 $to = $ta = $so = 0;
89fa639f 1727 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1728 {
1729 $to++;
1730 if ($row['attrc'] != 0)
1731 {
1732 $so++;
1733 $ta += $row['attrc'];
1734 }
1735 }
89fa639f 1736 $result->closeCursor();
da95280e
DO
1737 $ret = array();
1738 $ret['Total chapters in dictionary'] = $tc;
1739 $ret['Total words in dictionary'] = $tw;
1740 $ret['User chapters'] = $uc;
1741 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1742 $ret['Total objects'] = $to;
1743 $ret['Objects with stickers'] = $so;
1744 $ret['Total stickers attached'] = $ta;
da95280e
DO
1745 return $ret;
1746}
1747
6807f0be 1748function getIPv4Stats ()
9ec5fdf1 1749{
9ec5fdf1
DO
1750 $ret = array();
1751 $subject = array();
706ce117
DO
1752 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1753 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1754 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1755 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1756 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1757 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1758 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1759 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
9ec5fdf1
DO
1760
1761 foreach ($subject as $item)
1762 {
c9066b1c 1763 $result = usePreparedSelectBlade ($item['q']);
9ec5fdf1
DO
1764 $row = $result->fetch (PDO::FETCH_NUM);
1765 $ret[$item['txt']] = $row[0];
1766 $result->closeCursor();
1767 unset ($result);
1768 }
1769 return $ret;
1770}
1771
6807f0be 1772function getRackspaceStats ()
9ec5fdf1 1773{
9ec5fdf1
DO
1774 $ret = array();
1775 $subject = array();
10bac82a 1776 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
9ec5fdf1
DO
1777 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1778 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1779 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1780
1781 foreach ($subject as $item)
1782 {
c9066b1c 1783 $result = usePreparedSelectBlade ($item['q']);
9ec5fdf1 1784 $row = $result->fetch (PDO::FETCH_NUM);
59a83bd8 1785 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1786 $result->closeCursor();
1787 unset ($result);
1788 }
1789 return $ret;
1790}
1791
6807f0be
DO
1792/*
1793
1794The following allows figuring out records in TagStorage, which refer to non-existing entities:
1795
120e9ddd
DO
1796mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1797mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1798mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1799mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1800mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1801mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1802mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
6807f0be
DO
1803
1804Accordingly, these are the records, which refer to non-existent tags:
1805
1806mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1807
1808*/
1809
826c3dbd 1810// chapter_no is a must, see at @commitReduceDictionary() why
e673ee24
DO
1811function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1812{
32832c0e
DO
1813 return usePreparedExecuteBlade
1814 (
1815 'UPDATE Dictionary SET dict_value=? WHERE chapter_id=? AND dict_key=?',
1816 array ($dict_value, $chapter_no, $dict_key)
1817 );
e673ee24
DO
1818}
1819
1820function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1821{
c5f84f48
DY
1822 if ($chapter_no <= 0)
1823 throw new InvalidArgException ('$chapter_no', $chapter_no);
1824 if (!strlen ($dict_value))
1825 throw new InvalidArgException ('$dict_value', $dict_value);
c9066b1c 1826 return usePreparedInsertBlade
e673ee24
DO
1827 (
1828 'Dictionary',
c9066b1c 1829 array ('chapter_id' => $chapter_no, 'dict_value' => $dict_value)
e673ee24
DO
1830 );
1831}
1832
178fda20
DO
1833// Technically dict_key is enough to delete, but including chapter_id into
1834// WHERE clause makes sure, that the action actually happends for the same
1835// chapter, which authorization was granted for.
e673ee24
DO
1836function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1837{
c9066b1c 1838 return usePreparedDeleteBlade ('Dictionary', array ('chapter_id' => $chapter_no, 'dict_key' => $dict_key));
e673ee24
DO
1839}
1840
1841function commitAddChapter ($chapter_name = '')
1842{
59a83bd8 1843 if (!strlen ($chapter_name))
c5f84f48 1844 throw new InvalidArgException ('$chapter_name', $chapter_name);
c9066b1c 1845 return usePreparedInsertBlade
e673ee24
DO
1846 (
1847 'Chapter',
c9066b1c 1848 array ('name' => $chapter_name)
e673ee24
DO
1849 );
1850}
1851
1852function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1853{
178fda20 1854 if (!strlen ($chapter_name))
c5f84f48 1855 throw new InvalidArgException ('$chapter_name', $chapter_name);
32832c0e
DO
1856 return usePreparedExecuteBlade
1857 (
1858 'UPDATE Chapter SET name=? WHERE id=? AND sticky="no"',
1859 array ($chapter_name, $chapter_no)
1860 );
e673ee24
DO
1861}
1862
1863function commitDeleteChapter ($chapter_no = 0)
1864{
c9066b1c 1865 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
e673ee24
DO
1866}
1867
4c330a14
DO
1868// This is a dictionary accessor. We perform link rendering, so the user sees
1869// nice <select> drop-downs.
7fa7047a 1870function readChapter ($chapter_id = 0, $style = '')
e673ee24 1871{
c9066b1c
DO
1872 $result = usePreparedSelectBlade
1873 (
7fa7047a 1874 "select dict_key, dict_value from Dictionary " .
c9066b1c
DO
1875 "where chapter_id = ?",
1876 array ($chapter_id)
1877 );
e673ee24
DO
1878 $chapter = array();
1879 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7fa7047a 1880 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
e673ee24 1881 $result->closeCursor();
4aa8609b
DO
1882 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1883 asort ($chapter);
e673ee24
DO
1884 return $chapter;
1885}
1886
7fa7047a
DO
1887// Return refcounters for all given keys of the given chapter.
1888function getChapterRefc ($chapter_id, $keylist)
1889{
afdb3cf5
DO
1890 $ret = array();
1891 foreach ($keylist as $key)
1892 $ret[$key] = 0;
7fa7047a
DO
1893 switch ($chapter_id)
1894 {
1895 case CHAP_OBJTYPE:
1896 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
1897 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
c9066b1c 1898 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
7fa7047a
DO
1899 break;
1900 case CHAP_PORTTYPE:
93a83f51 1901 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
7fa7047a 1902 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
93a83f51 1903 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
c9066b1c 1904 "from Dictionary where chapter_id = ?";
7fa7047a
DO
1905 break;
1906 default:
1907 // Find the list of all assigned values of dictionary-addressed attributes, each with
1908 // chapter/word keyed reference counters.
1909 $query = "select uint_value, count(object_id) as refcnt " .
1910 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1911 "inner join AttributeValue as av on a.id = av.attr_id " .
1912 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
c9066b1c 1913 "where a.type = 'dict' and am.chapter_id = ? group by uint_value";
7fa7047a
DO
1914 break;
1915 }
c9066b1c 1916 $result = usePreparedSelectBlade ($query, array ($chapter_id));
7fa7047a
DO
1917 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1918 $ret[$row['uint_value']] = $row['refcnt'];
1919 return $ret;
1920}
1921
e4e9e2a1
DO
1922// Return a list of all stickers with sticker map applied. Each sticker records will
1923// list all its ways on the map with refcnt set.
e673ee24
DO
1924function getAttrMap ()
1925{
c9066b1c
DO
1926 $result = usePreparedSelectBlade
1927 (
978dc510
DO
1928 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
1929 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
7fa7047a 1930 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
e4e9e2a1 1931 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
c9066b1c
DO
1932 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
1933 );
e673ee24
DO
1934 $ret = array();
1935 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1936 {
e4e9e2a1
DO
1937 if (!isset ($ret[$row['id']]))
1938 $ret[$row['id']] = array
1939 (
1940 'id' => $row['id'],
1941 'type' => $row['type'],
1942 'name' => $row['name'],
1943 'application' => array(),
1944 );
e673ee24
DO
1945 if ($row['objtype_id'] == '')
1946 continue;
e4e9e2a1
DO
1947 $application = array
1948 (
1949 'objtype_id' => $row['objtype_id'],
e4e9e2a1
DO
1950 'refcnt' => $row['refcnt'],
1951 );
1952 if ($row['type'] == 'dict')
e673ee24 1953 {
50393983 1954 $application['chapter_no'] = $row['chapter_id'];
e673ee24
DO
1955 $application['chapter_name'] = $row['chapter_name'];
1956 }
e4e9e2a1 1957 $ret[$row['id']]['application'][] = $application;
e673ee24 1958 }
e673ee24
DO
1959 return $ret;
1960}
1961
1962function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1963{
32832c0e 1964 return usePreparedExecuteBlade ('UPDATE Attribute SET name=? WHERE id=?', array ($attr_name, $attr_id));
e673ee24
DO
1965}
1966
1967function commitAddAttribute ($attr_name = '', $attr_type = '')
1968{
59a83bd8 1969 if (!strlen ($attr_name))
0cc24e9a 1970 throw new InvalidArgException ('$attr_name', $attr_name);
e673ee24
DO
1971 switch ($attr_type)
1972 {
1973 case 'uint':
1974 case 'float':
1975 case 'string':
1976 case 'dict':
1977 break;
1978 default:
0cc24e9a 1979 throw new InvalidArgException ('$attr_type', $attr_type, 'Attribute type not supported');
e673ee24 1980 }
c9066b1c 1981 return usePreparedInsertBlade
e673ee24
DO
1982 (
1983 'Attribute',
c9066b1c 1984 array ('name' => $attr_name, 'type' => $attr_type)
e673ee24
DO
1985 );
1986}
1987
1988function commitDeleteAttribute ($attr_id = 0)
1989{
c9066b1c 1990 return usePreparedDeleteBlade ('Attribute', array ('id' => $attr_id));
e673ee24
DO
1991}
1992
1993// FIXME: don't store garbage in chapter_no for non-dictionary types.
1994function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1995{
0cc24e9a
DY
1996 if ($attr_id <= 0)
1997 throw new InvalidArgException ('$attr_id', $attr_id);
1998 if ($objtype_id <= 0)
1999 throw new InvalidArgException ('$objtype_id', $objtype_id);
2000
c9066b1c 2001 return usePreparedInsertBlade
e673ee24
DO
2002 (
2003 'AttributeMap',
2004 array
2005 (
2006 'attr_id' => $attr_id,
2007 'objtype_id' => $objtype_id,
10bac82a 2008 'chapter_id' => $chapter_no
e673ee24
DO
2009 )
2010 );
2011}
2012
2013function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2014{
c9066b1c 2015 return usePreparedDeleteBlade ('AttributeMap', array ('attr_id' => $attr_id, 'objtype_id' => $objtype_id));
e673ee24
DO
2016}
2017
2018// This function returns all optional attributes for requested object
2019// as an array of records. NULL is returned on error and empty array
2020// is returned, if there are no attributes found.
7fa7047a 2021function getAttrValues ($object_id)
e673ee24 2022{
e673ee24 2023 $ret = array();
c9066b1c
DO
2024 $result = usePreparedSelectBlade
2025 (
10bac82a 2026 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
7fa7047a 2027 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
e673ee24 2028 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
10bac82a 2029 "inner join Attribute as A on AM.attr_id = A.id " .
e673ee24 2030 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
10bac82a
DY
2031 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2032 "left join Chapter as C on AM.chapter_id = C.id " .
c9066b1c
DO
2033 "where RO.id = ? order by A.name, A.type",
2034 array ($object_id)
2035 );
e673ee24
DO
2036 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2037 {
2038 $record = array();
2039 $record['id'] = $row['attr_id'];
2040 $record['name'] = $row['attr_name'];
2041 $record['type'] = $row['attr_type'];
2042 switch ($row['attr_type'])
2043 {
7fa7047a
DO
2044 case 'dict':
2045 $record['chapter_id'] = $row['chapter_id'];
2046 $record['chapter_name'] = $row['chapter_name'];
2047 $record['key'] = $row['uint_value'];
2048 // fall through
e673ee24
DO
2049 case 'uint':
2050 case 'float':
2051 case 'string':
24cbe8af 2052 $record['value'] = $row[$row['attr_type'] . '_value'];
7fa7047a 2053 $record['o_value'] = parseWikiLink ($record['value'], 'o');
24cbe8af
DO
2054 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2055 break;
e673ee24
DO
2056 default:
2057 $record['value'] = NULL;
2058 break;
2059 }
2060 $ret[$row['attr_id']] = $record;
2061 }
2062 $result->closeCursor();
2063 return $ret;
2064}
2065
2066function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2067{
c9066b1c 2068 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
e673ee24
DO
2069}
2070
e673ee24
DO
2071function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2072{
0cc24e9a
DY
2073 if ($object_id <= 0)
2074 throw new InvalidArgException ('$objtype_id', $objtype_id);
2075 if ($attr_id <= 0)
2076 throw new InvalidArgException ('$attr_id', $attr_id);
59a83bd8 2077 if (!strlen ($value))
e673ee24 2078 return commitResetAttrValue ($object_id, $attr_id);
c9066b1c 2079 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
e673ee24 2080 $row = $result->fetch (PDO::FETCH_NUM);
e673ee24 2081 $attr_type = $row[0];
c9066b1c 2082 unset ($result);
e673ee24
DO
2083 switch ($attr_type)
2084 {
2085 case 'uint':
2086 case 'float':
2087 case 'string':
2088 $column = $attr_type . '_value';
2089 break;
2090 case 'dict':
2091 $column = 'uint_value';
2092 break;
2093 default:
0cc24e9a 2094 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
e673ee24 2095 }
c9066b1c 2096 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
e673ee24 2097 // We know $value isn't empty here.
c9066b1c
DO
2098 usePreparedInsertBlade
2099 (
2100 'AttributeValue',
2101 array
2102 (
2103 $column => $value,
2104 'object_id' => $object_id,
2105 'attr_id' => $attr_id,
2106 )
2107 );
e673ee24
DO
2108 return TRUE;
2109}
2110
2111function commitUseupPort ($port_id = 0)
2112{
32832c0e 2113 return usePreparedExecuteBlade ('UPDATE Port SET reservation_comment=NULL WHERE id=?', array ($port_id));
e673ee24
DO
2114}
2115
3fb56626
DO
2116function convertPDOException ($e)
2117{
2118 if ($e->getCode() != 23000)
2119 return $e;
2120 switch ($e->errorInfo[1])
2121 {
2122 case 1062:
2123 $text = 'such record already exists';
2124 break;
2125 case 1451:
2126 case 1452:
2127 $text = 'foreign key violation';
2128 break;
2129 default:
2130 $text = 'unknown error code ' . $e->errorInfo[1];
2131 break;
2132 }
2133 return new Exception ($text, E_DB_CONSTRAINT);
2134}
2135
e673ee24
DO
2136// This is a swiss-knife blade to insert a record into a table.
2137// The first argument is table name.
2138// The second argument is an array of "name" => "value" pairs.
357eb2ea
DO
2139function usePreparedInsertBlade ($tablename, $columns)
2140{
2141 global $dbxlink;
2142 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2143 $query .= ') VALUES (' . implode (', ', array_fill (0, count ($columns), '?')) . ')';
2144 // Now the query should be as follows:
2145 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
5f054512
DO
2146 try
2147 {
3fb56626 2148 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2149 if (!$prepared->execute (array_values ($columns)))
2150 return FALSE;
2151 return $prepared->rowCount() == 1;
2152 }
2153 catch (PDOException $e)
2154 {
3fb56626 2155 throw convertPDOException ($e);
5f054512 2156 }
357eb2ea
DO
2157}
2158
9589714d
DO
2159// This swiss-knife blade deletes any number of records from the specified table
2160// using the specified key names and values.
bbae3611 2161function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
8198f2c6
DO
2162{
2163 global $dbxlink;
bbae3611
DO
2164 $conj = '';
2165 $query = "DELETE FROM ${tablename} WHERE ";
2166 foreach ($columns as $colname => $colvalue)
2167 {
de47b574 2168 $query .= " ${conj} ${colname}=?";
bbae3611
DO
2169 $conj = $conjunction;
2170 }
5f054512
DO
2171 try
2172 {
3fb56626 2173 $prepared = $dbxlink->prepare ($query);
5f054512
DO
2174 if (!$prepared->execute (array_values ($columns)))
2175 return FALSE;
2176 return $prepared->rowCount(); // FALSE !== 0
2177 }
2178 catch (PDOException $e)
2179 {
3fb56626 2180 throw convertPDOException ($e);
5f054512 2181 }
8198f2c6
DO
2182}
2183
d0dadd80
DO
2184function usePreparedSelectBlade ($query, $args = array())
2185{
2186 global $dbxlink;
2187 $prepared = $dbxlink->prepare ($query);
2188 if (!$prepared->execute ($args))
2189 return FALSE;
2190 return $prepared;
2191}
2192
39eadd27
DO
2193// Prepare and execute the statement with parameters, then return number of
2194// rows affected (or FALSE in case of an error).
2195function usePreparedExecuteBlade ($query, $args = array())
2196{
2197 global $dbxlink;
3fb56626
DO
2198 try
2199 {
2200 if (!$prepared = $dbxlink->prepare ($query))
2201 return FALSE;
2202 if (!$prepared->execute ($args))
2203 return FALSE;
2204 return $prepared->rowCount();
2205 }
2206 catch (PDOException $e)
2207 {
2208 throw convertPDOException ($e);
2209 }
39eadd27
DO
2210}
2211
9c0b0016
DO
2212function loadConfigCache ()
2213{
c9066b1c 2214 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
3540d15c 2215 $cache = array();
c9066b1c 2216 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3540d15c 2217 $cache[$row['varname']] = $row;
3540d15c
DY
2218 return $cache;
2219}
2220
2221function loadUserConfigCache ($username = NULL)
2222{
2223 if (!strlen ($username))
2224 throw new InvalidArgException ('$username', $username);
c9066b1c 2225 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
9c0b0016
DO
2226 $cache = array();
2227 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2228 $cache[$row['varname']] = $row;
9c0b0016
DO
2229 return $cache;
2230}
2231
3540d15c
DY
2232function deleteUserConfigVar ($username = NULL, $varname = NULL)
2233{
c9066b1c 2234 usePreparedDeleteBlade ('UserConfig', array ('varname' => $varname, 'user' => $username));
3540d15c
DY
2235}
2236
3540d15c
DY
2237function storeUserConfigVar ($username = NULL, $varname = NULL, $varvalue = NULL)
2238{
3540d15c
DY
2239 if (!strlen ($username))
2240 throw new InvalidArgException ('$username', $username);
2241 if (!strlen ($varname))
2242 throw new InvalidArgException ('$varname', $varname);
2243 if ($varvalue === NULL)
2244 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2245 return usePreparedExecuteBlade
2246 (
2247 'REPLACE UserConfig SET varvalue=?, varname=?, user=?',
2248 array ($varvalue, $varname, $username)
e5925cee 2249 );
3540d15c
DY
2250}
2251
9c0b0016
DO
2252// setConfigVar() is expected to perform all necessary filtering
2253function storeConfigVar ($varname = NULL, $varvalue = NULL)
2254{
c5f84f48
DY
2255 if ($varvalue === NULL)
2256 throw new InvalidArgException ('$varvalue', $varvalue);
32832c0e
DO
2257 return usePreparedExecuteBlade
2258 (
2259 'UPDATE Config SET varvalue=? WHERE varname=?',
2260 array ($varvalue, $varname)
2261 );
9c0b0016
DO
2262}
2263
49293c68
DO
2264// Database version detector. Should behave corretly on any
2265// working dataset a user might have.
2266function getDatabaseVersion ()
2267{
2268 $result = usePreparedSelectBlade ('SELECT varvalue FROM Config WHERE varname = "DB_VERSION" and vartype = "string"');
2269 if ($result == NULL)
2270 {
2271 global $dbxlink;
2272 $errorInfo = $dbxlink->errorInfo();
2273 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2274 return '0.14.4';
2275 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2276 }
2277 $rows = $result->fetchAll (PDO::FETCH_NUM);
2278 if (count ($rows) != 1 || !strlen ($rows[0][0]))
2279 {
2280 $result->closeCursor();
2281 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2282 }
2283 $ret = $rows[0][0];
2284 $result->closeCursor();
2285 return $ret;
2286}
2287
da04825a
DO
2288// Return an array of virtual services. For each of them list real server pools
2289// with their load balancers and other stats.
62a1dcb5
DO
2290function getSLBSummary ()
2291{
c9066b1c
DO
2292 $result = usePreparedSelectBlade
2293 (
2294 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
6fec9f39 2295 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2296 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2297 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2298 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
c9066b1c
DO
2299 'group by vs.id, object_id order by vs.vip, object_id'
2300 );
c3bdc503
DO
2301 $ret = array();
2302 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2303 {
4cadac8f 2304 $vsid = $row['vsid'];
da04825a 2305 $object_id = $row['object_id'];
4cadac8f
DO
2306 if (!isset ($ret[$vsid]))
2307 {
2308 $ret[$vsid] = array();
13bffb29 2309 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2310 $ret[$vsid][$cname] = $row[$cname];
da04825a 2311 $ret[$vsid]['lblist'] = array();
4cadac8f 2312 }
6fec9f39
DO
2313 // There's only one assigned RS pool possible for each LB-VS combination.
2314 $ret[$vsid]['lblist'][$row['object_id']] = array
2315 (
2316 'id' => $row['rspool_id'],
2317 'size' => $row['rscount'],
2318 'name' => $row['pool_name']
2319 );
c3bdc503
DO
2320 }
2321 return $ret;
62a1dcb5
DO
2322}
2323
7e7a8387 2324function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2325{
a5c589d2 2326 return usePreparedExecuteBlade
ca461127 2327 (
a5c589d2 2328 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
ca461127
DO
2329 array
2330 (
a5c589d2
DO
2331 $rsip,
2332 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2333 $pool_id,
2334 $inservice == 'yes' ? 'yes' : 'no',
2335 !strlen ($rsconfig) ? NULL : $rsconfig
3241551e
DO
2336 )
2337 );
2338}
2339
c63a8d6e 2340function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21 2341{
c5f84f48
DY
2342 if (!strlen ($vip))
2343 throw new InvalidArgException ('$vip', $vip);
2344 if ($vport <= 0)
2345 throw new InvalidArgException ('$vport', $vport);
2346 if (!strlen ($proto))
2347 throw new InvalidArgException ('$proto', $proto);
a5c589d2 2348 if (FALSE === usePreparedExecuteBlade
d6517a21 2349 (
a5c589d2 2350 'INSERT INTO IPv4VS (vip, vport, proto, name, vsconfig, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?, ?)',
d6517a21
DO
2351 array
2352 (
a5c589d2
DO
2353 $vip,
2354 $vport,
2355 $proto,
2356 !strlen ($name) ? NULL : $name,
2357 !strlen ($vsconfig) ? NULL : $vsconfig,
2358 !strlen ($rsconfig) ? NULL : $rsconfig,
d6517a21 2359 )
c63a8d6e
DO
2360 ))
2361 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2362 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2363}
2364
c1ca768c 2365function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2366{
c9066b1c 2367 return usePreparedInsertBlade
3241551e 2368 (
706ce117 2369 'IPv4LB',
3241551e
DO
2370 array
2371 (
2372 'object_id' => $object_id,
2373 'rspool_id' => $pool_id,
c1ca768c 2374 'vs_id' => $vs_id,
c9066b1c
DO
2375 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2376 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
3241551e 2377 )
ca461127
DO
2378 );
2379}
2380
fb1c4a54
DO
2381function commitDeleteRS ($id = 0)
2382{
c9066b1c 2383 return usePreparedDeleteBlade ('IPv4RS', array ('id' => $id));
fb1c4a54
DO
2384}
2385
d6517a21
DO
2386function commitDeleteVS ($id = 0)
2387{
6657739e 2388 releaseFiles ('ipv4vs', $id);
0da3bf00 2389 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2390}
2391
c1ca768c 2392function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e 2393{
c9066b1c 2394 return usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id, 'rspool_id' => $pool_id, 'vs_id' => $vs_id));
3241551e
DO
2395}
2396
fb1c4a54
DO
2397function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2398{
fb1c4a54 2399 if (long2ip (ip2long ($rsip)) !== $rsip)
c5f84f48 2400 throw new InvalidArgException ('$rsip', $rsip);
a5c589d2
DO
2401 return usePreparedExecuteBlade
2402 (
2403 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2404 array
2405 (
2406 $rsip,
2407 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2408 !strlen ($rsconfig) ? NULL : $rsconfig,
2409 $rsid,
2410 )
2411 );
fb1c4a54
DO
2412}
2413
c1ca768c 2414function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2415{
a5c589d2
DO
2416 return usePreparedExecuteBlade
2417 (
2418 'UPDATE IPv4LB SET vsconfig=?, rsconfig=? WHERE object_id=? AND rspool_id=? AND vs_id=?',
2419 array
2420 (
2421 !strlen ($vsconfig) ? NULL : $vsconfig,
2422 !strlen ($rsconfig) ? NULL : $rsconfig,
2423 $object_id,
2424 $pool_id,
2425 $vs_id,
2426 )
2427 );
3241551e
DO
2428}
2429
d6517a21
DO
2430function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2431{
c5f84f48
DY
2432 if (!strlen ($vip))
2433 throw new InvalidArgException ('$vip', $vip);
2434 if ($vport <= 0)
2435 throw new InvalidArgException ('$vport', $vport);
2436 if (!strlen ($proto))
2437 throw new InvalidArgException ('$proto', $proto);
a5c589d2
DO
2438 return usePreparedExecuteBlade
2439 (
2440 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2441 array
2442 (
2443 $vip,
2444 $vport,
2445 $proto,
2446 !strlen ($name) ? NULL : $name,
2447 !strlen ($vsconfig) ? NULL : $vsconfig,
2448 !strlen ($rsconfig) ? NULL : $rsconfig,
2449 $vsid,
2450 )
2451 );
d6517a21
DO
2452}
2453
5a1680d2
DO
2454function loadThumbCache ($rack_id = 0)
2455{
5a1680d2 2456 $ret = NULL;
c9066b1c 2457 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
5a1680d2
DO
2458 $row = $result->fetch (PDO::FETCH_ASSOC);
2459 if ($row)
2460 $ret = base64_decode ($row['thumb_data']);
5a1680d2
DO
2461 return $ret;
2462}
2463
2464function saveThumbCache ($rack_id = 0, $cache = NULL)
2465{
178fda20 2466 if ($cache == NULL)
c5f84f48 2467 throw new InvalidArgException ('$cache', $cache);
a5c589d2 2468 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=? WHERE id=?', array (base64_encode ($cache), $rack_id));
5a1680d2 2469}
9a81d416 2470
c7fe33be
DO
2471function resetThumbCache ($rack_id = 0)
2472{
a5c589d2 2473 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=NULL WHERE id=?', array ($rack_id));
c7fe33be
DO
2474}
2475
748805bf 2476// Return the list of attached RS pools for the given object. As long as we have
706ce117 2477// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2478// by vs_id, because there will be only one RS pool listed for each VS of the
2479// current object.
78e7b769
DO
2480function getRSPoolsForObject ($object_id = 0)
2481{
c9066b1c
DO
2482 $result = usePreparedSelectBlade
2483 (
2484 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2485 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2486 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2487 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2488 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
c9066b1c
DO
2489 'where lb.object_id = ? ' .
2490 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2491 array ($object_id)
2492 );
748805bf 2493 $ret = array ();
78e7b769 2494 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2495 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2496 $ret[$row['vs_id']][$cname] = $row[$cname];
748805bf 2497 return $ret;
78e7b769
DO
2498}
2499
c63a8d6e 2500function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2501{
59a83bd8 2502 if (!strlen ($name))
c5f84f48 2503 throw new InvalidArgException ('$name', $name);
c9066b1c 2504 if (!usePreparedInsertBlade
5ad76f01 2505 (
706ce117 2506 'IPv4RSPool',
5ad76f01
DO
2507 array
2508 (
c9066b1c
DO
2509 'name' => (!strlen ($name) ? NULL : $name),
2510 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2511 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
5ad76f01 2512 )
c63a8d6e
DO
2513 ))
2514 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2515 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2516}
2517
2518function commitDeleteRSPool ($pool_id = 0)
2519{
6657739e 2520 releaseFiles ('ipv4rspool', $pool_id);
c9066b1c 2521 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2522}
2523
2524function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2525{
a5c589d2
DO
2526 return usePreparedExecuteBlade
2527 (
2528 'UPDATE IPv4RSPool SET name=?, vsconfig=?, rsconfig=? WHERE id=?',
2529 array
2530 (
2531 !strlen ($name) ? NULL : $name,
2532 !strlen ($vsconfig) ? NULL : $vsconfig,
2533 !strlen ($rsconfig) ? NULL : $rsconfig,
2534 $pool_id,
2535 )
2536 );
5ad76f01
DO
2537}
2538
8253d9f0
DO
2539function getRSList ()
2540{
c9066b1c
DO
2541 $result = usePreparedSelectBlade
2542 (
2543 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2544 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2545 );
4b0932b6 2546 $ret = array ();
8253d9f0 2547 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2548 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6 2549 $ret[$row['id']][$cname] = $row[$cname];
4b0932b6
DO
2550 return $ret;
2551}
2552
2553// Return the list of all currently configured load balancers with their pool count.
2554function getLBList ()
2555{
c9066b1c
DO
2556 $result = usePreparedSelectBlade
2557 (
2558 "select object_id, count(rspool_id) as poolcount " .
2559 "from IPv4LB group by object_id order by object_id"
2560 );
4b0932b6
DO
2561 $ret = array ();
2562 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2563 $ret[$row['object_id']] = $row['poolcount'];
4b0932b6 2564 return $ret;
8253d9f0
DO
2565}
2566
178fda20 2567// For the given object return: its vsconfig/rsconfig; the list of RS pools
9e677cbd
DO
2568// attached (each with vsconfig/rsconfig in turn), each with the list of
2569// virtual services terminating the pool. Each pool also lists all real
2570// servers with rsconfig.
2987fc1f 2571function getSLBConfig ($object_id)
9e677cbd 2572{
9e677cbd 2573 $ret = array();
e34dac4f
DO
2574 $result = usePreparedSelectBlade
2575 (
2576 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
d91f08f3
DO
2577 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2578 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2579 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2580 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2581 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2582 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2583 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
e34dac4f
DO
2584 "where lb.object_id = ? and rs.inservice = 'yes' " .
2585 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2586 array ($object_id)
2587 );
9e677cbd
DO
2588 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2589 {
d91f08f3
DO
2590 $vs_id = $row['vs_id'];
2591 if (!isset ($ret[$vs_id]))
2592 {
2593 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)
2594 $ret[$vs_id][$c] = $row[$c];
2595 $ret[$vs_id]['rslist'] = array();
2596 }
2597 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2598 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd 2599 }
9e677cbd
DO
2600 return $ret;
2601}
1f7d18fa
DO
2602
2603function commitSetInService ($rs_id = 0, $inservice = '')
2604{
c5f84f48
DY
2605 if (!strlen ($inservice))
2606 throw new InvalidArgException ('$inservice', $inservice);
a5c589d2 2607 return usePreparedExecuteBlade ('UPDATE IPv4RS SET inservice=? WHERE id=?', array ($inservice, $rs_id));
1f7d18fa
DO
2608}
2609
ad0e4754
DO
2610function executeAutoPorts ($object_id = 0, $type_id = 0)
2611{
c5f84f48
DY
2612 if ($object_id == 0)
2613 throw new InvalidArgException ('$object_id', $object_id);
2614 if ($type_id == 0)
2615 throw new InvalidArgException ('$type_id', $type_id);
f3f0161f 2616 $ret = TRUE;
118e4c38 2617 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2618 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2619 return $ret;
ad0e4754
DO
2620}
2621
6e49bd1f 2622// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2623// generated/deducted later at higher levels.
aab37bc0 2624// Result is a chain: randomly indexed taginfo list.
f9bc186f 2625function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2626{
a6e8d544 2627 $ret = array();
e34dac4f
DO
2628 $result = usePreparedSelectBlade
2629 (
2630 "select tt.id, tag from " .
edf0993c 2631 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
e34dac4f
DO
2632 "where entity_realm = ? and entity_id = ? " .
2633 "order by tt.tag",
2634 array ($entity_realm, $entity_id)
2635 );
5967b83d 2636 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2637 $ret[$row['id']] = $row;
aab37bc0 2638 return getExplicitTagsOnly ($ret);
5967b83d
DO
2639}
2640
351c0966 2641// Return a tag chain with all DB tags on it.
5967b83d
DO
2642function getTagList ()
2643{
20c901a7 2644 $ret = array();
e34dac4f
DO
2645 $result = usePreparedSelectBlade
2646 (
2647 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2648 "from TagTree left join TagStorage on id = tag_id " .
e34dac4f
DO
2649 "group by id, entity_realm order by tag"
2650 );
2651 // Collation index. The resulting rows are ordered according to default collation,
fb7a4967 2652 // which is utf8_general_ci for UTF-8.
e34dac4f 2653 $ci = 0;
5967b83d 2654 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2655 {
7cc02fc1 2656 if (!isset ($ret[$row['id']]))
20c901a7 2657 $ret[$row['id']] = array
5b7bd02e
DO
2658 (
2659 'id' => $row['id'],
2660 'tag' => $row['tag'],
fb7a4967 2661 'ci' => $ci++,
5b7bd02e 2662 'parent_id' => $row['parent_id'],
9e51318b 2663 'refcnt' => array ('total' => 0)
5b7bd02e
DO
2664 );
2665 if ($row['realm'])
9e51318b 2666 {
20c901a7 2667 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
9e51318b
DO
2668 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2669 }
5b7bd02e 2670 }
20c901a7 2671 return $ret;
5967b83d
DO
2672}
2673
fe7044ad
DO
2674function commitCreateTag ($tagname = '', $parent_id = 0)
2675{
6cfedb71
DO
2676 if ($tagname == '')
2677 throw new InvalidArgException ('tagname', $tagname);
2678 return usePreparedInsertBlade
fe7044ad
DO
2679 (
2680 'TagTree',
2681 array
2682 (
e34dac4f 2683 'tag' => $tagname,
fe7044ad
DO
2684 'parent_id' => $parent_id
2685 )
2686 );
fe7044ad
DO
2687}
2688
2689function commitDestroyTag ($tagid = 0)
2690{
e34dac4f 2691 if (usePreparedDeleteBlade ('TagTree', array ('id' => $tagid)))
fe7044ad 2692 return '';
e34dac4f 2693 return 'usePreparedDeleteBlade() failed in ' . __FUNCTION__;
fe7044ad 2694}
f9bc186f 2695
49fb1027 2696function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2697{
a5c589d2
DO
2698 return usePreparedExecuteBlade
2699 (
2700 'UPDATE TagTree SET tag=?, parent_id=? WHERE id=?',
2701 array
2702 (
2703 $tag_name,
2704 $parent_id == 0 ? NULL : $parent_id,
2705 $tag_id,
2706 )
2707 );
f9bc186f
DO
2708}
2709
01b6b4d6
DO
2710// Drop the whole chain stored.
2711function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af 2712{
e34dac4f 2713 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
aedf18af
DO
2714}
2715
01b6b4d6 2716// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
29c3a4d8
DO
2717// FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2718// but not now.
01b6b4d6
DO
2719function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2720{
e34dac4f 2721 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
01b6b4d6
DO
2722}
2723
351c0966 2724// Push a record into TagStorage unconditionally.
3355ca56 2725function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2726{
e34dac4f 2727 if (!in_array ($realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
3355ca56 2728 return FALSE;
e34dac4f 2729 return usePreparedInsertBlade
eb6ea26f
DO
2730 (
2731 'TagStorage',
2732 array
2733 (
e34dac4f 2734 'entity_realm' => $realm,
120e9ddd 2735 'entity_id' => $entity_id,
eb6ea26f
DO
2736 'tag_id' => $tag_id,
2737 )
2738 );
2739}
2740
351c0966 2741// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
2742// on the implicit list already). Then remove any other records, which
2743// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
2744// that both the tag base is still minimal and all requested tags appear on
2745// the resulting tag chain.
abef7149
DO
2746// Return TRUE, if any changes were committed.
2747function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2748{
2749 // Put the current explicit sub-chain into a buffer and merge all tags from
2750 // the extra chain, which aren't there yet.
2751 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2752 foreach ($extrachain as $extratag)
2753 if (!tagOnChain ($extratag, $newchain))
2754 $newchain[] = $extratag;
2755 // Then minimize the working buffer and check if it differs from the original
2756 // chain we started with. If it is so, save the work and signal the upper layer.
2757 $newchain = getExplicitTagsOnly ($newchain);
2758 if (tagChainCmp ($oldchain, $newchain))
2759 {
01b6b4d6 2760 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
2761 foreach ($newchain as $taginfo)
2762 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2763 return TRUE;
2764 }
2765 return FALSE;
351c0966
DO
2766}
2767
2768// Presume, that the target record has no tags attached.
2769function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2770{
2771 if (!count ($tagidlist))
c63a8d6e
DO
2772 return '';
2773 if (!$last_insert_id)
2774 $last_insert_id = lastInsertID();
2775 $errcount = 0;
abef7149 2776 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 2777 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
2778 $errcount++;
2779 if (!$errcount)
2780 return '';
2781 else
2782 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2783}
2784
42023f03
DO
2785function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2786{
2787 // $range is in x.x.x.x/x format, split into ip/mask vars
2788 $rangeArray = explode('/', $range);
2789 if (count ($rangeArray) != 2)
2790 return "Invalid IPv4 prefix '${range}'";
2791 $ip = $rangeArray[0];
2792 $mask = $rangeArray[1];
2793
59a83bd8 2794 if (!strlen ($ip) or !strlen ($mask))
42023f03
DO
2795 return "Invalid IPv4 prefix '${range}'";
2796 $ipL = ip2long($ip);
2797 $maskL = ip2long($mask);
2798 if ($ipL == -1 || $ipL === FALSE)
2799 return 'Bad IPv4 address';
2800 if ($mask < 32 && $mask > 0)
2801 $maskL = $mask;
2802 else
2803 {
2804 $maskB = decbin($maskL);
2805 if (strlen($maskB)!=32)
2806 return 'Invalid netmask';
2807 $ones=0;
2808 $zeroes=FALSE;
2809 foreach( str_split ($maskB) as $digit)
2810 {
2811 if ($digit == '0')
2812 $zeroes = TRUE;
2813 if ($digit == '1')
2814 {
2815 $ones++;
2816 if ($zeroes == TRUE)
2817 return 'Invalid netmask';
2818 }
2819 }
2820 $maskL = $ones;
2821 }
2822 $binmask = binMaskFromDec($maskL);
2823 $ipL = $ipL & $binmask;
357eb2ea 2824 $result = usePreparedInsertBlade
42023f03 2825 (
706ce117 2826 'IPv4Network',
42023f03
DO
2827 array
2828 (
2829 'ip' => sprintf ('%u', $ipL),
357eb2ea
DO
2830 'mask' => $maskL,
2831 'name' => $name
42023f03
DO
2832 )
2833 );
e782fca4
DO
2834 if ($result != TRUE)
2835 return "Could not add ${range} (already exists?).";
42023f03
DO
2836
2837 if ($is_bcast and $maskL < 31)
2838 {
2839 $network_addr = long2ip ($ipL);
2840 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2841 updateAddress ($network_addr, 'network', 'yes');
2842 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2843 }
351c0966 2844 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
2845}
2846
706ce117 2847// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
2848function destroyIPv4Prefix ($id = 0)
2849{
6657739e 2850 releaseFiles ('ipv4net', $id);
e34dac4f 2851 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
42023f03 2852 return __FUNCTION__ . ': SQL query #1 failed';
0da3bf00 2853 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
2854 return __FUNCTION__ . ': SQL query #2 failed';
2855 return '';
2856}
2857
ebae41b3
DO
2858function loadScript ($name)
2859{
e34dac4f 2860 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
ebae41b3 2861 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
2862 if ($row !== FALSE)
2863 return $row[0];
2864 else
2865 return NULL;
ebae41b3
DO
2866}
2867
178fda20 2868function saveScript ($name = '', $text)
ebae41b3 2869{
59a83bd8 2870 if (!strlen ($name))
c5f84f48 2871 throw new InvalidArgException ('$name', $name);
bb09f49c 2872 return usePreparedExecuteBlade
ebae41b3 2873 (
bb09f49c
DO
2874 'INSERT INTO Script (script_name, script_text) VALUES (?, ?) ' .
2875 'ON DUPLICATE KEY UPDATE script_text=?',
2876 array ($name, $text, $text)
ebae41b3
DO
2877 );
2878}
2879
d983f70a
DO
2880function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2881{
2882 if (NULL === getIPv4AddressNetworkId ($localip))
2883 return "$localip: Non existant ip";
0929db7f 2884 if (NULL === getIPv4AddressNetworkId ($remoteip))
d983f70a
DO
2885 return "$remoteip: Non existant ip";
2886 if ( ($localport <= 0) or ($localport >= 65536) )
2887 return "$localport: invaild port";
2888 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
2889 return "$remoteport: invaild port";
2890
a5c589d2 2891 $result = usePreparedExecuteBlade
d983f70a 2892 (
a5c589d2
DO
2893 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
2894 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
d983f70a
DO
2895 array
2896 (
a5c589d2
DO
2897 $object_id,
2898 $localip,
2899 $remoteip,
2900 $localport,
2901 $remoteport,
2902 $proto,
2903 $description,
d983f70a
DO
2904 )
2905 );
a5c589d2 2906 return $result !== FALSE ? '' : (__FUNCTION__ . '(): failed to insert the rule');
d983f70a
DO
2907}
2908
2909function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
2910{
a5c589d2
DO
2911 return usePreparedExecuteBlade
2912 (
2913 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
2914 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
2915 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2916 );
d983f70a
DO
2917}
2918
2919function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2920{
a5c589d2
DO
2921 return usePreparedExecuteBlade
2922 (
2923 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
2924 'AND localport=? AND remoteport=? AND proto=?',
2925 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2926 );
d983f70a
DO
2927}
2928
2929function getNATv4ForObject ($object_id)
2930{
2931 $ret = array();
2932 $ret['out'] = array();
2933 $ret['in'] = array();
e34dac4f
DO
2934 $result = usePreparedSelectBlade
2935 (
d983f70a
DO
2936 "select ".
2937 "proto, ".
2938 "INET_NTOA(localip) as localip, ".
2939 "localport, ".
2940 "INET_NTOA(remoteip) as remoteip, ".
2941 "remoteport, ".
2942 "ipa1.name as local_addr_name, " .
2943 "ipa2.name as remote_addr_name, " .
2944 "description ".
706ce117
DO
2945 "from IPv4NAT ".
2946 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
2947 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
e34dac4f
DO
2948 "where object_id=? ".
2949 "order by localip, localport, proto, remoteip, remoteport",
2950 array ($object_id)
2951 );
d983f70a
DO
2952 $count=0;
2953 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2954 {
2955 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
2956 $ret['out'][$count][$cname] = $row[$cname];
2957 $count++;
2958 }
d983f70a
DO
2959 unset ($result);
2960
e34dac4f
DO
2961 $result = usePreparedSelectBlade
2962 (
d983f70a
DO
2963 "select ".
2964 "proto, ".
2965 "INET_NTOA(localip) as localip, ".
2966 "localport, ".
2967 "INET_NTOA(remoteip) as remoteip, ".
2968 "remoteport, ".
706ce117 2969 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
2970 "RackObject.name as object_name, ".
2971 "description ".
706ce117 2972 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
e34dac4f
DO
2973 "where IPv4Allocation.object_id=? ".
2974 "order by remoteip, remoteport, proto, localip, localport",
2975 array ($object_id)
2976 );
d983f70a
DO
2977 $count=0;
2978 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2979 {
2980 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
2981 $ret['in'][$count][$cname] = $row[$cname];
2982 $count++;
2983 }
d983f70a
DO
2984 return $ret;
2985}
2986
178fda20 2987// Return a list of files, which are not linked to the specified record. This list
121496b6 2988// will be used by printSelect().
e1ae3fb4
AD
2989function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
2990{
e34dac4f
DO
2991 $query = usePreparedSelectBlade
2992 (
121496b6 2993 'SELECT id, name FROM File ' .
e1ae3fb4 2994 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
e34dac4f
DO
2995 'ORDER BY name, id',
2996 array ($entity_type, $entity_id)
2997 );
e1ae3fb4 2998 $ret=array();
e1ae3fb4 2999 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3000 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3001 return $ret;
3002}
3003
6df2025d
DO
3004// FIXME: return a standard cell list, so upper layer can iterate over
3005// it conveniently.
e1ae3fb4
AD
3006function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3007{
e34dac4f
DO
3008 $query = usePreparedSelectBlade
3009 (
e1ae3fb4
AD
3010 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3011 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
e34dac4f
DO
3012 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3013 array ($entity_type, $entity_id)
3014 );
e1ae3fb4
AD
3015 $ret = array();
3016 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3017 $ret[$row['file_id']] = array (
b3567368 3018 'id' => $row['file_id'],
e1ae3fb4
AD
3019 'link_id' => $row['link_id'],
3020 'name' => $row['name'],
3021 'type' => $row['type'],
3022 'size' => $row['size'],
3023 'ctime' => $row['ctime'],
3024 'mtime' => $row['mtime'],
3025 'atime' => $row['atime'],
3026 'comment' => $row['comment'],
3027 );
3028 return $ret;
3029}
3030
3031function getFile ($file_id = 0)
3032{
6cfedb71
DO
3033 $query = usePreparedSelectBlade
3034 (
3035 'SELECT id, name, type, size, ctime, mtime, atime, contents, comment ' .
3036 'FROM File WHERE id = ?',
3037 array ($file_id)
3038 );
e1ae3fb4
AD
3039 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3040 {
0cc24e9a 3041 showWarning ('Query succeeded, but returned no data', __FUNCTION__);
e1ae3fb4
AD
3042 $ret = NULL;
3043 }
3044 else
3045 {
3046 $ret = array();
3047 $ret['id'] = $row['id'];
3048 $ret['name'] = $row['name'];
3049 $ret['type'] = $row['type'];
3050 $ret['size'] = $row['size'];
3051 $ret['ctime'] = $row['ctime'];
3052 $ret['mtime'] = $row['mtime'];
3053 $ret['atime'] = $row['atime'];
3054 $ret['contents'] = $row['contents'];
3055 $ret['comment'] = $row['comment'];
bed9cd76 3056 $query->closeCursor();
e1ae3fb4 3057
deb3da1b 3058 // Someone accessed this file, update atime
6cfedb71 3059 usePreparedExecuteBlade ('UPDATE File SET atime = ? WHERE id = ?', array (date ('YmdHis'), $file_id));
e1ae3fb4 3060 }
e1ae3fb4
AD
3061 return $ret;
3062}
3063
e1ae3fb4
AD
3064function getFileLinks ($file_id = 0)
3065{
6cfedb71
DO
3066 $query = usePreparedSelectBlade
3067 (
3068 'SELECT id, file_id, entity_type, entity_id FROM FileLink ' .
3069 'WHERE file_id = ? ORDER BY entity_type, entity_id',
3070 array ($file_id)
3071 );
da3302ab 3072 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3073 $ret = array();
da3302ab 3074 foreach ($rows as $row)
e1ae3fb4
AD
3075 {
3076 // get info of the parent
3077 switch ($row['entity_type'])
3078 {
3079 case 'ipv4net':
3080 $page = 'ipv4net';
3081 $id_name = 'id';
d724d290 3082 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3083 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3084 break;
3085 case 'ipv4rspool':
3854af78 3086 $page = 'ipv4rspool';
e1ae3fb4 3087 $id_name = 'pool_id';
a6e91ac2 3088 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3089 $name = $parent['name'];
3090 break;
3091 case 'ipv4vs':
3092 $page = 'ipv4vs';
3093 $id_name = 'vs_id';
7c38462f 3094 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3095 $name = $parent['name'];
3096 break;
3097 case 'object':
3098 $page = 'object';
3099 $id_name = 'object_id';
6297d584 3100 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
7ddbcf59 3101 $name = $parent['dname'];
e1ae3fb4
AD
3102 break;
3103 case 'rack':
3104 $page = 'rack';
3105 $id_name = 'rack_id';
61a1d996 3106 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3107 $name = $parent['name'];
3108 break;
3109 case 'user':
3110 $page = 'user';
3111 $id_name = 'user_id';
0b2c74cb
DO
3112 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3113 $name = $parent['user_name'];
e1ae3fb4
AD
3114 break;
3115 }
3116
17d95c32 3117 // name needs to have some value for hrefs to work
59a83bd8 3118 if (!strlen ($name))
17d95c32
AD
3119 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3120
e1ae3fb4
AD
3121 $ret[$row['id']] = array(
3122 'page' => $page,
3123 'id_name' => $id_name,
3124 'entity_type' => $row['entity_type'],
3125 'entity_id' => $row['entity_id'],
3126 'name' => $name
3127 );
3128 }
3129 return $ret;
3130}
3131
0b97b8f0 3132function getFileStats ()
e1ae3fb4 3133{
e34dac4f 3134 $result = usePreparedSelectBlade ('SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type');
e1ae3fb4 3135 $ret = array();
e1ae3fb4
AD
3136 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3137 if ($row['count'] > 0)
0b97b8f0
DO
3138 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3139 unset ($result);
e1ae3fb4
AD
3140
3141 // Find number of files without any linkage
e34dac4f
DO
3142 $result = usePreparedSelectBlade
3143 (
e1ae3fb4
AD
3144 'SELECT COUNT(*) ' .
3145 'FROM File ' .
27b2ae0d 3146 'WHERE id NOT IN (SELECT file_id FROM FileLink)'
e34dac4f 3147 );
0b97b8f0
DO
3148 $ret["Unattached files"] = $result->fetchColumn ();
3149 unset ($result);
e1ae3fb4
AD
3150
3151 // Find total number of files
e34dac4f 3152 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM File');
0b97b8f0 3153 $ret["Total files"] = $result->fetchColumn ();
e1ae3fb4 3154
e1ae3fb4
AD
3155 return $ret;
3156}
3157
3158function commitAddFile ($name, $type, $size, $contents, $comment)
3159{
3160 $now = date('YmdHis');
3161
3162 global $dbxlink;
3163 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3164 $query->bindParam(1, $name);
3165 $query->bindParam(2, $type);
3166 $query->bindParam(3, $size);
3167 $query->bindParam(4, $now);
3168 $query->bindParam(5, $now);
3169 $query->bindParam(6, $now);
3170 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3171 $query->bindParam(8, $comment);
6cfedb71
DO
3172 try
3173 {
3174 return $query->execute();
3175 }
3176 catch (PDOException $e)
3177 {
3178 throw convertPDOException ($e);
3179 }
e1ae3fb4
AD
3180}
3181
4a2c6c6b 3182function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4 3183{
6cfedb71
DO
3184 return usePreparedExecuteBlade
3185 (
3186 'INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)',
3187 array ($file_id, $entity_type, $entity_id)
3188 );
e1ae3fb4
AD
3189}
3190
f8874cdb 3191function commitReplaceFile ($file_id = 0, $contents)
fd1fb420 3192{
fd1fb420 3193 global $dbxlink;
f8874cdb
DO
3194 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3195 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3196 $query->bindParam(2, $file_id);
fd1fb420 3197
6cfedb71
DO
3198 try
3199 {
3200 return $query->execute();
3201 }
3202 catch (PDOException $e)
3203 {
3204 throw convertPDOException ($e);
3205 }
fd1fb420
AD
3206}
3207
9db67d95 3208function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
e1ae3fb4 3209{
c5f84f48
DY
3210 if (!strlen ($new_name))
3211 throw new InvalidArgException ('$new_name', $new_name);
3212 if (!strlen ($new_type))
3213 throw new InvalidArgException ('$new_type', $new_type);
6cfedb71
DO
3214 return usePreparedExecuteBlade
3215 (
3216 'UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?',
3217 array ($new_name, $new_type, $new_comment, $file_id)
3218 );
e1ae3fb4
AD
3219}
3220
3221function commitUnlinkFile ($link_id)
3222{
e34dac4f 3223 if (usePreparedDeleteBlade ('FileLink', array ('id' => $link_id)) === FALSE)
9589714d 3224 return __FUNCTION__ . '(): query failed';
e1ae3fb4
AD
3225 return '';
3226}
3227
3228function commitDeleteFile ($file_id)
3229{
29c3a4d8 3230 destroyTagsForEntity ('file', $file_id);
e34dac4f 3231 if (usePreparedDeleteBlade ('File', array ('id' => $file_id)) === FALSE)
9589714d 3232 return __FUNCTION__ . '(): query failed';
e1ae3fb4
AD
3233 return '';
3234}
3235
4034ab9e
DO
3236function getChapterList ()
3237{
3238 $ret = array();
e34dac4f
DO
3239 $result = usePreparedSelectBlade
3240 (
3241 'SELECT id, sticky, name, count(chapter_id) as wordc ' .
3242 'FROM Chapter LEFT JOIN Dictionary ON Chapter.id = chapter_id ' .
3243 'GROUP BY id ORDER BY name'
3244 );
4034ab9e 3245 while ($row = $result->fetch (PDO::FETCH_ASSOC))
c4d0dc30 3246 $ret[$row['id']] = $row;
4034ab9e
DO
3247 return $ret;
3248}
3249
2d1e6b63 3250// Return file id by file name.
72d2a7ee
DO
3251function findFileByName ($filename)
3252{
6cfedb71 3253 $query = usePreparedSelectBlade ('SELECT id FROM File WHERE name = ?', array ($filename));
2d1e6b63 3254 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
72d2a7ee 3255 return $row['id'];
2d1e6b63
AD
3256
3257 return NULL;
72d2a7ee
DO
3258}
3259
9133d2c5
DO
3260function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3261{
3262 global $dbxlink;
3263 $dbxlink->beginTransaction();
e34dac4f
DO
3264 $result = usePreparedSelectBlade
3265 (
3266 'SELECT TIMESTAMPDIFF(SECOND, first_success, now()) AS success_age, ' .
3267 'TIMESTAMPDIFF(SECOND, last_retry, now()) AS retry_age, displayed_name, memberof ' .
3268 'FROM LDAPCache WHERE presented_username = ? AND successful_hash = ? ' .
3269 'HAVING success_age < ? FOR UPDATE',
3270 array ($form_username, $password_hash, $expiry)
3271 );
9133d2c5
DO
3272 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3273 {
3274 $row['memberof'] = unserialize (base64_decode ($row['memberof']));
3275 return $row;
3276 }
3277 return NULL;
3278}
3279
3280function releaseLDAPCache ()
3281{
3282 global $dbxlink;
3283 $dbxlink->commit();
3284}
3285
3286// This actually changes only last_retry.
3287function touchLDAPCacheRecord ($form_username)
3288{
a5c589d2 3289 return usePreparedExecuteBlade ('UPDATE LDAPCache SET last_retry=NOW() WHERE presented_username=?', array ($form_username));
9133d2c5
DO
3290}
3291
3292function replaceLDAPCacheRecord ($form_username, $password_hash, $dname, $memberof)
3293{
3294 deleteLDAPCacheRecord ($form_username);
e34dac4f 3295 usePreparedInsertBlade ('LDAPCache',
9133d2c5
DO
3296 array
3297 (
e34dac4f
DO
3298 'presented_username' => $form_username,
3299 'successful_hash' => $password_hash,
3300 'displayed_name' => $dname,
3301 'memberof' => base64_encode (serialize ($memberof)),
9133d2c5
DO
3302 )
3303 );
3304}
3305
3306function deleteLDAPCacheRecord ($form_username)
3307{
e34dac4f 3308 return usePreparedDeleteBlade ('LDAPCache', array ('presented_username' => $form_username));
9133d2c5
DO
3309}
3310
f3371850
DO
3311// Age all records older, than cache_expiry seconds, and all records made in future.
3312// Calling this function w/o argument purges the whole LDAP cache.
3313function discardLDAPCache ($maxage = 0)
ef44d4a3 3314{
a5c589d2 3315 return usePreparedExecuteBlade ('DELETE from LDAPCache WHERE TIMESTAMPDIFF(SECOND, first_success, NOW()) >= ? or NOW() < first_success', array ($maxage));
ef44d4a3
DO
3316}
3317
b82cce3f
DO
3318function getUserIDByUsername ($username)
3319{
e34dac4f 3320 $result = usePreparedSelectBlade ('SELECT user_id FROM UserAccount WHeRE user_name = ?', array ($username));
b82cce3f
DO
3321 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3322 return $row['user_id'];
3323 return NULL;
3324}
3325
029a14bc
DO
3326// Return TRUE, if the given address is assigned to a port of any object
3327// except the current object. Using this function as a constraint makes
3328// it possible to reuse L2 addresses within one object, yet keeping them
3329// universally unique on the other hand.
3330function alreadyUsedL2Address ($address, $my_object_id)
3331{
e34dac4f
DO
3332 $result = usePreparedSelectBlade
3333 (
3334 'SELECT COUNT(*) FROM Port WHERE BINARY l2address = ? AND object_id != ?',
3335 array ($address, $my_object_id)
3336 );
029a14bc
DO
3337 $row = $result->fetch (PDO::FETCH_NUM);
3338 return $row[0] != 0;
3339}
3340
2dfa1b73 3341function getPortInterfaceCompat()
3153a326 3342{
e34dac4f
DO
3343 $result = usePreparedSelectBlade
3344 (
3345 'SELECT iif_id, iif_name, oif_id, dict_value AS oif_name ' .
3153a326
DO
3346 'FROM PortInterfaceCompat INNER JOIN PortInnerInterface ON id = iif_id ' .
3347 'INNER JOIN Dictionary ON dict_key = oif_id ' .
e34dac4f
DO
3348 'ORDER BY iif_name, oif_name'
3349 );
2dfa1b73 3350 return $result->fetchAll (PDO::FETCH_ASSOC);
3153a326
DO
3351}
3352
3353// Return a set of options for a plain SELECT. These options include the current
3354// OIF of the given port and all OIFs of its permanent IIF.
3355function getExistingPortTypeOptions ($port_id)
3356{
e34dac4f
DO
3357 $result = usePreparedSelectBlade
3358 (
3359 'SELECT oif_id, dict_value AS oif_name ' .
3153a326 3360 'FROM PortInterfaceCompat INNER JOIN Dictionary ON oif_id = dict_key ' .
e34dac4f
DO
3361 'WHERE iif_id = (SELECT iif_id FROM Port WHERE id = ?) ' .
3362 'ORDER BY oif_name',
3363 array ($port_id)
3364 );
3153a326
DO
3365 $ret = array();
3366 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3367 $ret[$row['oif_id']] = $row['oif_name'];
3368 return $ret;
3369}
3370
2dfa1b73
DO
3371function getPortIIFOptions()
3372{
3373 $ret = array();
e34dac4f 3374 $result = usePreparedSelectBlade ('SELECT id, iif_name FROM PortInnerInterface ORDER BY iif_name');
2dfa1b73
DO
3375 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3376 $ret[$row['id']] = $row['iif_name'];
3377 return $ret;
3378}
3379
3380function commitSupplementPIC ($iif_id, $oif_id)
3381{
e34dac4f 3382 return usePreparedInsertBlade
2dfa1b73
DO
3383 (
3384 'PortInterfaceCompat',
3385 array ('iif_id' => $iif_id, 'oif_id' => $oif_id)
3386 );
3387}
3388
3389function commitReducePIC ($iif_id, $oif_id)
3390{
e34dac4f 3391 return usePreparedDeleteBlade ('PortInterfaceCompat', array ('iif_id' => $iif_id, 'oif_id' => $oif_id));
2dfa1b73
DO
3392}
3393
27ec21b2
DO
3394function getPortIIFStats ($args)
3395{
e34dac4f
DO
3396 $result = usePreparedSelectBlade
3397 (
3398 'SELECT dict_value AS title, COUNT(id) AS max, ' .
27ec21b2
DO
3399 'COUNT(reservation_comment) + ' .
3400 'SUM((SELECT COUNT(*) FROM Link WHERE id IN (porta, portb))) AS current ' .
3401 'FROM Port INNER JOIN Dictionary ON type = dict_key ' .
e34dac4f
DO
3402 'WHERE iif_id = ? GROUP BY type',
3403 array (current ($args))
3404 );
27ec21b2
DO
3405 return $result->fetchAll (PDO::FETCH_ASSOC);
3406}
3407
cd3775e9
DO
3408function getPortInfo ($port_id)
3409{
e34dac4f
DO
3410 $result = usePreparedSelectBlade
3411 (
3412 "SELECT object_id, name, iif_id, type AS oif_id, l2address, ".
cd3775e9 3413 "(SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, " .
b3247480 3414 "(SELECT COUNT(*) FROM Link WHERE id IN (porta, portb)) AS linked, " .
cd3775e9 3415 "(SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name " .
e34dac4f
DO
3416 "FROM Port WHERE id = ?",
3417 array ($port_id)
3418 );
cd3775e9
DO
3419 return $result->fetch (PDO::FETCH_ASSOC);
3420}
3421
87cca0c2 3422function getVLANDomainStats ()
8198f2c6 3423{
e34dac4f
DO
3424 $result = usePreparedSelectBlade
3425 (
3426 'SELECT id, description, ' .
8198f2c6 3427 '(SELECT COUNT(vlan_id) FROM VLANDescription WHERE domain_id = id) AS vlanc, ' .
b5ac48d0 3428 '(SELECT COUNT(ipv4net_id) FROM VLANIPv4 WHERE domain_id = id) AS ipv4netc, ' .
6affe3b9
DO
3429 '(SELECT COUNT(object_id) FROM VLANSwitch WHERE domain_id = id) AS switchc, ' .
3430 '(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
3431 'FROM VLANDomain ORDER BY description'
3432 );
8198f2c6
DO
3433 $ret = array();
3434 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3435 $ret[$row['id']] = $row;
3436 return $ret;
3437}
3438
e829e76b
DO
3439function getVLANDomainOptions()
3440{
e34dac4f 3441 $result = usePreparedSelectBlade ('SELECT id, description FROM VLANDomain ORDER BY description');
e829e76b
DO
3442 $ret = array();
3443 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3444 $ret[$row['id']] = $row['description'];
3445 return $ret;
3446}
3447
8877c14a 3448function getVLANDomain ($vdid)
8198f2c6 3449{
8877c14a
DO
3450 $result = usePreparedSelectBlade ('SELECT id, description FROM VLANDomain WHERE id = ?', array ($vdid));
3451 if (!$ret = $result->fetch (PDO::FETCH_ASSOC))
3452 throw new EntityNotFoundException ('VLAN domain', $vdid);
3453 unset ($result);
3454 $ret['vlanlist'] = getDomainVLANs ($vdid);
960ab00b
DO
3455 $ret['switchlist'] = array();
3456 $result = usePreparedSelectBlade
3457 (
3458 'SELECT object_id, template_id, last_errno, out_of_sync, ' .
3459 'TIMESTAMPDIFF(SECOND, last_change, NOW()) AS age_seconds ' .
3460 'FROM VLANSwitch WHERE domain_id = ? ORDER BY object_id',
3461 array ($vdid)
3462 );
3463 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3464 $ret['switchlist'][$row['object_id']] = $row;
8877c14a 3465 return $ret;
8198f2c6
DO
3466}
3467
3468function getDomainVLANs ($vdom_id)
3469{
e34dac4f 3470 $result = usePreparedSelectBlade
cbf78395 3471 (
94496ec7 3472 'SELECT vlan_id, vlan_type, vlan_descr, ' .
49e07479
DO
3473 '(SELECT COUNT(ipv4net_id) FROM VLANIPv4 WHERE domain_id = ? AND vlan_id = VD.vlan_id) AS netc, ' .
3474 '(SELECT COUNT(port_name) FROM VLANSwitch AS VS INNER JOIN PortAllowedVLAN AS PAV ' .
3475 '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
3476 'FROM VLANDescription AS VD ' .
3477 'WHERE domain_id = ? ' .
e34dac4f
DO
3478 'ORDER BY vlan_id',
3479 array ($vdom_id, $vdom_id, $vdom_id)
cbf78395 3480 );
8198f2c6 3481 $ret = array();
35ccd01d 3482 while ($row = $result->fetch (PDO::FETCH_ASSOC))
8198f2c6
DO
3483 $ret[$row['vlan_id']] = $row;
3484 return $ret;
3485}
3486
8198f2c6
DO
3487function commitReduceVLANDescription ($vdom_id, $vlan_id)
3488{
a822926c
DO
3489 return usePreparedDeleteBlade
3490 (
3491 'VLANDescription',
3492 array