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