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