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