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