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