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