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