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