r3196 - peekNode(): also fix in trunk
[racktables] / inc / database.php
CommitLineData
b325120a 1<?php
e673ee24
DO
2/*
3*
4* This file is a library of database access functions for RackTables.
5*
6*/
7
a6e91ac2
DO
8$SQLSchema = array
9(
10 'object' => array
11 (
12 'table' => 'RackObject',
13 'columns' => array
14 (
15 'id' => 'id',
16 'name' => 'name',
17 'label' => 'label',
18 'barcode' => 'barcode',
19 'asset_no' => 'asset_no',
20 'objtype_id' => 'objtype_id',
21 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
22 'Rack_name' => '(select name from Rack where id = rack_id)',
23 'row_id' => '(select row_id from Rack where id = rack_id)',
24 'Row_name' => '(select name from RackRow where id = row_id)',
0d993afe 25 'has_problems' => 'has_problems',
6657739e 26 'comment' => 'comment',
6d472f26 27 'nports' => '(SELECT COUNT(*) FROM Port WHERE object_id = RackObject.id)',
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
27ec21b2 1711function removePortOIFCompat ($type1 = 0, $type2 = 0)
e673ee24
DO
1712{
1713 global $dbxlink;
0cc24e9a
DY
1714 if ($type1 <= 0)
1715 throw new InvalidArgException ('type1', $type1);
1716 if ($type2 <= 0)
1717 throw new InvalidArgException ('type2', $type2);
e7aa0333 1718 $dbxlink->query ("DELETE FROM PortCompat WHERE type1 = ${type1} AND type2 = ${type2}");
e673ee24
DO
1719 return TRUE;
1720}
1721
27ec21b2 1722function addPortOIFCompat ($type1 = 0, $type2 = 0)
e673ee24 1723{
0cc24e9a
DY
1724 if ($type1 <= 0)
1725 throw new InvalidArgException ('type1', $type1);
1726 if ($type2 <= 0)
1727 throw new InvalidArgException ('type2', $type2);
e673ee24
DO
1728 return useInsertBlade
1729 (
1730 'PortCompat',
1731 array ('type1' => $type1, 'type2' => $type2)
1732 );
1733}
1734
da95280e
DO
1735function getDictStats ()
1736{
63811a09 1737 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
da95280e 1738 $query =
10bac82a 1739 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
6530f34e 1740 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id";
8a5a4555 1741 $result = useSelectBlade ($query);
da95280e 1742 $tc = $tw = $uc = $uw = 0;
89fa639f 1743 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1744 {
1745 $tc++;
1746 $tw += $row['wc'];;
1747 if (in_array ($row['chapter_no'], $stock_chapters))
1748 continue;
1749 $uc++;
1750 $uw += $row['wc'];;
1751 }
89fa639f
DO
1752 $result->closeCursor();
1753 unset ($result);
a5efc857 1754 $query = "select count(object_id) as attrc from RackObject as ro left join " .
08b4cb24 1755 "AttributeValue as av on ro.id = av.object_id group by ro.id";
8a5a4555 1756 $result = useSelectBlade ($query);
08b4cb24 1757 $to = $ta = $so = 0;
89fa639f 1758 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1759 {
1760 $to++;
1761 if ($row['attrc'] != 0)
1762 {
1763 $so++;
1764 $ta += $row['attrc'];
1765 }
1766 }
89fa639f 1767 $result->closeCursor();
da95280e
DO
1768 $ret = array();
1769 $ret['Total chapters in dictionary'] = $tc;
1770 $ret['Total words in dictionary'] = $tw;
1771 $ret['User chapters'] = $uc;
1772 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1773 $ret['Total objects'] = $to;
1774 $ret['Objects with stickers'] = $so;
1775 $ret['Total stickers attached'] = $ta;
da95280e
DO
1776 return $ret;
1777}
1778
6807f0be 1779function getIPv4Stats ()
9ec5fdf1 1780{
9ec5fdf1
DO
1781 $ret = array();
1782 $subject = array();
706ce117
DO
1783 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1784 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1785 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1786 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1787 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1788 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1789 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1790 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
9ec5fdf1
DO
1791
1792 foreach ($subject as $item)
1793 {
8a5a4555 1794 $result = useSelectBlade ($item['q']);
9ec5fdf1
DO
1795 $row = $result->fetch (PDO::FETCH_NUM);
1796 $ret[$item['txt']] = $row[0];
1797 $result->closeCursor();
1798 unset ($result);
1799 }
1800 return $ret;
1801}
1802
6807f0be 1803function getRackspaceStats ()
9ec5fdf1 1804{
9ec5fdf1
DO
1805 $ret = array();
1806 $subject = array();
10bac82a 1807 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
9ec5fdf1
DO
1808 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1809 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1810 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1811
1812 foreach ($subject as $item)
1813 {
8a5a4555 1814 $result = useSelectBlade ($item['q']);
9ec5fdf1 1815 $row = $result->fetch (PDO::FETCH_NUM);
59a83bd8 1816 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1817 $result->closeCursor();
1818 unset ($result);
1819 }
1820 return $ret;
1821}
1822
6807f0be
DO
1823/*
1824
1825The following allows figuring out records in TagStorage, which refer to non-existing entities:
1826
120e9ddd
DO
1827mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1828mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1829mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1830mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1831mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1832mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1833mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
6807f0be
DO
1834
1835Accordingly, these are the records, which refer to non-existent tags:
1836
1837mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1838
1839*/
1840
826c3dbd 1841// chapter_no is a must, see at @commitReduceDictionary() why
e673ee24
DO
1842function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1843{
c5f84f48
DY
1844 if ($chapter_no <= 0)
1845 throw new InvalidArgException ('$chapter_no', $chapter_no);
1846 if ($dict_key <= 0)
1847 throw new InvalidArgException ('$dict_key', $dict_key);
1848 if (!strlen ($dict_value))
1849 throw new InvalidArgException ('$dict_value', $dict_value);
1850
e673ee24
DO
1851 global $dbxlink;
1852 $query =
10bac82a 1853 "update Dictionary set dict_value = '${dict_value}' where chapter_id=${chapter_no} " .
e673ee24
DO
1854 "and dict_key=${dict_key} limit 1";
1855 $result = $dbxlink->query ($query);
e673ee24
DO
1856 return TRUE;
1857}
1858
1859function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1860{
c5f84f48
DY
1861 if ($chapter_no <= 0)
1862 throw new InvalidArgException ('$chapter_no', $chapter_no);
1863 if (!strlen ($dict_value))
1864 throw new InvalidArgException ('$dict_value', $dict_value);
e673ee24
DO
1865 return useInsertBlade
1866 (
1867 'Dictionary',
10bac82a 1868 array ('chapter_id' => $chapter_no, 'dict_value' => "'${dict_value}'")
e673ee24
DO
1869 );
1870}
1871
178fda20
DO
1872// Technically dict_key is enough to delete, but including chapter_id into
1873// WHERE clause makes sure, that the action actually happends for the same
1874// chapter, which authorization was granted for.
e673ee24
DO
1875function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1876{
e673ee24
DO
1877 global $dbxlink;
1878 $query =
10bac82a 1879 "delete from Dictionary where chapter_id=${chapter_no} " .
e673ee24
DO
1880 "and dict_key=${dict_key} limit 1";
1881 $result = $dbxlink->query ($query);
e673ee24
DO
1882 return TRUE;
1883}
1884
1885function commitAddChapter ($chapter_name = '')
1886{
59a83bd8 1887 if (!strlen ($chapter_name))
c5f84f48 1888 throw new InvalidArgException ('$chapter_name', $chapter_name);
e673ee24
DO
1889 return useInsertBlade
1890 (
1891 'Chapter',
10bac82a 1892 array ('name' => "'${chapter_name}'")
e673ee24
DO
1893 );
1894}
1895
1896function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1897{
178fda20 1898 if (!strlen ($chapter_name))
c5f84f48 1899 throw new InvalidArgException ('$chapter_name', $chapter_name);
e673ee24
DO
1900 global $dbxlink;
1901 $query =
10bac82a 1902 "update Chapter set name = '${chapter_name}' where id = ${chapter_no} " .
e673ee24
DO
1903 "and sticky = 'no' limit 1";
1904 $result = $dbxlink->query ($query);
e673ee24
DO
1905 return TRUE;
1906}
1907
1908function commitDeleteChapter ($chapter_no = 0)
1909{
e673ee24
DO
1910 global $dbxlink;
1911 $query =
10bac82a 1912 "delete from Chapter where id = ${chapter_no} and sticky = 'no' limit 1";
e673ee24 1913 $result = $dbxlink->query ($query);
e673ee24
DO
1914 return TRUE;
1915}
1916
4c330a14
DO
1917// This is a dictionary accessor. We perform link rendering, so the user sees
1918// nice <select> drop-downs.
7fa7047a 1919function readChapter ($chapter_id = 0, $style = '')
e673ee24 1920{
7fa7047a
DO
1921 if ($chapter_id <= 0)
1922 throw new InvalidArgException ('$chapter_id', $chapter_id);
e673ee24 1923 $query =
7fa7047a
DO
1924 "select dict_key, dict_value from Dictionary " .
1925 "where chapter_id = ${chapter_id}";
8a5a4555 1926 $result = useSelectBlade ($query);
e673ee24
DO
1927 $chapter = array();
1928 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7fa7047a 1929 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
e673ee24 1930 $result->closeCursor();
4aa8609b
DO
1931 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1932 asort ($chapter);
e673ee24
DO
1933 return $chapter;
1934}
1935
7fa7047a
DO
1936// Return refcounters for all given keys of the given chapter.
1937function getChapterRefc ($chapter_id, $keylist)
1938{
afdb3cf5
DO
1939 $ret = array();
1940 foreach ($keylist as $key)
1941 $ret[$key] = 0;
7fa7047a
DO
1942 switch ($chapter_id)
1943 {
1944 case CHAP_OBJTYPE:
1945 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
1946 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
1947 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ${chapter_id}";
1948 break;
1949 case CHAP_PORTTYPE:
93a83f51 1950 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
7fa7047a 1951 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
93a83f51 1952 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
7fa7047a
DO
1953 "from Dictionary where chapter_id = ${chapter_id}";
1954 break;
1955 default:
1956 // Find the list of all assigned values of dictionary-addressed attributes, each with
1957 // chapter/word keyed reference counters.
1958 $query = "select uint_value, count(object_id) as refcnt " .
1959 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1960 "inner join AttributeValue as av on a.id = av.attr_id " .
1961 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
1962 "where a.type = 'dict' and am.chapter_id = ${chapter_id} group by uint_value";
1963 break;
1964 }
8a5a4555 1965 $result = useSelectBlade ($query);
7fa7047a
DO
1966 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1967 $ret[$row['uint_value']] = $row['refcnt'];
1968 return $ret;
1969}
1970
e4e9e2a1
DO
1971// Return a list of all stickers with sticker map applied. Each sticker records will
1972// list all its ways on the map with refcnt set.
e673ee24
DO
1973function getAttrMap ()
1974{
e673ee24 1975 $query =
e4e9e2a1 1976 'SELECT id, type, name, chapter_id, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
7fa7047a 1977 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
e4e9e2a1
DO
1978 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
1979 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_id';
8a5a4555 1980 $result = useSelectBlade ($query);
e673ee24
DO
1981 $ret = array();
1982 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1983 {
e4e9e2a1
DO
1984 if (!isset ($ret[$row['id']]))
1985 $ret[$row['id']] = array
1986 (
1987 'id' => $row['id'],
1988 'type' => $row['type'],
1989 'name' => $row['name'],
1990 'application' => array(),
1991 );
e673ee24
DO
1992 if ($row['objtype_id'] == '')
1993 continue;
e4e9e2a1
DO
1994 $application = array
1995 (
1996 'objtype_id' => $row['objtype_id'],
e4e9e2a1
DO
1997 'refcnt' => $row['refcnt'],
1998 );
1999 if ($row['type'] == 'dict')
e673ee24 2000 {
50393983 2001 $application['chapter_no'] = $row['chapter_id'];
e673ee24
DO
2002 $application['chapter_name'] = $row['chapter_name'];
2003 }
e4e9e2a1 2004 $ret[$row['id']]['application'][] = $application;
e673ee24 2005 }
e673ee24
DO
2006 return $ret;
2007}
2008
2009function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2010{
0cc24e9a
DY
2011 if ($attr_id <= 0)
2012 throw new InvalidArgException ('$attr_id', $attr_id);
2013 if (!strlen ($attr_name))
2014 throw new InvalidArgException ('$attr_name', $attr_name);
2015
e673ee24
DO
2016 global $dbxlink;
2017 $query =
10bac82a
DY
2018 "update Attribute set name = '${attr_name}' " .
2019 "where id = ${attr_id} limit 1";
e673ee24 2020 $result = $dbxlink->query ($query);
e673ee24
DO
2021 return TRUE;
2022}
2023
2024function commitAddAttribute ($attr_name = '', $attr_type = '')
2025{
59a83bd8 2026 if (!strlen ($attr_name))
0cc24e9a 2027 throw new InvalidArgException ('$attr_name', $attr_name);
e673ee24
DO
2028 switch ($attr_type)
2029 {
2030 case 'uint':
2031 case 'float':
2032 case 'string':
2033 case 'dict':
2034 break;
2035 default:
0cc24e9a 2036 throw new InvalidArgException ('$attr_type', $attr_type, 'Attribute type not supported');
e673ee24
DO
2037 }
2038 return useInsertBlade
2039 (
2040 'Attribute',
10bac82a 2041 array ('name' => "'${attr_name}'", 'type' => "'${attr_type}'")
e673ee24
DO
2042 );
2043}
2044
2045function commitDeleteAttribute ($attr_id = 0)
2046{
2047 if ($attr_id <= 0)
0cc24e9a 2048 throw new InvalidArgException ('$attr_id', $attr_id);
10bac82a 2049 return useDeleteBlade ('Attribute', 'id', $attr_id);
e673ee24
DO
2050}
2051
2052// FIXME: don't store garbage in chapter_no for non-dictionary types.
2053function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2054{
0cc24e9a
DY
2055 if ($attr_id <= 0)
2056 throw new InvalidArgException ('$attr_id', $attr_id);
2057 if ($objtype_id <= 0)
2058 throw new InvalidArgException ('$objtype_id', $objtype_id);
2059
e673ee24
DO
2060 return useInsertBlade
2061 (
2062 'AttributeMap',
2063 array
2064 (
2065 'attr_id' => $attr_id,
2066 'objtype_id' => $objtype_id,
10bac82a 2067 'chapter_id' => $chapter_no
e673ee24
DO
2068 )
2069 );
2070}
2071
2072function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2073{
0cc24e9a
DY
2074 if ($attr_id <= 0)
2075 throw new InvalidArgException ('$attr_id', $attr_id);
2076 if ($objtype_id <= 0)
2077 throw new InvalidArgException ('$objtype_id', $objtype_id);
e673ee24
DO
2078 global $dbxlink;
2079 $query =
2080 "delete from AttributeMap where attr_id=${attr_id} " .
2081 "and objtype_id=${objtype_id} limit 1";
2082 $result = $dbxlink->query ($query);
e673ee24
DO
2083 return TRUE;
2084}
2085
2086// This function returns all optional attributes for requested object
2087// as an array of records. NULL is returned on error and empty array
2088// is returned, if there are no attributes found.
7fa7047a 2089function getAttrValues ($object_id)
e673ee24
DO
2090{
2091 if ($object_id <= 0)
0cc24e9a 2092 throw new InvalidArgException ('$objtype_id', $objtype_id);
e673ee24
DO
2093 $ret = array();
2094 $query =
10bac82a 2095 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
7fa7047a 2096 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
e673ee24 2097 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
10bac82a 2098 "inner join Attribute as A on AM.attr_id = A.id " .
e673ee24 2099 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
10bac82a
DY
2100 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2101 "left join Chapter as C on AM.chapter_id = C.id " .
2102 "where RO.id = ${object_id} order by A.type, A.name";
8a5a4555 2103 $result = useSelectBlade ($query);
e673ee24
DO
2104 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2105 {
2106 $record = array();
2107 $record['id'] = $row['attr_id'];
2108 $record['name'] = $row['attr_name'];
2109 $record['type'] = $row['attr_type'];
2110 switch ($row['attr_type'])
2111 {
7fa7047a
DO
2112 case 'dict':
2113 $record['chapter_id'] = $row['chapter_id'];
2114 $record['chapter_name'] = $row['chapter_name'];
2115 $record['key'] = $row['uint_value'];
2116 // fall through
e673ee24
DO
2117 case 'uint':
2118 case 'float':
2119 case 'string':
24cbe8af 2120 $record['value'] = $row[$row['attr_type'] . '_value'];
7fa7047a 2121 $record['o_value'] = parseWikiLink ($record['value'], 'o');
24cbe8af
DO
2122 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2123 break;
e673ee24
DO
2124 default:
2125 $record['value'] = NULL;
2126 break;
2127 }
2128 $ret[$row['attr_id']] = $record;
2129 }
2130 $result->closeCursor();
2131 return $ret;
2132}
2133
2134function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2135{
0cc24e9a
DY
2136 if ($object_id <= 0)
2137 throw new InvalidArgException ('$objtype_id', $objtype_id);
2138 if ($attr_id <= 0)
2139 throw new InvalidArgException ('$attr_id', $attr_id);
e673ee24
DO
2140 global $dbxlink;
2141 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2142 $result = $dbxlink->query ($query);
e673ee24
DO
2143 return TRUE;
2144}
2145
2146// FIXME: don't share common code with use commitResetAttrValue()
2147function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2148{
0cc24e9a
DY
2149 if ($object_id <= 0)
2150 throw new InvalidArgException ('$objtype_id', $objtype_id);
2151 if ($attr_id <= 0)
2152 throw new InvalidArgException ('$attr_id', $attr_id);
59a83bd8 2153 if (!strlen ($value))
e673ee24
DO
2154 return commitResetAttrValue ($object_id, $attr_id);
2155 global $dbxlink;
10bac82a 2156 $query1 = "select type as attr_type from Attribute where id = ${attr_id}";
e673ee24 2157 $result = $dbxlink->query ($query1);
e673ee24 2158 $row = $result->fetch (PDO::FETCH_NUM);
e673ee24
DO
2159 $attr_type = $row[0];
2160 $result->closeCursor();
2161 switch ($attr_type)
2162 {
2163 case 'uint':
2164 case 'float':
2165 case 'string':
2166 $column = $attr_type . '_value';
2167 break;
2168 case 'dict':
2169 $column = 'uint_value';
2170 break;
2171 default:
0cc24e9a 2172 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
e673ee24
DO
2173 }
2174 $query2 =
2175 "delete from AttributeValue where " .
2176 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2177 $result = $dbxlink->query ($query2);
e673ee24
DO
2178 // We know $value isn't empty here.
2179 $query3 =
2180 "insert into AttributeValue set ${column} = '${value}', " .
2181 "object_id = ${object_id}, attr_id = ${attr_id} ";
2182 $result = $dbxlink->query ($query3);
e673ee24
DO
2183 return TRUE;
2184}
2185
2186function commitUseupPort ($port_id = 0)
2187{
2188 if ($port_id <= 0)
0cc24e9a 2189 throw new InvalidArgException ('$port_id', $port_id);
e673ee24
DO
2190 global $dbxlink;
2191 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2192 $result = $dbxlink->exec ($query);
e673ee24
DO
2193 return TRUE;
2194
2195}
2196
2197// This is a swiss-knife blade to insert a record into a table.
2198// The first argument is table name.
2199// The second argument is an array of "name" => "value" pairs.
2200// The function returns either TRUE or FALSE (we expect one row
2201// to be inserted).
2202function useInsertBlade ($tablename, $values)
2203{
2204 global $dbxlink;
2205 $namelist = $valuelist = '';
2206 foreach ($values as $name => $value)
2207 {
2208 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2209 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2210 }
2211 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2212 $result = $dbxlink->exec ($query);
2213 if ($result != 1)
2214 return FALSE;
2215 return TRUE;
2216}
2217
357eb2ea
DO
2218function usePreparedInsertBlade ($tablename, $columns)
2219{
2220 global $dbxlink;
2221 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2222 $query .= ') VALUES (' . implode (', ', array_fill (0, count ($columns), '?')) . ')';
2223 // Now the query should be as follows:
2224 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
2225 $prepared = $dbxlink->prepare ($query);
2226 if (!$prepared->execute (array_values ($columns)))
2227 return FALSE;
2228 return $prepared->rowCount() == 1;
2229}
2230
e673ee24
DO
2231// This swiss-knife blade deletes one record from the specified table
2232// using the specified key name and value.
f5575f12 2233function useDeleteBlade ($tablename, $keyname, $keyvalue)
e673ee24
DO
2234{
2235 global $dbxlink;
f5575f12 2236 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
e673ee24
DO
2237}
2238
8a5a4555 2239function useSelectBlade ($query)
5967b83d
DO
2240{
2241 global $dbxlink;
2242 $result = $dbxlink->query ($query);
5967b83d
DO
2243 return $result;
2244}
2245
9c0b0016
DO
2246function loadConfigCache ()
2247{
4fe32e78 2248 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
8a5a4555 2249 $result = useSelectBlade ($query);
9c0b0016
DO
2250 $cache = array();
2251 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2252 $cache[$row['varname']] = $row;
2253 $result->closeCursor();
2254 return $cache;
2255}
2256
2257// setConfigVar() is expected to perform all necessary filtering
2258function storeConfigVar ($varname = NULL, $varvalue = NULL)
2259{
c461c579 2260 global $dbxlink;
c5f84f48
DY
2261 if (!strlen ($varname))
2262 throw new InvalidArgException ('$varname', $varname);
2263 if ($varvalue === NULL)
2264 throw new InvalidArgException ('$varvalue', $varvalue);
9c0b0016
DO
2265 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2266 $result = $dbxlink->query ($query);
9c0b0016
DO
2267 $rc = $result->rowCount();
2268 $result->closeCursor();
f7ee57a1 2269 if ($rc == 0 or $rc == 1)
9c0b0016 2270 return TRUE;
0cc24e9a 2271 showWarning ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2272 return FALSE;
2273}
2274
fbbb74fb
DO
2275// Database version detector. Should behave corretly on any
2276// working dataset a user might have.
2277function getDatabaseVersion ()
2278{
2279 global $dbxlink;
2280 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2281 $result = $dbxlink->query ($query);
2282 if ($result == NULL)
2283 {
2284 $errorInfo = $dbxlink->errorInfo();
2285 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2286 return '0.14.4';
4d2e93f2 2287 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2288 }
2289 $rows = $result->fetchAll (PDO::FETCH_NUM);
59a83bd8 2290 if (count ($rows) != 1 || !strlen ($rows[0][0]))
fbbb74fb
DO
2291 {
2292 $result->closeCursor();
4d2e93f2 2293 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2294 }
2295 $ret = $rows[0][0];
2296 $result->closeCursor();
2297 return $ret;
2298}
2299
da04825a
DO
2300// Return an array of virtual services. For each of them list real server pools
2301// with their load balancers and other stats.
62a1dcb5
DO
2302function getSLBSummary ()
2303{
6fec9f39
DO
2304 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2305 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2306 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2307 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2308 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
6fec9f39 2309 'group by vs.id, object_id order by vs.vip, object_id';
8a5a4555 2310 $result = useSelectBlade ($query);
c3bdc503
DO
2311 $ret = array();
2312 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2313 {
4cadac8f 2314 $vsid = $row['vsid'];
da04825a 2315 $object_id = $row['object_id'];
4cadac8f
DO
2316 if (!isset ($ret[$vsid]))
2317 {
2318 $ret[$vsid] = array();
13bffb29 2319 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2320 $ret[$vsid][$cname] = $row[$cname];
da04825a 2321 $ret[$vsid]['lblist'] = array();
4cadac8f 2322 }
6fec9f39
DO
2323 // There's only one assigned RS pool possible for each LB-VS combination.
2324 $ret[$vsid]['lblist'][$row['object_id']] = array
2325 (
2326 'id' => $row['rspool_id'],
2327 'size' => $row['rscount'],
2328 'name' => $row['pool_name']
2329 );
c3bdc503 2330 }
060ba26e 2331 $result->closeCursor();
c3bdc503 2332 return $ret;
62a1dcb5
DO
2333}
2334
7e7a8387 2335function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2336{
79a9edb4 2337 if ($pool_id <= 0)
c5f84f48 2338 throw new InvalidArgException ('$pool_id', $pool_id);
59a83bd8 2339 if (!strlen ($rsport) or $rsport === 0)
79a9edb4 2340 $rsport = 'NULL';
ca461127
DO
2341 return useInsertBlade
2342 (
706ce117 2343 'IPv4RS',
ca461127
DO
2344 array
2345 (
2346 'rsip' => "inet_aton('${rsip}')",
2347 'rsport' => $rsport,
2348 'rspool_id' => $pool_id,
bcbeadb4 2349 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
59a83bd8 2350 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
3241551e
DO
2351 )
2352 );
2353}
2354
c63a8d6e 2355function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21 2356{
c5f84f48
DY
2357 if (!strlen ($vip))
2358 throw new InvalidArgException ('$vip', $vip);
2359 if ($vport <= 0)
2360 throw new InvalidArgException ('$vport', $vport);
2361 if (!strlen ($proto))
2362 throw new InvalidArgException ('$proto', $proto);
c63a8d6e 2363 if (!useInsertBlade
d6517a21 2364 (
706ce117 2365 'IPv4VS',
d6517a21
DO
2366 array
2367 (
2368 'vip' => "inet_aton('${vip}')",
2369 'vport' => $vport,
2370 'proto' => "'${proto}'",
59a83bd8
DO
2371 'name' => (!strlen ($name) ? 'NULL' : "'${name}'"),
2372 'vsconfig' => (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2373 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
d6517a21 2374 )
c63a8d6e
DO
2375 ))
2376 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2377 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2378}
2379
c1ca768c 2380function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2381{
c5f84f48
DY
2382 if ($pool_id <= 0)
2383 throw new InvalidArgException ('$pool_id', $pool_id);
2384 if ($object_id <= 0)
2385 throw new InvalidArgException ('$object_id', $object_id);
2386 if ($vs_id <= 0)
2387 throw new InvalidArgException ('$vs_id', $vs_id);
3241551e
DO
2388 return useInsertBlade
2389 (
706ce117 2390 'IPv4LB',
3241551e
DO
2391 array
2392 (
2393 'object_id' => $object_id,
2394 'rspool_id' => $pool_id,
c1ca768c 2395 'vs_id' => $vs_id,
59a83bd8
DO
2396 'vsconfig' => (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2397 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
3241551e 2398 )
ca461127
DO
2399 );
2400}
2401
fb1c4a54
DO
2402function commitDeleteRS ($id = 0)
2403{
2404 if ($id <= 0)
2405 return FALSE;
706ce117 2406 return useDeleteBlade ('IPv4RS', 'id', $id);
fb1c4a54
DO
2407}
2408
d6517a21
DO
2409function commitDeleteVS ($id = 0)
2410{
6657739e 2411 releaseFiles ('ipv4vs', $id);
706ce117 2412 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2413}
2414
c1ca768c 2415function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2416{
2417 global $dbxlink;
c4d85fd1 2418 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2419 return FALSE;
706ce117 2420 $query = "delete from IPv4LB where object_id = ${object_id} and " .
c1ca768c 2421 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2422 $result = $dbxlink->exec ($query);
2423 if ($result === NULL)
2424 return FALSE;
2425 elseif ($result != 1)
2426 return FALSE;
2427 else
2428 return TRUE;
2429}
2430
fb1c4a54
DO
2431function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2432{
fb1c4a54 2433 if (long2ip (ip2long ($rsip)) !== $rsip)
c5f84f48 2434 throw new InvalidArgException ('$rsip', $rsip);
59a83bd8 2435 if (!strlen ($rsport) or $rsport === 0)
79a9edb4 2436 $rsport = 'NULL';
fb1c4a54
DO
2437 global $dbxlink;
2438 $query =
706ce117 2439 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
59a83bd8 2440 (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2441 " where id = ${rsid} limit 1";
2442 $result = $dbxlink->query ($query);
fb1c4a54
DO
2443 return TRUE;
2444}
2445
c1ca768c 2446function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2447{
3241551e
DO
2448 global $dbxlink;
2449 $query =
706ce117 2450 "update IPv4LB set vsconfig = " .
59a83bd8 2451 (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
3241551e 2452 ', rsconfig = ' .
59a83bd8 2453 (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2454 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2455 "and vs_id = ${vs_id} limit 1";
3241551e 2456 $result = $dbxlink->exec ($query);
0cc24e9a 2457 return TRUE;
3241551e
DO
2458}
2459
d6517a21
DO
2460function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2461{
c5f84f48
DY
2462 if (!strlen ($vip))
2463 throw new InvalidArgException ('$vip', $vip);
2464 if ($vport <= 0)
2465 throw new InvalidArgException ('$vport', $vport);
2466 if (!strlen ($proto))
2467 throw new InvalidArgException ('$proto', $proto);
d6517a21 2468 global $dbxlink;
706ce117 2469 $query = "update IPv4VS set " .
d6517a21
DO
2470 "vip = inet_aton('${vip}'), " .
2471 "vport = ${vport}, " .
2472 "proto = '${proto}', " .
59a83bd8
DO
2473 'name = ' . (!strlen ($name) ? 'NULL,' : "'${name}', ") .
2474 'vsconfig = ' . (!strlen ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2475 'rsconfig = ' . (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
5ad76f01 2476 " where id = ${vsid} limit 1";
d6517a21 2477 $result = $dbxlink->exec ($query);
0cc24e9a 2478 return TRUE;
d6517a21
DO
2479}
2480
5a1680d2
DO
2481function loadThumbCache ($rack_id = 0)
2482{
5a1680d2
DO
2483 $ret = NULL;
2484 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
8a5a4555 2485 $result = useSelectBlade ($query);
5a1680d2
DO
2486 $row = $result->fetch (PDO::FETCH_ASSOC);
2487 if ($row)
2488 $ret = base64_decode ($row['thumb_data']);
2489 $result->closeCursor();
2490 return $ret;
2491}
2492
2493function saveThumbCache ($rack_id = 0, $cache = NULL)
2494{
2495 global $dbxlink;
178fda20 2496 if ($cache == NULL)
c5f84f48 2497 throw new InvalidArgException ('$cache', $cache);
5a1680d2
DO
2498 $data = base64_encode ($cache);
2499 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2500 $result = $dbxlink->exec ($query);
2501}
9a81d416 2502
c7fe33be
DO
2503function resetThumbCache ($rack_id = 0)
2504{
2505 global $dbxlink;
c7fe33be
DO
2506 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2507 $result = $dbxlink->exec ($query);
2508}
2509
748805bf 2510// Return the list of attached RS pools for the given object. As long as we have
706ce117 2511// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2512// by vs_id, because there will be only one RS pool listed for each VS of the
2513// current object.
78e7b769
DO
2514function getRSPoolsForObject ($object_id = 0)
2515{
748805bf 2516 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2517 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2518 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2519 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2520 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
748805bf
DO
2521 "where lb.object_id = ${object_id} " .
2522 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
8a5a4555 2523 $result = useSelectBlade ($query);
748805bf 2524 $ret = array ();
78e7b769 2525 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2526 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2527 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2528 $result->closeCursor();
748805bf 2529 return $ret;
78e7b769
DO
2530}
2531
c63a8d6e 2532function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2533{
59a83bd8 2534 if (!strlen ($name))
c5f84f48 2535 throw new InvalidArgException ('$name', $name);
c63a8d6e 2536 if (!useInsertBlade
5ad76f01 2537 (
706ce117 2538 'IPv4RSPool',
5ad76f01
DO
2539 array
2540 (
59a83bd8
DO
2541 'name' => (!strlen ($name) ? 'NULL' : "'${name}'"),
2542 'vsconfig' => (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2543 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
5ad76f01 2544 )
c63a8d6e
DO
2545 ))
2546 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2547 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2548}
2549
2550function commitDeleteRSPool ($pool_id = 0)
2551{
2552 global $dbxlink;
2553 if ($pool_id <= 0)
2554 return FALSE;
6657739e 2555 releaseFiles ('ipv4rspool', $pool_id);
706ce117 2556 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2557}
2558
2559function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2560{
5ad76f01 2561 global $dbxlink;
706ce117 2562 $query = "update IPv4RSPool set " .
59a83bd8
DO
2563 'name = ' . (!strlen ($name) ? 'NULL,' : "'${name}', ") .
2564 'vsconfig = ' . (!strlen ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2565 'rsconfig = ' . (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
5ad76f01
DO
2566 " where id = ${pool_id} limit 1";
2567 $result = $dbxlink->exec ($query);
0cc24e9a 2568 if ($result != 1)
5ad76f01
DO
2569 return FALSE;
2570 else
2571 return TRUE;
2572}
2573
8253d9f0
DO
2574function getRSList ()
2575{
1f7d18fa 2576 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
706ce117 2577 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
8a5a4555 2578 $result = useSelectBlade ($query);
4b0932b6 2579 $ret = array ();
8253d9f0 2580 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2581 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2582 $ret[$row['id']][$cname] = $row[$cname];
2583 $result->closeCursor();
2584 return $ret;
2585}
2586
2587// Return the list of all currently configured load balancers with their pool count.
2588function getLBList ()
2589{
4b0932b6 2590 $query = "select object_id, count(rspool_id) as poolcount " .
706ce117 2591 "from IPv4LB group by object_id order by object_id";
8a5a4555 2592 $result = useSelectBlade ($query);
4b0932b6
DO
2593 $ret = array ();
2594 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2595 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2596 $result->closeCursor();
4b0932b6 2597 return $ret;
8253d9f0
DO
2598}
2599
178fda20 2600// For the given object return: its vsconfig/rsconfig; the list of RS pools
9e677cbd
DO
2601// attached (each with vsconfig/rsconfig in turn), each with the list of
2602// virtual services terminating the pool. Each pool also lists all real
2603// servers with rsconfig.
2987fc1f 2604function getSLBConfig ($object_id)
9e677cbd 2605{
9e677cbd 2606 $ret = array();
d91f08f3
DO
2607 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2608 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2609 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2610 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2611 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2612 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2613 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2614 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2615 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2616 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
8a5a4555 2617 $result = useSelectBlade ($query);
9e677cbd
DO
2618 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2619 {
d91f08f3
DO
2620 $vs_id = $row['vs_id'];
2621 if (!isset ($ret[$vs_id]))
2622 {
2623 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)
2624 $ret[$vs_id][$c] = $row[$c];
2625 $ret[$vs_id]['rslist'] = array();
2626 }
2627 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2628 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2629 }
2630 $result->closeCursor();
2631 return $ret;
2632}
1f7d18fa
DO
2633
2634function commitSetInService ($rs_id = 0, $inservice = '')
2635{
c5f84f48
DY
2636 if (!strlen ($inservice))
2637 throw new InvalidArgException ('$inservice', $inservice);
2638 if ($rs_id <= 0)
2639 throw new InvalidArgException ('$rs_id', $rs_id);
1f7d18fa 2640 global $dbxlink;
706ce117 2641 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
1f7d18fa 2642 $result = $dbxlink->exec ($query);
0cc24e9a 2643 if ($result != 1)
1f7d18fa
DO
2644 return FALSE;
2645 else
2646 return TRUE;
2647}
2648
ad0e4754
DO
2649function executeAutoPorts ($object_id = 0, $type_id = 0)
2650{
c5f84f48
DY
2651 if ($object_id == 0)
2652 throw new InvalidArgException ('$object_id', $object_id);
2653 if ($type_id == 0)
2654 throw new InvalidArgException ('$type_id', $type_id);
f3f0161f 2655 $ret = TRUE;
118e4c38 2656 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2657 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2658 return $ret;
ad0e4754
DO
2659}
2660
6e49bd1f 2661// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2662// generated/deducted later at higher levels.
aab37bc0 2663// Result is a chain: randomly indexed taginfo list.
f9bc186f 2664function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2665{
a6e8d544 2666 $ret = array();
2c21a10c
DO
2667 if (!in_array ($entity_realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2668 return $ret;
edf0993c
DO
2669 $query = "select tt.id, tag from " .
2670 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
120e9ddd 2671 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
edf0993c 2672 "order by tt.tag";
8a5a4555 2673 $result = useSelectBlade ($query);
5967b83d 2674 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2675 $ret[$row['id']] = $row;
a6e8d544 2676 $result->closeCursor();
aab37bc0 2677 return getExplicitTagsOnly ($ret);
5967b83d
DO
2678}
2679
351c0966 2680// Return a tag chain with all DB tags on it.
5967b83d
DO
2681function getTagList ()
2682{
20c901a7 2683 $ret = array();
120e9ddd 2684 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2685 "from TagTree left join TagStorage on id = tag_id " .
120e9ddd 2686 "group by id, entity_realm order by tag";
8a5a4555 2687 $result = useSelectBlade ($query);
fb7a4967
DO
2688 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2689 // which is utf8_general_ci for UTF-8.
5967b83d 2690 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2691 {
7cc02fc1 2692 if (!isset ($ret[$row['id']]))
20c901a7 2693 $ret[$row['id']] = array
5b7bd02e
DO
2694 (
2695 'id' => $row['id'],
2696 'tag' => $row['tag'],
fb7a4967 2697 'ci' => $ci++,
5b7bd02e 2698 'parent_id' => $row['parent_id'],
9e51318b 2699 'refcnt' => array ('total' => 0)
5b7bd02e
DO
2700 );
2701 if ($row['realm'])
9e51318b 2702 {
20c901a7 2703 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
9e51318b
DO
2704 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2705 }
5b7bd02e 2706 }
5967b83d 2707 $result->closeCursor();
20c901a7 2708 return $ret;
5967b83d
DO
2709}
2710
fe7044ad
DO
2711function commitCreateTag ($tagname = '', $parent_id = 0)
2712{
2713 if ($tagname == '' or $parent_id === 0)
2714 return "Invalid args to " . __FUNCTION__;
2715 $result = useInsertBlade
2716 (
2717 'TagTree',
2718 array
2719 (
2720 'tag' => "'${tagname}'",
2721 'parent_id' => $parent_id
2722 )
2723 );
2724 if ($result)
2725 return '';
9f572fb5
DO
2726 global $dbxlink;
2727 if ($dbxlink->errorCode() == 23000) // integrity constraint violation
2728 {
2729 $ei = $dbxlink->errorInfo();
2730 if ($ei[1] == 1062)
2731 return 'tag name must be unique';
2732 if ($ei[1] == 1452)
2733 return "parent tag id ${parent_id} does not exist";
2734 }
2735 return "SQL query failed in " . __FUNCTION__;
fe7044ad
DO
2736}
2737
2738function commitDestroyTag ($tagid = 0)
2739{
2740 if ($tagid == 0)
2741 return 'Invalid arg to ' . __FUNCTION__;
f5575f12 2742 if (useDeleteBlade ('TagTree', 'id', $tagid))
fe7044ad
DO
2743 return '';
2744 else
2745 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2746}
f9bc186f 2747
49fb1027 2748function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2749{
49fb1027
DO
2750 if ($parent_id == 0)
2751 $parent_id = 'NULL';
f9bc186f 2752 global $dbxlink;
49fb1027
DO
2753 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2754 "where id = ${tag_id} limit 1";
f9bc186f 2755 $result = $dbxlink->exec ($query);
590e1281
DO
2756 if ($result !== FALSE)
2757 return '';
9f572fb5
DO
2758 if ($dbxlink->errorCode() == 23000)
2759 {
2760 $ei = $dbxlink->errorInfo();
2761 if ($ei[1] == 1062)
2762 return 'tag name must be unique';
2763 if ($ei[1] == 1452)
2764 return "parent tag id ${parent_id} does not exist";
2765 }
2766 return 'SQL query failed in ' . __FUNCTION__;
f9bc186f
DO
2767}
2768
01b6b4d6
DO
2769// Drop the whole chain stored.
2770function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af
DO
2771{
2772 global $dbxlink;
120e9ddd 2773 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
aedf18af 2774 $result = $dbxlink->exec ($query);
0cc24e9a 2775 return TRUE;
aedf18af
DO
2776}
2777
01b6b4d6 2778// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
29c3a4d8
DO
2779// FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2780// but not now.
01b6b4d6
DO
2781function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2782{
2783 global $dbxlink;
120e9ddd 2784 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
01b6b4d6 2785 $result = $dbxlink->exec ($query);
0cc24e9a 2786 return TRUE;
01b6b4d6
DO
2787}
2788
351c0966 2789// Push a record into TagStorage unconditionally.
3355ca56 2790function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2791{
59a83bd8 2792 if (!strlen ($realm))
3355ca56 2793 return FALSE;
eb6ea26f
DO
2794 return useInsertBlade
2795 (
2796 'TagStorage',
2797 array
2798 (
120e9ddd
DO
2799 'entity_realm' => "'${realm}'",
2800 'entity_id' => $entity_id,
eb6ea26f
DO
2801 'tag_id' => $tag_id,
2802 )
2803 );
2804}
2805
351c0966 2806// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
2807// on the implicit list already). Then remove any other records, which
2808// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
2809// that both the tag base is still minimal and all requested tags appear on
2810// the resulting tag chain.
abef7149
DO
2811// Return TRUE, if any changes were committed.
2812function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2813{
2814 // Put the current explicit sub-chain into a buffer and merge all tags from
2815 // the extra chain, which aren't there yet.
2816 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2817 foreach ($extrachain as $extratag)
2818 if (!tagOnChain ($extratag, $newchain))
2819 $newchain[] = $extratag;
2820 // Then minimize the working buffer and check if it differs from the original
2821 // chain we started with. If it is so, save the work and signal the upper layer.
2822 $newchain = getExplicitTagsOnly ($newchain);
2823 if (tagChainCmp ($oldchain, $newchain))
2824 {
01b6b4d6 2825 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
2826 foreach ($newchain as $taginfo)
2827 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2828 return TRUE;
2829 }
2830 return FALSE;
351c0966
DO
2831}
2832
2833// Presume, that the target record has no tags attached.
2834function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2835{
2836 if (!count ($tagidlist))
c63a8d6e
DO
2837 return '';
2838 if (!$last_insert_id)
2839 $last_insert_id = lastInsertID();
2840 $errcount = 0;
abef7149 2841 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 2842 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
2843 $errcount++;
2844 if (!$errcount)
2845 return '';
2846 else
2847 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2848}
2849
42023f03
DO
2850function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2851{
2852 // $range is in x.x.x.x/x format, split into ip/mask vars
2853 $rangeArray = explode('/', $range);
2854 if (count ($rangeArray) != 2)
2855 return "Invalid IPv4 prefix '${range}'";
2856 $ip = $rangeArray[0];
2857 $mask = $rangeArray[1];
2858
59a83bd8 2859 if (!strlen ($ip) or !strlen ($mask))
42023f03
DO
2860 return "Invalid IPv4 prefix '${range}'";
2861 $ipL = ip2long($ip);
2862 $maskL = ip2long($mask);
2863 if ($ipL == -1 || $ipL === FALSE)
2864 return 'Bad IPv4 address';
2865 if ($mask < 32 && $mask > 0)
2866 $maskL = $mask;
2867 else
2868 {
2869 $maskB = decbin($maskL);
2870 if (strlen($maskB)!=32)
2871 return 'Invalid netmask';
2872 $ones=0;
2873 $zeroes=FALSE;
2874 foreach( str_split ($maskB) as $digit)
2875 {
2876 if ($digit == '0')
2877 $zeroes = TRUE;
2878 if ($digit == '1')
2879 {
2880 $ones++;
2881 if ($zeroes == TRUE)
2882 return 'Invalid netmask';
2883 }
2884 }
2885 $maskL = $ones;
2886 }
2887 $binmask = binMaskFromDec($maskL);
2888 $ipL = $ipL & $binmask;
357eb2ea 2889 $result = usePreparedInsertBlade
42023f03 2890 (
706ce117 2891 'IPv4Network',
42023f03
DO
2892 array
2893 (
2894 'ip' => sprintf ('%u', $ipL),
357eb2ea
DO
2895 'mask' => $maskL,
2896 'name' => $name
42023f03
DO
2897 )
2898 );
e782fca4
DO
2899 if ($result != TRUE)
2900 return "Could not add ${range} (already exists?).";
42023f03
DO
2901
2902 if ($is_bcast and $maskL < 31)
2903 {
2904 $network_addr = long2ip ($ipL);
2905 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2906 updateAddress ($network_addr, 'network', 'yes');
2907 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2908 }
351c0966 2909 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
2910}
2911
706ce117 2912// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
2913function destroyIPv4Prefix ($id = 0)
2914{
2915 if ($id <= 0)
2916 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
6657739e 2917 releaseFiles ('ipv4net', $id);
706ce117 2918 if (!useDeleteBlade ('IPv4Network', 'id', $id))
42023f03 2919 return __FUNCTION__ . ': SQL query #1 failed';
01b6b4d6 2920 if (!destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
2921 return __FUNCTION__ . ': SQL query #2 failed';
2922 return '';
2923}
2924
ebae41b3
DO
2925function loadScript ($name)
2926{
8a5a4555 2927 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
ebae41b3 2928 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
2929 if ($row !== FALSE)
2930 return $row[0];
2931 else
2932 return NULL;
ebae41b3
DO
2933}
2934
178fda20 2935function saveScript ($name = '', $text)
ebae41b3 2936{
59a83bd8 2937 if (!strlen ($name))
c5f84f48 2938 throw new InvalidArgException ('$name', $name);
4a6a28f1 2939 // delete regardless of existence
f5575f12 2940 useDeleteBlade ('Script', 'script_name', "'${name}'");
4a6a28f1 2941 return useInsertBlade
ebae41b3
DO
2942 (
2943 'Script',
2944 array
2945 (
2946 'script_name' => "'${name}'",
2947 'script_text' => "'${text}'"
2948 )
2949 );
2950}
2951
d983f70a
DO
2952function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2953{
2954 if (NULL === getIPv4AddressNetworkId ($localip))
2955 return "$localip: Non existant ip";
0929db7f 2956 if (NULL === getIPv4AddressNetworkId ($remoteip))
d983f70a
DO
2957 return "$remoteip: Non existant ip";
2958 if ( ($localport <= 0) or ($localport >= 65536) )
2959 return "$localport: invaild port";
2960 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
2961 return "$remoteport: invaild port";
2962
2963 $result = useInsertBlade
2964 (
706ce117 2965 'IPv4NAT',
d983f70a
DO
2966 array
2967 (
2968 'object_id' => $object_id,
2969 'localip' => "INET_ATON('${localip}')",
2970 'remoteip' => "INET_ATON('$remoteip')",
2971 'localport' => $localport,
2972 'remoteport' => $remoteport,
2973 'proto' => "'${proto}'",
2974 'description' => "'${description}'",
2975 )
2976 );
2977 if ($result)
2978 return '';
2979 else
2980 return __FUNCTION__ . ': Failed to insert the rule.';
2981}
2982
2983function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
2984{
2985 global $dbxlink;
2986
2987 $query =
706ce117 2988 "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
2989 $result = $dbxlink->exec ($query);
2990 return '';
2991}
2992
2993function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2994{
2995 global $dbxlink;
2996
2997 $query =
706ce117 2998 "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
2999 $result = $dbxlink->exec ($query);
3000 return '';
3001}
3002
3003function getNATv4ForObject ($object_id)
3004{
3005 $ret = array();
3006 $ret['out'] = array();
3007 $ret['in'] = array();
3008 $query =
3009 "select ".
3010 "proto, ".
3011 "INET_NTOA(localip) as localip, ".
3012 "localport, ".
3013 "INET_NTOA(remoteip) as remoteip, ".
3014 "remoteport, ".
3015 "ipa1.name as local_addr_name, " .
3016 "ipa2.name as remote_addr_name, " .
3017 "description ".
706ce117
DO
3018 "from IPv4NAT ".
3019 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3020 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
d983f70a
DO
3021 "where object_id='$object_id' ".
3022 "order by localip, localport, proto, remoteip, remoteport";
8a5a4555 3023 $result = useSelectBlade ($query);
d983f70a
DO
3024 $count=0;
3025 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3026 {
3027 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3028 $ret['out'][$count][$cname] = $row[$cname];
3029 $count++;
3030 }
3031 $result->closeCursor();
3032 unset ($result);
3033
3034 $query =
3035 "select ".
3036 "proto, ".
3037 "INET_NTOA(localip) as localip, ".
3038 "localport, ".
3039 "INET_NTOA(remoteip) as remoteip, ".
3040 "remoteport, ".
706ce117 3041 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
3042 "RackObject.name as object_name, ".
3043 "description ".
706ce117
DO
3044 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3045 "where IPv4Allocation.object_id='$object_id' ".
d983f70a 3046 "order by remoteip, remoteport, proto, localip, localport";
8a5a4555 3047 $result = useSelectBlade ($query);
d983f70a
DO
3048 $count=0;
3049 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3050 {
3051 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3052 $ret['in'][$count][$cname] = $row[$cname];
3053 $count++;
3054 }
3055 $result->closeCursor();
3056
3057 return $ret;
3058}
3059
178fda20 3060// Return a list of files, which are not linked to the specified record. This list
121496b6 3061// will be used by printSelect().
e1ae3fb4
AD
3062function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3063{
c5f84f48
DY
3064 if ($entity_type == NULL)
3065 throw new InvalidArgException ('$entity_type', $entity_type);
3066 if ($entity_id == 0)
3067 throw new InvalidArgException ('$entity_id', $entity_id);
e1ae3fb4
AD
3068 global $dbxlink;
3069 $sql =
121496b6 3070 'SELECT id, name FROM File ' .
e1ae3fb4 3071 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
121496b6 3072 'ORDER BY name, id';
e1ae3fb4
AD
3073 $query = $dbxlink->prepare($sql);
3074 $query->bindParam(1, $entity_type);
3075 $query->bindParam(2, $entity_id);
3076 $query->execute();
3077 $ret=array();
e1ae3fb4 3078 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3079 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3080 return $ret;
3081}
3082
6df2025d
DO
3083// FIXME: return a standard cell list, so upper layer can iterate over
3084// it conveniently.
e1ae3fb4
AD
3085function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3086{
c5f84f48
DY
3087 if ($entity_type === NULL)
3088 throw new InvalidArgException ('$entity_type', $entity_type);
3089 if ($entity_id <= 0)
3090 throw new InvalidArgException ('$entity_id', $entity_id);
e1ae3fb4
AD
3091 global $dbxlink;
3092 $sql =
3093 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3094 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3095 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3096 $query = $dbxlink->prepare($sql);
3097 $query->bindParam(1, $entity_type);
3098 $query->bindParam(2, $entity_id);
3099 $query->execute();
3100 $ret = array();
3101 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3102 $ret[$row['file_id']] = array (
b3567368 3103 'id' => $row['file_id'],
e1ae3fb4
AD
3104 'link_id' => $row['link_id'],
3105 'name' => $row['name'],
3106 'type' => $row['type'],
3107 'size' => $row['size'],
3108 'ctime' => $row['ctime'],
3109 'mtime' => $row['mtime'],
3110 'atime' => $row['atime'],
3111 'comment' => $row['comment'],
3112 );
3113 return $ret;
3114}
3115
3116function getFile ($file_id = 0)
3117{
e1ae3fb4
AD
3118 global $dbxlink;
3119 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3120 $query->bindParam(1, $file_id);
3121 $query->execute();
3122 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3123 {
0cc24e9a 3124 showWarning ('Query succeeded, but returned no data', __FUNCTION__);
e1ae3fb4
AD
3125 $ret = NULL;
3126 }
3127 else
3128 {
3129 $ret = array();
3130 $ret['id'] = $row['id'];
3131 $ret['name'] = $row['name'];
3132 $ret['type'] = $row['type'];
3133 $ret['size'] = $row['size'];
3134 $ret['ctime'] = $row['ctime'];
3135 $ret['mtime'] = $row['mtime'];
3136 $ret['atime'] = $row['atime'];
3137 $ret['contents'] = $row['contents'];
3138 $ret['comment'] = $row['comment'];
bed9cd76 3139 $query->closeCursor();
e1ae3fb4 3140
deb3da1b 3141 // Someone accessed this file, update atime
e1ae3fb4
AD
3142 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3143 $q_atime->bindParam(1, date('YmdHis'));
3144 $q_atime->bindParam(2, $file_id);
3145 $q_atime->execute();
3146 }
e1ae3fb4
AD
3147 return $ret;
3148}
3149
e1ae3fb4
AD
3150function getFileLinks ($file_id = 0)
3151{
e1ae3fb4 3152 global $dbxlink;
8bc5d1e4 3153 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ? ORDER BY entity_type, entity_id');
e1ae3fb4
AD
3154 $query->bindParam(1, $file_id);
3155 $query->execute();
da3302ab 3156 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3157 $ret = array();
da3302ab 3158 foreach ($rows as $row)
e1ae3fb4
AD
3159 {
3160 // get info of the parent
3161 switch ($row['entity_type'])
3162 {
3163 case 'ipv4net':
3164 $page = 'ipv4net';
3165 $id_name = 'id';
d724d290 3166 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3167 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3168 break;
3169 case 'ipv4rspool':
3854af78 3170 $page = 'ipv4rspool';
e1ae3fb4 3171 $id_name = 'pool_id';
a6e91ac2 3172 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3173 $name = $parent['name'];
3174 break;
3175 case 'ipv4vs':
3176 $page = 'ipv4vs';
3177 $id_name = 'vs_id';
7c38462f 3178 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3179 $name = $parent['name'];
3180 break;
3181 case 'object':
3182 $page = 'object';
3183 $id_name = 'object_id';
6297d584 3184 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
7ddbcf59 3185 $name = $parent['dname'];
e1ae3fb4
AD
3186 break;
3187 case 'rack':
3188 $page = 'rack';
3189 $id_name = 'rack_id';
61a1d996 3190 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3191 $name = $parent['name'];
3192 break;
3193 case 'user':
3194 $page = 'user';
3195 $id_name = 'user_id';
0b2c74cb
DO
3196 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3197 $name = $parent['user_name'];
e1ae3fb4
AD
3198 break;
3199 }
3200
17d95c32 3201 // name needs to have some value for hrefs to work
59a83bd8 3202 if (!strlen ($name))
17d95c32
AD
3203 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3204
e1ae3fb4
AD
3205 $ret[$row['id']] = array(
3206 'page' => $page,
3207 'id_name' => $id_name,
3208 'entity_type' => $row['entity_type'],
3209 'entity_id' => $row['entity_id'],
3210 'name' => $name
3211 );
3212 }
3213 return $ret;
3214}
3215
0b97b8f0 3216function getFileStats ()
e1ae3fb4 3217{
e1ae3fb4 3218 $query = 'SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type';
8a5a4555 3219 $result = useSelectBlade ($query);
e1ae3fb4 3220 $ret = array();
e1ae3fb4
AD
3221 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3222 if ($row['count'] > 0)
0b97b8f0
DO
3223 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3224 unset ($result);
e1ae3fb4
AD
3225
3226 // Find number of files without any linkage
3227 $linkless_sql =
3228 'SELECT COUNT(*) ' .
3229 'FROM File ' .
3230 'WHERE id NOT IN (SELECT file_id FROM FileLink)';
8a5a4555 3231 $result = useSelectBlade ($linkless_sql);
0b97b8f0
DO
3232 $ret["Unattached files"] = $result->fetchColumn ();
3233 unset ($result);
e1ae3fb4
AD
3234
3235 // Find total number of files
3236 $total_sql = 'SELECT COUNT(*) FROM File';
8a5a4555 3237 $result = useSelectBlade ($total_sql);
0b97b8f0 3238 $ret["Total files"] = $result->fetchColumn ();
e1ae3fb4 3239
e1ae3fb4
AD
3240 return $ret;
3241}
3242
3243function commitAddFile ($name, $type, $size, $contents, $comment)
3244{
3245 $now = date('YmdHis');
3246
3247 global $dbxlink;
3248 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3249 $query->bindParam(1, $name);
3250 $query->bindParam(2, $type);
3251 $query->bindParam(3, $size);
3252 $query->bindParam(4, $now);
3253 $query->bindParam(5, $now);
3254 $query->bindParam(6, $now);
3255 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3256 $query->bindParam(8, $comment);
3257
3258 $result = $query->execute();
3259
3260
3261 if ($result)
3262 return '';
590e1281 3263 elseif ($query->errorCode() == 23000)
13edfa1c 3264 return "commitAddFile: File named '${name}' already exists";
e1ae3fb4
AD
3265 else
3266 return 'commitAddFile: SQL query failed';
3267}
3268
4a2c6c6b 3269function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4
AD
3270{
3271 global $dbxlink;
3272 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3273 $query->bindParam(1, $file_id);
4a2c6c6b
AD
3274 $query->bindParam(2, $entity_type);
3275 $query->bindParam(3, $entity_id);
e1ae3fb4
AD
3276
3277 $result = $query->execute();
3278
3279 if ($result)
3280 return '';
3281 else
3282 return 'commitLinkFile: SQL query failed';
3283}
3284
f8874cdb 3285function commitReplaceFile ($file_id = 0, $contents)
fd1fb420 3286{
fd1fb420 3287 global $dbxlink;
f8874cdb
DO
3288 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3289 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3290 $query->bindParam(2, $file_id);
fd1fb420
AD
3291
3292 $result = $query->execute();
fd1fb420
AD
3293 return '';
3294}
3295
9db67d95 3296function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
e1ae3fb4 3297{
c5f84f48
DY
3298 if (!strlen ($new_name))
3299 throw new InvalidArgException ('$new_name', $new_name);
3300 if (!strlen ($new_type))
3301 throw new InvalidArgException ('$new_type', $new_type);
e1ae3fb4 3302 global $dbxlink;
9db67d95 3303 $query = $dbxlink->prepare('UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?');
6ee41bd4 3304 $query->bindParam(1, $new_name);
9db67d95
DO
3305 $query->bindParam(2, $new_type);
3306 $query->bindParam(3, $new_comment);
3307 $query->bindParam(4, $file_id);
e1ae3fb4
AD
3308
3309 $result = $query->execute();
3310 if (!$result)
6ee41bd4 3311 return 'SQL query failed in ' . __FUNCTION__;
e1ae3fb4
AD
3312 return '';
3313}
3314
3315function commitUnlinkFile ($link_id)
3316{
3317 if (useDeleteBlade ('FileLink', 'id', $link_id) != TRUE)
3318 return __FUNCTION__ . ': useDeleteBlade() failed';
3319 return '';
3320}
3321
3322function commitDeleteFile ($file_id)
3323{
29c3a4d8 3324 destroyTagsForEntity ('file', $file_id);
e1ae3fb4
AD
3325 if (useDeleteBlade ('File', 'id', $file_id) != TRUE)
3326 return __FUNCTION__ . ': useDeleteBlade() failed';
3327 return '';
3328}
3329
4034ab9e
DO
3330function getChapterList ()
3331{
3332 $ret = array();
8a5a4555 3333 $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 3334 while ($row = $result->fetch (PDO::FETCH_ASSOC))
c4d0dc30 3335 $ret[$row['id']] = $row;
4034ab9e
DO
3336 return $ret;
3337}
3338
2d1e6b63 3339// Return file id by file name.
72d2a7ee
DO
3340function findFileByName ($filename)
3341{
2d1e6b63
AD
3342 global $dbxlink;
3343 $query = $dbxlink->prepare('SELECT id FROM File WHERE name = ?');
3344 $query->bindParam(1, $filename);
3345 $query->execute();
3346 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
72d2a7ee 3347 return $row['id'];
2d1e6b63
AD
3348
3349 return NULL;
72d2a7ee
DO
3350}
3351
9133d2c5
DO
3352function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3353{
3354 global $dbxlink;
3355 $dbxlink->beginTransaction();
3356 $query = "select now() - first_success as success_age, now() - last_retry as retry_age, displayed_name, memberof " .
3357 "from LDAPCache where presented_username = '${form_username}' and successful_hash = '${password_hash}' " .
3358 "having success_age < ${expiry} for update";
8a5a4555 3359 $result = useSelectBlade ($query);
9133d2c5
DO
3360 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3361 {
3362 $row['memberof'] = unserialize (base64_decode ($row['memberof']));
3363 return $row;
3364 }
3365 return NULL;
3366}
3367
3368function releaseLDAPCache ()
3369{
3370 global $dbxlink;
3371 $dbxlink->commit();
3372}
3373
3374// This actually changes only last_retry.
3375function touchLDAPCacheRecord ($form_username)
3376{
3377 global $dbxlink;
3378 $query = "update LDAPCache set last_retry = NOW() where presented_username = '${form_username}'";
3379 $dbxlink->exec ($query);
3380}
3381
3382function replaceLDAPCacheRecord ($form_username, $password_hash, $dname, $memberof)
3383{
3384 deleteLDAPCacheRecord ($form_username);
3385 useInsertBlade ('LDAPCache',
3386 array
3387 (
3388 'presented_username' => "'${form_username}'",
3389 'successful_hash' => "'${password_hash}'",
3390 'displayed_name' => "'${dname}'",
3391 'memberof' => "'" . base64_encode (serialize ($memberof)) . "'"
3392 )
3393 );
3394}
3395
3396function deleteLDAPCacheRecord ($form_username)
3397{
3398 return useDeleteBlade ('LDAPCache', 'presented_username', "'${form_username}'");
3399}
3400
f3371850
DO
3401// Age all records older, than cache_expiry seconds, and all records made in future.
3402// Calling this function w/o argument purges the whole LDAP cache.
3403function discardLDAPCache ($maxage = 0)
ef44d4a3
DO
3404{
3405 global $dbxlink;
39776127 3406 $dbxlink->exec ("DELETE from LDAPCache WHERE NOW() - first_success >= ${maxage} or NOW() < first_success");
ef44d4a3
DO
3407}
3408
b82cce3f
DO
3409function getUserIDByUsername ($username)
3410{
3411 $query = "select user_id from UserAccount where user_name = '${username}'";
8a5a4555 3412 $result = useSelectBlade ($query);
b82cce3f
DO
3413 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3414 return $row['user_id'];
3415 return NULL;
3416}
3417
029a14bc
DO
3418// Return TRUE, if the given address is assigned to a port of any object
3419// except the current object. Using this function as a constraint makes
3420// it possible to reuse L2 addresses within one object, yet keeping them
3421// universally unique on the other hand.
3422function alreadyUsedL2Address ($address, $my_object_id)
3423{
3424 $query = "SELECT COUNT(*) FROM Port WHERE BINARY l2address = '${address}' AND object_id != ${my_object_id}";
8a5a4555 3425 $result = useSelectBlade ($query);
029a14bc
DO
3426 $row = $result->fetch (PDO::FETCH_NUM);
3427 return $row[0] != 0;
3428}
3429
2dfa1b73 3430function getPortInterfaceCompat()
3153a326
DO
3431{
3432 $query = 'SELECT iif_id, iif_name, oif_id, dict_value AS oif_name ' .
3433 'FROM PortInterfaceCompat INNER JOIN PortInnerInterface ON id = iif_id ' .
3434 'INNER JOIN Dictionary ON dict_key = oif_id ' .
2400d7ec 3435 'ORDER BY iif_name, oif_name';
8a5a4555 3436 $result = useSelectBlade ($query);
2dfa1b73 3437 return $result->fetchAll (PDO::FETCH_ASSOC);
3153a326
DO
3438}
3439
3440// Return a set of options for a plain SELECT. These options include the current
3441// OIF of the given port and all OIFs of its permanent IIF.
3442function getExistingPortTypeOptions ($port_id)
3443{
3444 $query = 'SELECT oif_id, dict_value AS oif_name ' .
3445 'FROM PortInterfaceCompat INNER JOIN Dictionary ON oif_id = dict_key ' .
3446 "WHERE iif_id = (SELECT iif_id FROM Port WHERE id = ${port_id}) " .
3447 'ORDER BY oif_name';
8a5a4555 3448 $result = useSelectBlade ($query);
3153a326
DO
3449 $ret = array();
3450 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3451 $ret[$row['oif_id']] = $row['oif_name'];
3452 return $ret;
3453}
3454
2dfa1b73
DO
3455function getPortIIFOptions()
3456{
3457 $ret = array();
8a5a4555 3458 $result = useSelectBlade ('SELECT id, iif_name FROM PortInnerInterface ORDER BY iif_name');
2dfa1b73
DO
3459 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3460 $ret[$row['id']] = $row['iif_name'];
3461 return $ret;
3462}
3463
3464function commitSupplementPIC ($iif_id, $oif_id)
3465{
3466 return useInsertBlade
3467 (
3468 'PortInterfaceCompat',
3469 array ('iif_id' => $iif_id, 'oif_id' => $oif_id)
3470 );
3471}
3472
3473function commitReducePIC ($iif_id, $oif_id)
3474{
3475 global $dbxlink;
3d9ac3d4 3476 return 1 === $dbxlink->exec ("DELETE FROM PortInterfaceCompat WHERE iif_id = ${iif_id} AND oif_id = ${oif_id}");
2dfa1b73
DO
3477}
3478
27ec21b2
DO
3479function getPortIIFStats ($args)
3480{
3481 $query = 'SELECT dict_value AS title, COUNT(id) AS max, ' .
3482 'COUNT(reservation_comment) + ' .
3483 'SUM((SELECT COUNT(*) FROM Link WHERE id IN (porta, portb))) AS current ' .
3484 'FROM Port INNER JOIN Dictionary ON type = dict_key ' .
3485 'WHERE iif_id = ' . current ($args) . ' GROUP BY type';
8a5a4555 3486 $result = useSelectBlade ($query);
27ec21b2
DO
3487 return $result->fetchAll (PDO::FETCH_ASSOC);
3488}
3489
cd3775e9
DO
3490function getPortInfo ($port_id)
3491{
3492 $query = "SELECT object_id, name, iif_id, type AS oif_id, l2address, ".
3493 "(SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, " .
3494 "(SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name " .
3495 "FROM Port WHERE id = ${port_id}";
8a5a4555 3496 $result = useSelectBlade ($query);
cd3775e9
DO
3497 return $result->fetch (PDO::FETCH_ASSOC);
3498}
3499
e673ee24 3500?>