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