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