r3064 - InnoDB: employ foreign keys in TagTree, TagStorage
[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
f1b5f68d 1670// search in port "reservation comment", "label" and "L2 address" columns
d516d719 1671function getPortSearchResults ($what)
323edbbf 1672{
f1b5f68d 1673 $ret = array();
323edbbf
DO
1674 $ports = getSearchResultByField
1675 (
1676 'Port',
1b4a0a6a 1677 array ('object_id', 'id', 'reservation_comment'),
323edbbf
DO
1678 'reservation_comment',
1679 $what,
1680 'object_id',
1681 0
1682 );
323edbbf
DO
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 1687 }
f1b5f68d
DO
1688 $ports = getSearchResultByField
1689 (
1690 'Port',
1691 array ('object_id', 'id', 'label'),
1692 'label',
1693 $what,
1694 'object_id',
1695 0
1696 );
1697 foreach ($ports as $port)
1698 {
1699 $ret[$port['object_id']]['id'] = $port['object_id'];
1700 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1701 }
d516d719
DO
1702 if (NULL === ($db_l2address = l2addressForDatabase ($what)))
1703 return $ret;
1704 $ports = getSearchResultByField
1705 (
1706 'Port',
1b4a0a6a 1707 array ('object_id', 'id', 'l2address'),
d516d719
DO
1708 'l2address',
1709 $db_l2address,
1710 'object_id',
1711 2
1712 );
1713 foreach ($ports as $port)
1714 {
1715 $ret[$port['object_id']]['id'] = $port['object_id'];
1b4a0a6a 1716 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
323edbbf
DO
1717 }
1718 return $ret;
1719}
1720
5fd2a004
DO
1721// search in IPv4 allocations
1722function getObjectIfacesSearchResults ($what)
1723{
1724 $ret = array();
1725 $ifaces = getSearchResultByField
1726 (
1727 'IPv4Allocation',
1728 array ('object_id', 'name'),
1729 'name',
1730 $what,
1731 'object_id'
1732 );
1733 foreach ($ifaces as $row)
1734 {
1735 $ret[$row['object_id']]['id'] = $row['object_id'];
1736 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1737 }
1738 return $ret;
1739}
1740
1741function getObjectNATSearchResults ($what)
1742{
1743 $ret = array();
1744 $ifaces = getSearchResultByField
1745 (
1746 'IPv4NAT',
1747 array ('object_id', 'description'),
1748 'description',
1749 $what,
1750 'object_id'
1751 );
1752 foreach ($ifaces as $row)
1753 {
1754 $ret[$row['object_id']]['id'] = $row['object_id'];
1755 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1756 }
1757 return $ret;
1758}
1759
1760// This function returns either port ID or NULL for specified arguments.
e673ee24
DO
1761// This function returns either port ID or NULL for specified arguments.
1762function getPortID ($object_id, $port_name)
1763{
e673ee24 1764 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
065eeb52 1765 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1766 $rows = $result->fetchAll (PDO::FETCH_NUM);
1767 if (count ($rows) != 1)
1768 return NULL;
1769 $ret = $rows[0][0];
1770 $result->closeCursor();
1771 return $ret;
1772}
1773
1774function commitCreateUserAccount ($username, $realname, $password)
1775{
1776 return useInsertBlade
1777 (
1778 'UserAccount',
1779 array
1780 (
1781 'user_name' => "'${username}'",
1782 'user_realname' => "'${realname}'",
1783 'user_password_hash' => "'${password}'"
1784 )
1785 );
1786}
1787
1788function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1789{
1790 global $dbxlink;
1791 $query =
1792 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1793 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1794 $result = $dbxlink->query ($query);
1795 if ($result == NULL)
1796 {
f41b492f 1797 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1798 die;
1799 }
1800 return TRUE;
1801}
1802
e673ee24
DO
1803// This function returns an array of all port type pairs from PortCompat table.
1804function getPortCompat ()
1805{
e673ee24
DO
1806 $query =
1807 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1808 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1809 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
10bac82a
DY
1810 "inner join Chapter as c1 on d1.chapter_id = c1.id " .
1811 "inner join Chapter as c2 on d2.chapter_id = c2.id " .
1812 "where c1.name = 'PortType' and c2.name = 'PortType'";
065eeb52 1813 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1814 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1815 $result->closeCursor();
1816 return $ret;
1817}
1818
1819function removePortCompat ($type1 = 0, $type2 = 0)
1820{
1821 global $dbxlink;
1822 if ($type1 == 0 or $type2 == 0)
1823 {
f41b492f 1824 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1825 die;
1826 }
1827 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1828 $result = $dbxlink->query ($query);
1829 if ($result == NULL)
1830 {
f41b492f 1831 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1832 die;
1833 }
1834 return TRUE;
1835}
1836
1837function addPortCompat ($type1 = 0, $type2 = 0)
1838{
1839 if ($type1 <= 0 or $type2 <= 0)
1840 {
f41b492f 1841 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1842 die;
1843 }
1844 return useInsertBlade
1845 (
1846 'PortCompat',
1847 array ('type1' => $type1, 'type2' => $type2)
1848 );
1849}
1850
da95280e
DO
1851function getDictStats ()
1852{
83884590 1853 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27);
da95280e 1854 $query =
10bac82a 1855 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
6530f34e 1856 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id";
065eeb52 1857 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1858 $tc = $tw = $uc = $uw = 0;
89fa639f 1859 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1860 {
1861 $tc++;
1862 $tw += $row['wc'];;
1863 if (in_array ($row['chapter_no'], $stock_chapters))
1864 continue;
1865 $uc++;
1866 $uw += $row['wc'];;
1867 }
89fa639f
DO
1868 $result->closeCursor();
1869 unset ($result);
a5efc857 1870 $query = "select count(object_id) as attrc from RackObject as ro left join " .
08b4cb24 1871 "AttributeValue as av on ro.id = av.object_id group by ro.id";
065eeb52 1872 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1873 $to = $ta = $so = 0;
89fa639f 1874 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1875 {
1876 $to++;
1877 if ($row['attrc'] != 0)
1878 {
1879 $so++;
1880 $ta += $row['attrc'];
1881 }
1882 }
89fa639f 1883 $result->closeCursor();
da95280e
DO
1884 $ret = array();
1885 $ret['Total chapters in dictionary'] = $tc;
1886 $ret['Total words in dictionary'] = $tw;
1887 $ret['User chapters'] = $uc;
1888 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1889 $ret['Total objects'] = $to;
1890 $ret['Objects with stickers'] = $so;
1891 $ret['Total stickers attached'] = $ta;
da95280e
DO
1892 return $ret;
1893}
1894
6807f0be 1895function getIPv4Stats ()
9ec5fdf1 1896{
9ec5fdf1
DO
1897 $ret = array();
1898 $subject = array();
706ce117
DO
1899 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1900 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1901 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1902 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1903 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1904 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1905 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1906 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
9ec5fdf1
DO
1907
1908 foreach ($subject as $item)
1909 {
065eeb52 1910 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
1911 $row = $result->fetch (PDO::FETCH_NUM);
1912 $ret[$item['txt']] = $row[0];
1913 $result->closeCursor();
1914 unset ($result);
1915 }
1916 return $ret;
1917}
1918
6807f0be 1919function getRackspaceStats ()
9ec5fdf1 1920{
9ec5fdf1
DO
1921 $ret = array();
1922 $subject = array();
10bac82a 1923 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
9ec5fdf1
DO
1924 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1925 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1926 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1927
1928 foreach ($subject as $item)
1929 {
065eeb52 1930 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1931 $row = $result->fetch (PDO::FETCH_NUM);
59a83bd8 1932 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1933 $result->closeCursor();
1934 unset ($result);
1935 }
1936 return $ret;
1937}
1938
6807f0be
DO
1939/*
1940
1941The following allows figuring out records in TagStorage, which refer to non-existing entities:
1942
120e9ddd
DO
1943mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1944mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1945mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1946mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1947mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1948mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1949mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
6807f0be
DO
1950
1951Accordingly, these are the records, which refer to non-existent tags:
1952
1953mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1954
1955*/
1956
826c3dbd 1957// chapter_no is a must, see at @commitReduceDictionary() why
e673ee24
DO
1958function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1959{
c5f84f48
DY
1960 if ($chapter_no <= 0)
1961 throw new InvalidArgException ('$chapter_no', $chapter_no);
1962 if ($dict_key <= 0)
1963 throw new InvalidArgException ('$dict_key', $dict_key);
1964 if (!strlen ($dict_value))
1965 throw new InvalidArgException ('$dict_value', $dict_value);
1966
e673ee24
DO
1967 global $dbxlink;
1968 $query =
10bac82a 1969 "update Dictionary set dict_value = '${dict_value}' where chapter_id=${chapter_no} " .
e673ee24
DO
1970 "and dict_key=${dict_key} limit 1";
1971 $result = $dbxlink->query ($query);
1972 if ($result == NULL)
1973 {
f41b492f 1974 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1975 die;
1976 }
1977 return TRUE;
1978}
1979
1980function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1981{
c5f84f48
DY
1982 if ($chapter_no <= 0)
1983 throw new InvalidArgException ('$chapter_no', $chapter_no);
1984 if (!strlen ($dict_value))
1985 throw new InvalidArgException ('$dict_value', $dict_value);
e673ee24
DO
1986 return useInsertBlade
1987 (
1988 'Dictionary',
10bac82a 1989 array ('chapter_id' => $chapter_no, 'dict_value' => "'${dict_value}'")
e673ee24
DO
1990 );
1991}
1992
178fda20
DO
1993// Technically dict_key is enough to delete, but including chapter_id into
1994// WHERE clause makes sure, that the action actually happends for the same
1995// chapter, which authorization was granted for.
e673ee24
DO
1996function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1997{
e673ee24
DO
1998 global $dbxlink;
1999 $query =
10bac82a 2000 "delete from Dictionary where chapter_id=${chapter_no} " .
e673ee24
DO
2001 "and dict_key=${dict_key} limit 1";
2002 $result = $dbxlink->query ($query);
2003 if ($result == NULL)
2004 {
f41b492f 2005 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2006 die;
2007 }
2008 return TRUE;
2009}
2010
2011function commitAddChapter ($chapter_name = '')
2012{
59a83bd8 2013 if (!strlen ($chapter_name))
c5f84f48 2014 throw new InvalidArgException ('$chapter_name', $chapter_name);
e673ee24
DO
2015 return useInsertBlade
2016 (
2017 'Chapter',
10bac82a 2018 array ('name' => "'${chapter_name}'")
e673ee24
DO
2019 );
2020}
2021
2022function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
2023{
178fda20 2024 if (!strlen ($chapter_name))
c5f84f48 2025 throw new InvalidArgException ('$chapter_name', $chapter_name);
e673ee24
DO
2026 global $dbxlink;
2027 $query =
10bac82a 2028 "update Chapter set name = '${chapter_name}' where id = ${chapter_no} " .
e673ee24
DO
2029 "and sticky = 'no' limit 1";
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
2039function commitDeleteChapter ($chapter_no = 0)
2040{
e673ee24
DO
2041 global $dbxlink;
2042 $query =
10bac82a 2043 "delete from Chapter where id = ${chapter_no} and sticky = 'no' limit 1";
e673ee24
DO
2044 $result = $dbxlink->query ($query);
2045 if ($result == NULL)
2046 {
f41b492f 2047 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2048 die;
2049 }
2050 return TRUE;
2051}
2052
4c330a14
DO
2053// This is a dictionary accessor. We perform link rendering, so the user sees
2054// nice <select> drop-downs.
7fa7047a 2055function readChapter ($chapter_id = 0, $style = '')
e673ee24 2056{
7fa7047a
DO
2057 if ($chapter_id <= 0)
2058 throw new InvalidArgException ('$chapter_id', $chapter_id);
e673ee24 2059 $query =
7fa7047a
DO
2060 "select dict_key, dict_value from Dictionary " .
2061 "where chapter_id = ${chapter_id}";
065eeb52 2062 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2063 $chapter = array();
2064 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7fa7047a 2065 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
e673ee24 2066 $result->closeCursor();
4aa8609b
DO
2067 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2068 asort ($chapter);
e673ee24
DO
2069 return $chapter;
2070}
2071
7fa7047a
DO
2072// Return refcounters for all given keys of the given chapter.
2073function getChapterRefc ($chapter_id, $keylist)
2074{
afdb3cf5
DO
2075 $ret = array();
2076 foreach ($keylist as $key)
2077 $ret[$key] = 0;
7fa7047a
DO
2078 switch ($chapter_id)
2079 {
2080 case CHAP_OBJTYPE:
2081 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
2082 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
2083 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ${chapter_id}";
2084 break;
2085 case CHAP_PORTTYPE:
2086 // PortType chapter is referenced by PortCompat and Port tables
2087 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
2088 '(select count(*) from Port where type = dict_key) as refcnt ' .
2089 "from Dictionary where chapter_id = ${chapter_id}";
2090 break;
2091 default:
2092 // Find the list of all assigned values of dictionary-addressed attributes, each with
2093 // chapter/word keyed reference counters.
2094 $query = "select uint_value, count(object_id) as refcnt " .
2095 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
2096 "inner join AttributeValue as av on a.id = av.attr_id " .
2097 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
2098 "where a.type = 'dict' and am.chapter_id = ${chapter_id} group by uint_value";
2099 break;
2100 }
2101 $result = useSelectBlade ($query, __FUNCTION__);
2102 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2103 $ret[$row['uint_value']] = $row['refcnt'];
2104 return $ret;
2105}
2106
e4e9e2a1
DO
2107// Return a list of all stickers with sticker map applied. Each sticker records will
2108// list all its ways on the map with refcnt set.
e673ee24
DO
2109function getAttrMap ()
2110{
e673ee24 2111 $query =
e4e9e2a1 2112 'SELECT id, type, name, chapter_id, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
7fa7047a 2113 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
e4e9e2a1
DO
2114 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
2115 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_id';
065eeb52 2116 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2117 $ret = array();
2118 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2119 {
e4e9e2a1
DO
2120 if (!isset ($ret[$row['id']]))
2121 $ret[$row['id']] = array
2122 (
2123 'id' => $row['id'],
2124 'type' => $row['type'],
2125 'name' => $row['name'],
2126 'application' => array(),
2127 );
e673ee24
DO
2128 if ($row['objtype_id'] == '')
2129 continue;
e4e9e2a1
DO
2130 $application = array
2131 (
2132 'objtype_id' => $row['objtype_id'],
e4e9e2a1
DO
2133 'refcnt' => $row['refcnt'],
2134 );
2135 if ($row['type'] == 'dict')
e673ee24 2136 {
50393983 2137 $application['chapter_no'] = $row['chapter_id'];
e673ee24
DO
2138 $application['chapter_name'] = $row['chapter_name'];
2139 }
e4e9e2a1 2140 $ret[$row['id']]['application'][] = $application;
e673ee24 2141 }
e673ee24
DO
2142 return $ret;
2143}
2144
2145function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2146{
59a83bd8 2147 if ($attr_id <= 0 or !strlen ($attr_name))
e673ee24 2148 {
f41b492f 2149 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2150 die;
2151 }
2152 global $dbxlink;
2153 $query =
10bac82a
DY
2154 "update Attribute set name = '${attr_name}' " .
2155 "where id = ${attr_id} limit 1";
e673ee24
DO
2156 $result = $dbxlink->query ($query);
2157 if ($result == NULL)
2158 {
f41b492f 2159 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
2160 die;
2161 }
2162 return TRUE;
2163}
2164
2165function commitAddAttribute ($attr_name = '', $attr_type = '')
2166{
59a83bd8 2167 if (!strlen ($attr_name))
e673ee24 2168 {
f41b492f 2169 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2170 die;
2171 }
2172 switch ($attr_type)
2173 {
2174 case 'uint':
2175 case 'float':
2176 case 'string':
2177 case 'dict':
2178 break;
2179 default:
f41b492f 2180 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2181 die;
2182 }
2183 return useInsertBlade
2184 (
2185 'Attribute',
10bac82a 2186 array ('name' => "'${attr_name}'", 'type' => "'${attr_type}'")
e673ee24
DO
2187 );
2188}
2189
2190function commitDeleteAttribute ($attr_id = 0)
2191{
2192 if ($attr_id <= 0)
2193 {
f41b492f 2194 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2195 die;
2196 }
10bac82a 2197 return useDeleteBlade ('Attribute', 'id', $attr_id);
e673ee24
DO
2198}
2199
2200// FIXME: don't store garbage in chapter_no for non-dictionary types.
2201function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2202{
7028a42c 2203 if ($attr_id <= 0 or $objtype_id <= 0)
e673ee24 2204 {
f41b492f 2205 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2206 die;
2207 }
2208 return useInsertBlade
2209 (
2210 'AttributeMap',
2211 array
2212 (
2213 'attr_id' => $attr_id,
2214 'objtype_id' => $objtype_id,
10bac82a 2215 'chapter_id' => $chapter_no
e673ee24
DO
2216 )
2217 );
2218}
2219
2220function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2221{
2222 if ($attr_id <= 0 or $objtype_id <= 0)
2223 {
f41b492f 2224 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2225 die;
2226 }
2227 global $dbxlink;
2228 $query =
2229 "delete from AttributeMap where attr_id=${attr_id} " .
2230 "and objtype_id=${objtype_id} limit 1";
2231 $result = $dbxlink->query ($query);
2232 if ($result == NULL)
2233 {
f41b492f 2234 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2235 die;
2236 }
2237 return TRUE;
2238}
2239
2240// This function returns all optional attributes for requested object
2241// as an array of records. NULL is returned on error and empty array
2242// is returned, if there are no attributes found.
7fa7047a 2243function getAttrValues ($object_id)
e673ee24
DO
2244{
2245 if ($object_id <= 0)
2246 {
f41b492f 2247 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
2248 return NULL;
2249 }
e673ee24
DO
2250 $ret = array();
2251 $query =
10bac82a 2252 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
7fa7047a 2253 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
e673ee24 2254 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
10bac82a 2255 "inner join Attribute as A on AM.attr_id = A.id " .
e673ee24 2256 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
10bac82a
DY
2257 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2258 "left join Chapter as C on AM.chapter_id = C.id " .
2259 "where RO.id = ${object_id} order by A.type, A.name";
065eeb52 2260 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2261 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2262 {
2263 $record = array();
2264 $record['id'] = $row['attr_id'];
2265 $record['name'] = $row['attr_name'];
2266 $record['type'] = $row['attr_type'];
2267 switch ($row['attr_type'])
2268 {
7fa7047a
DO
2269 case 'dict':
2270 $record['chapter_id'] = $row['chapter_id'];
2271 $record['chapter_name'] = $row['chapter_name'];
2272 $record['key'] = $row['uint_value'];
2273 // fall through
e673ee24
DO
2274 case 'uint':
2275 case 'float':
2276 case 'string':
24cbe8af 2277 $record['value'] = $row[$row['attr_type'] . '_value'];
7fa7047a 2278 $record['o_value'] = parseWikiLink ($record['value'], 'o');
24cbe8af
DO
2279 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2280 break;
e673ee24
DO
2281 default:
2282 $record['value'] = NULL;
2283 break;
2284 }
2285 $ret[$row['attr_id']] = $record;
2286 }
2287 $result->closeCursor();
2288 return $ret;
2289}
2290
2291function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2292{
2293 if ($object_id <= 0 or $attr_id <= 0)
2294 {
f41b492f 2295 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2296 die;
2297 }
2298 global $dbxlink;
2299 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2300 $result = $dbxlink->query ($query);
2301 if ($result == NULL)
2302 {
f41b492f 2303 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2304 die;
2305 }
2306 return TRUE;
2307}
2308
2309// FIXME: don't share common code with use commitResetAttrValue()
2310function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2311{
2312 if ($object_id <= 0 or $attr_id <= 0)
2313 {
f41b492f 2314 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2315 die;
2316 }
59a83bd8 2317 if (!strlen ($value))
e673ee24
DO
2318 return commitResetAttrValue ($object_id, $attr_id);
2319 global $dbxlink;
10bac82a 2320 $query1 = "select type as attr_type from Attribute where id = ${attr_id}";
e673ee24
DO
2321 $result = $dbxlink->query ($query1);
2322 if ($result == NULL)
2323 {
f41b492f 2324 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
2325 die;
2326 }
2327 $row = $result->fetch (PDO::FETCH_NUM);
2328 if ($row == NULL)
2329 {
f41b492f 2330 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
2331 die;
2332 }
2333 $attr_type = $row[0];
2334 $result->closeCursor();
2335 switch ($attr_type)
2336 {
2337 case 'uint':
2338 case 'float':
2339 case 'string':
2340 $column = $attr_type . '_value';
2341 break;
2342 case 'dict':
2343 $column = 'uint_value';
2344 break;
2345 default:
f41b492f 2346 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
2347 die;
2348 }
2349 $query2 =
2350 "delete from AttributeValue where " .
2351 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2352 $result = $dbxlink->query ($query2);
2353 if ($result == NULL)
2354 {
f41b492f 2355 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
2356 die;
2357 }
2358 // We know $value isn't empty here.
2359 $query3 =
2360 "insert into AttributeValue set ${column} = '${value}', " .
2361 "object_id = ${object_id}, attr_id = ${attr_id} ";
2362 $result = $dbxlink->query ($query3);
2363 if ($result == NULL)
2364 {
f41b492f 2365 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
2366 die;
2367 }
2368 return TRUE;
2369}
2370
2371function commitUseupPort ($port_id = 0)
2372{
2373 if ($port_id <= 0)
2374 {
f41b492f 2375 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
2376 die;
2377 }
2378 global $dbxlink;
2379 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2380 $result = $dbxlink->exec ($query);
2381 if ($result == NULL)
2382 {
f41b492f 2383 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
2384 die;
2385 }
2386 return TRUE;
2387
2388}
2389
2390// This is a swiss-knife blade to insert a record into a table.
2391// The first argument is table name.
2392// The second argument is an array of "name" => "value" pairs.
2393// The function returns either TRUE or FALSE (we expect one row
2394// to be inserted).
2395function useInsertBlade ($tablename, $values)
2396{
2397 global $dbxlink;
2398 $namelist = $valuelist = '';
2399 foreach ($values as $name => $value)
2400 {
2401 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2402 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2403 }
2404 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2405 $result = $dbxlink->exec ($query);
2406 if ($result != 1)
2407 return FALSE;
2408 return TRUE;
2409}
2410
2411// This swiss-knife blade deletes one record from the specified table
2412// using the specified key name and value.
f5575f12 2413function useDeleteBlade ($tablename, $keyname, $keyvalue)
e673ee24
DO
2414{
2415 global $dbxlink;
f5575f12 2416 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
e673ee24
DO
2417}
2418
5967b83d
DO
2419function useSelectBlade ($query, $caller = 'N/A')
2420{
2421 global $dbxlink;
2422 $result = $dbxlink->query ($query);
2423 if ($result == NULL)
2424 {
2425 $ei = $dbxlink->errorInfo();
105a3bc8 2426 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
2427 return NULL;
2428 }
2429 return $result;
2430}
2431
9c0b0016
DO
2432function loadConfigCache ()
2433{
4fe32e78 2434 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 2435 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
2436 $cache = array();
2437 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2438 $cache[$row['varname']] = $row;
2439 $result->closeCursor();
2440 return $cache;
2441}
2442
2443// setConfigVar() is expected to perform all necessary filtering
2444function storeConfigVar ($varname = NULL, $varvalue = NULL)
2445{
c461c579 2446 global $dbxlink;
c5f84f48
DY
2447 if (!strlen ($varname))
2448 throw new InvalidArgException ('$varname', $varname);
2449 if ($varvalue === NULL)
2450 throw new InvalidArgException ('$varvalue', $varvalue);
9c0b0016
DO
2451 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2452 $result = $dbxlink->query ($query);
2453 if ($result == NULL)
2454 {
f41b492f 2455 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
2456 return FALSE;
2457 }
2458 $rc = $result->rowCount();
2459 $result->closeCursor();
f7ee57a1 2460 if ($rc == 0 or $rc == 1)
9c0b0016 2461 return TRUE;
f41b492f 2462 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2463 return FALSE;
2464}
2465
fbbb74fb
DO
2466// Database version detector. Should behave corretly on any
2467// working dataset a user might have.
2468function getDatabaseVersion ()
2469{
2470 global $dbxlink;
2471 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2472 $result = $dbxlink->query ($query);
2473 if ($result == NULL)
2474 {
2475 $errorInfo = $dbxlink->errorInfo();
2476 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2477 return '0.14.4';
4d2e93f2 2478 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2479 }
2480 $rows = $result->fetchAll (PDO::FETCH_NUM);
59a83bd8 2481 if (count ($rows) != 1 || !strlen ($rows[0][0]))
fbbb74fb
DO
2482 {
2483 $result->closeCursor();
4d2e93f2 2484 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2485 }
2486 $ret = $rows[0][0];
2487 $result->closeCursor();
2488 return $ret;
2489}
2490
da04825a
DO
2491// Return an array of virtual services. For each of them list real server pools
2492// with their load balancers and other stats.
62a1dcb5
DO
2493function getSLBSummary ()
2494{
6fec9f39
DO
2495 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2496 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2497 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2498 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2499 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
6fec9f39 2500 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 2501 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2502 $ret = array();
2503 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2504 {
4cadac8f 2505 $vsid = $row['vsid'];
da04825a 2506 $object_id = $row['object_id'];
4cadac8f
DO
2507 if (!isset ($ret[$vsid]))
2508 {
2509 $ret[$vsid] = array();
13bffb29 2510 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2511 $ret[$vsid][$cname] = $row[$cname];
da04825a 2512 $ret[$vsid]['lblist'] = array();
4cadac8f 2513 }
6fec9f39
DO
2514 // There's only one assigned RS pool possible for each LB-VS combination.
2515 $ret[$vsid]['lblist'][$row['object_id']] = array
2516 (
2517 'id' => $row['rspool_id'],
2518 'size' => $row['rscount'],
2519 'name' => $row['pool_name']
2520 );
c3bdc503 2521 }
060ba26e 2522 $result->closeCursor();
c3bdc503 2523 return $ret;
62a1dcb5
DO
2524}
2525
7e7a8387 2526function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2527{
79a9edb4 2528 if ($pool_id <= 0)
c5f84f48 2529 throw new InvalidArgException ('$pool_id', $pool_id);
59a83bd8 2530 if (!strlen ($rsport) or $rsport === 0)
79a9edb4 2531 $rsport = 'NULL';
ca461127
DO
2532 return useInsertBlade
2533 (
706ce117 2534 'IPv4RS',
ca461127
DO
2535 array
2536 (
2537 'rsip' => "inet_aton('${rsip}')",
2538 'rsport' => $rsport,
2539 'rspool_id' => $pool_id,
bcbeadb4 2540 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
59a83bd8 2541 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
3241551e
DO
2542 )
2543 );
2544}
2545
c63a8d6e 2546function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21 2547{
c5f84f48
DY
2548 if (!strlen ($vip))
2549 throw new InvalidArgException ('$vip', $vip);
2550 if ($vport <= 0)
2551 throw new InvalidArgException ('$vport', $vport);
2552 if (!strlen ($proto))
2553 throw new InvalidArgException ('$proto', $proto);
c63a8d6e 2554 if (!useInsertBlade
d6517a21 2555 (
706ce117 2556 'IPv4VS',
d6517a21
DO
2557 array
2558 (
2559 'vip' => "inet_aton('${vip}')",
2560 'vport' => $vport,
2561 'proto' => "'${proto}'",
59a83bd8
DO
2562 'name' => (!strlen ($name) ? 'NULL' : "'${name}'"),
2563 'vsconfig' => (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2564 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
d6517a21 2565 )
c63a8d6e
DO
2566 ))
2567 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2568 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2569}
2570
c1ca768c 2571function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2572{
c5f84f48
DY
2573 if ($pool_id <= 0)
2574 throw new InvalidArgException ('$pool_id', $pool_id);
2575 if ($object_id <= 0)
2576 throw new InvalidArgException ('$object_id', $object_id);
2577 if ($vs_id <= 0)
2578 throw new InvalidArgException ('$vs_id', $vs_id);
3241551e
DO
2579 return useInsertBlade
2580 (
706ce117 2581 'IPv4LB',
3241551e
DO
2582 array
2583 (
2584 'object_id' => $object_id,
2585 'rspool_id' => $pool_id,
c1ca768c 2586 'vs_id' => $vs_id,
59a83bd8
DO
2587 'vsconfig' => (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2588 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
3241551e 2589 )
ca461127
DO
2590 );
2591}
2592
fb1c4a54
DO
2593function commitDeleteRS ($id = 0)
2594{
2595 if ($id <= 0)
2596 return FALSE;
706ce117 2597 return useDeleteBlade ('IPv4RS', 'id', $id);
fb1c4a54
DO
2598}
2599
d6517a21
DO
2600function commitDeleteVS ($id = 0)
2601{
6657739e 2602 releaseFiles ('ipv4vs', $id);
706ce117 2603 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2604}
2605
c1ca768c 2606function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2607{
2608 global $dbxlink;
c4d85fd1 2609 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2610 return FALSE;
706ce117 2611 $query = "delete from IPv4LB where object_id = ${object_id} and " .
c1ca768c 2612 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2613 $result = $dbxlink->exec ($query);
2614 if ($result === NULL)
2615 return FALSE;
2616 elseif ($result != 1)
2617 return FALSE;
2618 else
2619 return TRUE;
2620}
2621
fb1c4a54
DO
2622function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2623{
fb1c4a54 2624 if (long2ip (ip2long ($rsip)) !== $rsip)
c5f84f48 2625 throw new InvalidArgException ('$rsip', $rsip);
59a83bd8 2626 if (!strlen ($rsport) or $rsport === 0)
79a9edb4 2627 $rsport = 'NULL';
fb1c4a54
DO
2628 global $dbxlink;
2629 $query =
706ce117 2630 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
59a83bd8 2631 (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2632 " where id = ${rsid} limit 1";
2633 $result = $dbxlink->query ($query);
2634 if ($result == NULL)
2635 {
2636 showError ("SQL query '${query}' failed", __FUNCTION__);
2637 die;
2638 }
2639 return TRUE;
2640}
2641
c1ca768c 2642function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2643{
3241551e
DO
2644 global $dbxlink;
2645 $query =
706ce117 2646 "update IPv4LB set vsconfig = " .
59a83bd8 2647 (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
3241551e 2648 ', rsconfig = ' .
59a83bd8 2649 (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2650 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2651 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2652 $result = $dbxlink->exec ($query);
2653 if ($result === NULL)
2654 return FALSE;
3241551e
DO
2655 else
2656 return TRUE;
2657}
2658
d6517a21
DO
2659function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2660{
c5f84f48
DY
2661 if (!strlen ($vip))
2662 throw new InvalidArgException ('$vip', $vip);
2663 if ($vport <= 0)
2664 throw new InvalidArgException ('$vport', $vport);
2665 if (!strlen ($proto))
2666 throw new InvalidArgException ('$proto', $proto);
d6517a21 2667 global $dbxlink;
706ce117 2668 $query = "update IPv4VS set " .
d6517a21
DO
2669 "vip = inet_aton('${vip}'), " .
2670 "vport = ${vport}, " .
2671 "proto = '${proto}', " .
59a83bd8
DO
2672 'name = ' . (!strlen ($name) ? 'NULL,' : "'${name}', ") .
2673 'vsconfig = ' . (!strlen ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2674 'rsconfig = ' . (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
5ad76f01 2675 " where id = ${vsid} limit 1";
d6517a21
DO
2676 $result = $dbxlink->exec ($query);
2677 if ($result === NULL)
2678 return FALSE;
d6517a21
DO
2679 else
2680 return TRUE;
2681}
2682
5a1680d2
DO
2683function loadThumbCache ($rack_id = 0)
2684{
5a1680d2
DO
2685 $ret = NULL;
2686 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2687 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2688 $row = $result->fetch (PDO::FETCH_ASSOC);
2689 if ($row)
2690 $ret = base64_decode ($row['thumb_data']);
2691 $result->closeCursor();
2692 return $ret;
2693}
2694
2695function saveThumbCache ($rack_id = 0, $cache = NULL)
2696{
2697 global $dbxlink;
178fda20 2698 if ($cache == NULL)
c5f84f48 2699 throw new InvalidArgException ('$cache', $cache);
5a1680d2
DO
2700 $data = base64_encode ($cache);
2701 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2702 $result = $dbxlink->exec ($query);
2703}
9a81d416 2704
c7fe33be
DO
2705function resetThumbCache ($rack_id = 0)
2706{
2707 global $dbxlink;
c7fe33be
DO
2708 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2709 $result = $dbxlink->exec ($query);
2710}
2711
748805bf 2712// Return the list of attached RS pools for the given object. As long as we have
706ce117 2713// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2714// by vs_id, because there will be only one RS pool listed for each VS of the
2715// current object.
78e7b769
DO
2716function getRSPoolsForObject ($object_id = 0)
2717{
748805bf 2718 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2719 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2720 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2721 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2722 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
748805bf
DO
2723 "where lb.object_id = ${object_id} " .
2724 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2725 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2726 $ret = array ();
78e7b769 2727 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2728 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2729 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2730 $result->closeCursor();
748805bf 2731 return $ret;
78e7b769
DO
2732}
2733
c63a8d6e 2734function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2735{
59a83bd8 2736 if (!strlen ($name))
c5f84f48 2737 throw new InvalidArgException ('$name', $name);
c63a8d6e 2738 if (!useInsertBlade
5ad76f01 2739 (
706ce117 2740 'IPv4RSPool',
5ad76f01
DO
2741 array
2742 (
59a83bd8
DO
2743 'name' => (!strlen ($name) ? 'NULL' : "'${name}'"),
2744 'vsconfig' => (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2745 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
5ad76f01 2746 )
c63a8d6e
DO
2747 ))
2748 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2749 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2750}
2751
2752function commitDeleteRSPool ($pool_id = 0)
2753{
2754 global $dbxlink;
2755 if ($pool_id <= 0)
2756 return FALSE;
6657739e 2757 releaseFiles ('ipv4rspool', $pool_id);
706ce117 2758 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2759}
2760
2761function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2762{
5ad76f01 2763 global $dbxlink;
706ce117 2764 $query = "update IPv4RSPool set " .
59a83bd8
DO
2765 'name = ' . (!strlen ($name) ? 'NULL,' : "'${name}', ") .
2766 'vsconfig = ' . (!strlen ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2767 'rsconfig = ' . (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
5ad76f01
DO
2768 " where id = ${pool_id} limit 1";
2769 $result = $dbxlink->exec ($query);
2770 if ($result === NULL)
2771 return FALSE;
2772 elseif ($result != 1)
2773 return FALSE;
2774 else
2775 return TRUE;
2776}
2777
8253d9f0
DO
2778function getRSList ()
2779{
1f7d18fa 2780 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
706ce117 2781 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
065eeb52 2782 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2783 $ret = array ();
8253d9f0 2784 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2785 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2786 $ret[$row['id']][$cname] = $row[$cname];
2787 $result->closeCursor();
2788 return $ret;
2789}
2790
2791// Return the list of all currently configured load balancers with their pool count.
2792function getLBList ()
2793{
4b0932b6 2794 $query = "select object_id, count(rspool_id) as poolcount " .
706ce117 2795 "from IPv4LB group by object_id order by object_id";
065eeb52 2796 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2797 $ret = array ();
2798 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2799 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2800 $result->closeCursor();
4b0932b6 2801 return $ret;
8253d9f0
DO
2802}
2803
178fda20 2804// For the given object return: its vsconfig/rsconfig; the list of RS pools
9e677cbd
DO
2805// attached (each with vsconfig/rsconfig in turn), each with the list of
2806// virtual services terminating the pool. Each pool also lists all real
2807// servers with rsconfig.
2987fc1f 2808function getSLBConfig ($object_id)
9e677cbd 2809{
9e677cbd 2810 $ret = array();
d91f08f3
DO
2811 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2812 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2813 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2814 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2815 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2816 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2817 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2818 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2819 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2820 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2821 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2822 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2823 {
d91f08f3
DO
2824 $vs_id = $row['vs_id'];
2825 if (!isset ($ret[$vs_id]))
2826 {
2827 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)
2828 $ret[$vs_id][$c] = $row[$c];
2829 $ret[$vs_id]['rslist'] = array();
2830 }
2831 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2832 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2833 }
2834 $result->closeCursor();
2835 return $ret;
2836}
1f7d18fa
DO
2837
2838function commitSetInService ($rs_id = 0, $inservice = '')
2839{
c5f84f48
DY
2840 if (!strlen ($inservice))
2841 throw new InvalidArgException ('$inservice', $inservice);
2842 if ($rs_id <= 0)
2843 throw new InvalidArgException ('$rs_id', $rs_id);
1f7d18fa 2844 global $dbxlink;
706ce117 2845 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
1f7d18fa
DO
2846 $result = $dbxlink->exec ($query);
2847 if ($result === NULL)
2848 return FALSE;
2849 elseif ($result != 1)
2850 return FALSE;
2851 else
2852 return TRUE;
2853}
2854
ad0e4754
DO
2855function executeAutoPorts ($object_id = 0, $type_id = 0)
2856{
c5f84f48
DY
2857 if ($object_id == 0)
2858 throw new InvalidArgException ('$object_id', $object_id);
2859 if ($type_id == 0)
2860 throw new InvalidArgException ('$type_id', $type_id);
f3f0161f 2861 $ret = TRUE;
118e4c38 2862 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2863 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2864 return $ret;
ad0e4754
DO
2865}
2866
6e49bd1f 2867// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2868// generated/deducted later at higher levels.
aab37bc0 2869// Result is a chain: randomly indexed taginfo list.
f9bc186f 2870function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2871{
a6e8d544 2872 $ret = array();
2c21a10c
DO
2873 if (!in_array ($entity_realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2874 return $ret;
edf0993c
DO
2875 $query = "select tt.id, tag from " .
2876 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
120e9ddd 2877 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
edf0993c
DO
2878 "order by tt.tag";
2879 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2880 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2881 $ret[$row['id']] = $row;
a6e8d544 2882 $result->closeCursor();
aab37bc0 2883 return getExplicitTagsOnly ($ret);
5967b83d
DO
2884}
2885
351c0966 2886// Return a tag chain with all DB tags on it.
5967b83d
DO
2887function getTagList ()
2888{
20c901a7 2889 $ret = array();
120e9ddd 2890 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2891 "from TagTree left join TagStorage on id = tag_id " .
120e9ddd 2892 "group by id, entity_realm order by tag";
065eeb52 2893 $result = useSelectBlade ($query, __FUNCTION__);
fb7a4967
DO
2894 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2895 // which is utf8_general_ci for UTF-8.
5967b83d 2896 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2897 {
7cc02fc1 2898 if (!isset ($ret[$row['id']]))
20c901a7 2899 $ret[$row['id']] = array
5b7bd02e
DO
2900 (
2901 'id' => $row['id'],
2902 'tag' => $row['tag'],
fb7a4967 2903 'ci' => $ci++,
5b7bd02e 2904 'parent_id' => $row['parent_id'],
9e51318b 2905 'refcnt' => array ('total' => 0)
5b7bd02e
DO
2906 );
2907 if ($row['realm'])
9e51318b 2908 {
20c901a7 2909 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
9e51318b
DO
2910 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2911 }
5b7bd02e 2912 }
5967b83d 2913 $result->closeCursor();
20c901a7 2914 return $ret;
5967b83d
DO
2915}
2916
fe7044ad
DO
2917function commitCreateTag ($tagname = '', $parent_id = 0)
2918{
2919 if ($tagname == '' or $parent_id === 0)
2920 return "Invalid args to " . __FUNCTION__;
2921 $result = useInsertBlade
2922 (
2923 'TagTree',
2924 array
2925 (
2926 'tag' => "'${tagname}'",
2927 'parent_id' => $parent_id
2928 )
2929 );
2930 if ($result)
2931 return '';
9f572fb5
DO
2932 global $dbxlink;
2933 if ($dbxlink->errorCode() == 23000) // integrity constraint violation
2934 {
2935 $ei = $dbxlink->errorInfo();
2936 if ($ei[1] == 1062)
2937 return 'tag name must be unique';
2938 if ($ei[1] == 1452)
2939 return "parent tag id ${parent_id} does not exist";
2940 }
2941 return "SQL query failed in " . __FUNCTION__;
fe7044ad
DO
2942}
2943
2944function commitDestroyTag ($tagid = 0)
2945{
2946 if ($tagid == 0)
2947 return 'Invalid arg to ' . __FUNCTION__;
f5575f12 2948 if (useDeleteBlade ('TagTree', 'id', $tagid))
fe7044ad
DO
2949 return '';
2950 else
2951 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2952}
f9bc186f 2953
49fb1027 2954function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2955{
49fb1027
DO
2956 if ($parent_id == 0)
2957 $parent_id = 'NULL';
f9bc186f 2958 global $dbxlink;
49fb1027
DO
2959 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2960 "where id = ${tag_id} limit 1";
f9bc186f 2961 $result = $dbxlink->exec ($query);
590e1281
DO
2962 if ($result !== FALSE)
2963 return '';
9f572fb5
DO
2964 if ($dbxlink->errorCode() == 23000)
2965 {
2966 $ei = $dbxlink->errorInfo();
2967 if ($ei[1] == 1062)
2968 return 'tag name must be unique';
2969 if ($ei[1] == 1452)
2970 return "parent tag id ${parent_id} does not exist";
2971 }
2972 return 'SQL query failed in ' . __FUNCTION__;
f9bc186f
DO
2973}
2974
01b6b4d6
DO
2975// Drop the whole chain stored.
2976function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af
DO
2977{
2978 global $dbxlink;
120e9ddd 2979 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
aedf18af
DO
2980 $result = $dbxlink->exec ($query);
2981 if ($result === NULL)
2982 return FALSE;
2983 else
2984 return TRUE;
2985}
2986
01b6b4d6 2987// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
29c3a4d8
DO
2988// FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2989// but not now.
01b6b4d6
DO
2990function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2991{
2992 global $dbxlink;
120e9ddd 2993 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
01b6b4d6
DO
2994 $result = $dbxlink->exec ($query);
2995 if ($result === NULL)
2996 return FALSE;
2997 else
2998 return TRUE;
2999}
3000
351c0966 3001// Push a record into TagStorage unconditionally.
3355ca56 3002function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 3003{
59a83bd8 3004 if (!strlen ($realm))
3355ca56 3005 return FALSE;
eb6ea26f
DO
3006 return useInsertBlade
3007 (
3008 'TagStorage',
3009 array
3010 (
120e9ddd
DO
3011 'entity_realm' => "'${realm}'",
3012 'entity_id' => $entity_id,
eb6ea26f
DO
3013 'tag_id' => $tag_id,
3014 )
3015 );
3016}
3017
351c0966 3018// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
3019// on the implicit list already). Then remove any other records, which
3020// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
3021// that both the tag base is still minimal and all requested tags appear on
3022// the resulting tag chain.
abef7149
DO
3023// Return TRUE, if any changes were committed.
3024function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3025{
3026 // Put the current explicit sub-chain into a buffer and merge all tags from
3027 // the extra chain, which aren't there yet.
3028 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3029 foreach ($extrachain as $extratag)
3030 if (!tagOnChain ($extratag, $newchain))
3031 $newchain[] = $extratag;
3032 // Then minimize the working buffer and check if it differs from the original
3033 // chain we started with. If it is so, save the work and signal the upper layer.
3034 $newchain = getExplicitTagsOnly ($newchain);
3035 if (tagChainCmp ($oldchain, $newchain))
3036 {
01b6b4d6 3037 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
3038 foreach ($newchain as $taginfo)
3039 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3040 return TRUE;
3041 }
3042 return FALSE;
351c0966
DO
3043}
3044
3045// Presume, that the target record has no tags attached.
3046function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3047{
3048 if (!count ($tagidlist))
c63a8d6e
DO
3049 return '';
3050 if (!$last_insert_id)
3051 $last_insert_id = lastInsertID();
3052 $errcount = 0;
abef7149 3053 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 3054 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
3055 $errcount++;
3056 if (!$errcount)
3057 return '';
3058 else
3059 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3060}
3061
42023f03
DO
3062function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3063{
3064 // $range is in x.x.x.x/x format, split into ip/mask vars
3065 $rangeArray = explode('/', $range);
3066 if (count ($rangeArray) != 2)
3067 return "Invalid IPv4 prefix '${range}'";
3068 $ip = $rangeArray[0];
3069 $mask = $rangeArray[1];
3070
59a83bd8 3071 if (!strlen ($ip) or !strlen ($mask))
42023f03
DO
3072 return "Invalid IPv4 prefix '${range}'";
3073 $ipL = ip2long($ip);
3074 $maskL = ip2long($mask);
3075 if ($ipL == -1 || $ipL === FALSE)
3076 return 'Bad IPv4 address';
3077 if ($mask < 32 && $mask > 0)
3078 $maskL = $mask;
3079 else
3080 {
3081 $maskB = decbin($maskL);
3082 if (strlen($maskB)!=32)
3083 return 'Invalid netmask';
3084 $ones=0;
3085 $zeroes=FALSE;
3086 foreach( str_split ($maskB) as $digit)
3087 {
3088 if ($digit == '0')
3089 $zeroes = TRUE;
3090 if ($digit == '1')
3091 {
3092 $ones++;
3093 if ($zeroes == TRUE)
3094 return 'Invalid netmask';
3095 }
3096 }
3097 $maskL = $ones;
3098 }
3099 $binmask = binMaskFromDec($maskL);
3100 $ipL = $ipL & $binmask;
42023f03
DO
3101 $result = useInsertBlade
3102 (
706ce117 3103 'IPv4Network',
42023f03
DO
3104 array
3105 (
3106 'ip' => sprintf ('%u', $ipL),
3107 'mask' => "'${maskL}'",
3108 'name' => "'${name}'"
3109 )
3110 );
e782fca4
DO
3111 if ($result != TRUE)
3112 return "Could not add ${range} (already exists?).";
42023f03
DO
3113
3114 if ($is_bcast and $maskL < 31)
3115 {
3116 $network_addr = long2ip ($ipL);
3117 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3118 updateAddress ($network_addr, 'network', 'yes');
3119 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3120 }
351c0966 3121 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
3122}
3123
706ce117 3124// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
3125function destroyIPv4Prefix ($id = 0)
3126{
3127 if ($id <= 0)
3128 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
6657739e 3129 releaseFiles ('ipv4net', $id);
706ce117 3130 if (!useDeleteBlade ('IPv4Network', 'id', $id))
42023f03 3131 return __FUNCTION__ . ': SQL query #1 failed';
01b6b4d6 3132 if (!destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
3133 return __FUNCTION__ . ': SQL query #2 failed';
3134 return '';
3135}
3136
ebae41b3
DO
3137function loadScript ($name)
3138{
3139 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3140 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
3141 if ($row !== FALSE)
3142 return $row[0];
3143 else
3144 return NULL;
ebae41b3
DO
3145}
3146
178fda20 3147function saveScript ($name = '', $text)
ebae41b3 3148{
59a83bd8 3149 if (!strlen ($name))
c5f84f48 3150 throw new InvalidArgException ('$name', $name);
4a6a28f1 3151 // delete regardless of existence
f5575f12 3152 useDeleteBlade ('Script', 'script_name', "'${name}'");
4a6a28f1 3153 return useInsertBlade
ebae41b3
DO
3154 (
3155 'Script',
3156 array
3157 (
3158 'script_name' => "'${name}'",
3159 'script_text' => "'${text}'"
3160 )
3161 );
3162}
3163
d983f70a
DO
3164function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3165{
3166 if (NULL === getIPv4AddressNetworkId ($localip))
3167 return "$localip: Non existant ip";
0929db7f 3168 if (NULL === getIPv4AddressNetworkId ($remoteip))
d983f70a
DO
3169 return "$remoteip: Non existant ip";
3170 if ( ($localport <= 0) or ($localport >= 65536) )
3171 return "$localport: invaild port";
3172 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3173 return "$remoteport: invaild port";
3174
3175 $result = useInsertBlade
3176 (
706ce117 3177 'IPv4NAT',
d983f70a
DO
3178 array
3179 (
3180 'object_id' => $object_id,
3181 'localip' => "INET_ATON('${localip}')",
3182 'remoteip' => "INET_ATON('$remoteip')",
3183 'localport' => $localport,
3184 'remoteport' => $remoteport,
3185 'proto' => "'${proto}'",
3186 'description' => "'${description}'",
3187 )
3188 );
3189 if ($result)
3190 return '';
3191 else
3192 return __FUNCTION__ . ': Failed to insert the rule.';
3193}
3194
3195function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3196{
3197 global $dbxlink;
3198
3199 $query =
706ce117 3200 "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
3201 $result = $dbxlink->exec ($query);
3202 return '';
3203}
3204
3205function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3206{
3207 global $dbxlink;
3208
3209 $query =
706ce117 3210 "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
3211 $result = $dbxlink->exec ($query);
3212 return '';
3213}
3214
3215function getNATv4ForObject ($object_id)
3216{
3217 $ret = array();
3218 $ret['out'] = array();
3219 $ret['in'] = array();
3220 $query =
3221 "select ".
3222 "proto, ".
3223 "INET_NTOA(localip) as localip, ".
3224 "localport, ".
3225 "INET_NTOA(remoteip) as remoteip, ".
3226 "remoteport, ".
3227 "ipa1.name as local_addr_name, " .
3228 "ipa2.name as remote_addr_name, " .
3229 "description ".
706ce117
DO
3230 "from IPv4NAT ".
3231 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3232 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
d983f70a
DO
3233 "where object_id='$object_id' ".
3234 "order by localip, localport, proto, remoteip, remoteport";
3235 $result = useSelectBlade ($query, __FUNCTION__);
3236 $count=0;
3237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3238 {
3239 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3240 $ret['out'][$count][$cname] = $row[$cname];
3241 $count++;
3242 }
3243 $result->closeCursor();
3244 unset ($result);
3245
3246 $query =
3247 "select ".
3248 "proto, ".
3249 "INET_NTOA(localip) as localip, ".
3250 "localport, ".
3251 "INET_NTOA(remoteip) as remoteip, ".
3252 "remoteport, ".
706ce117 3253 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
3254 "RackObject.name as object_name, ".
3255 "description ".
706ce117
DO
3256 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3257 "where IPv4Allocation.object_id='$object_id' ".
d983f70a
DO
3258 "order by remoteip, remoteport, proto, localip, localport";
3259 $result = useSelectBlade ($query, __FUNCTION__);
3260 $count=0;
3261 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3262 {
3263 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3264 $ret['in'][$count][$cname] = $row[$cname];
3265 $count++;
3266 }
3267 $result->closeCursor();
3268
3269 return $ret;
3270}
3271
178fda20 3272// Return a list of files, which are not linked to the specified record. This list
121496b6 3273// will be used by printSelect().
e1ae3fb4
AD
3274function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3275{
c5f84f48
DY
3276 if ($entity_type == NULL)
3277 throw new InvalidArgException ('$entity_type', $entity_type);
3278 if ($entity_id == 0)
3279 throw new InvalidArgException ('$entity_id', $entity_id);
e1ae3fb4
AD
3280 global $dbxlink;
3281 $sql =
121496b6 3282 'SELECT id, name FROM File ' .
e1ae3fb4 3283 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
121496b6 3284 'ORDER BY name, id';
e1ae3fb4
AD
3285 $query = $dbxlink->prepare($sql);
3286 $query->bindParam(1, $entity_type);
3287 $query->bindParam(2, $entity_id);
3288 $query->execute();
3289 $ret=array();
e1ae3fb4 3290 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3291 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3292 return $ret;
3293}
3294
6df2025d
DO
3295// FIXME: return a standard cell list, so upper layer can iterate over
3296// it conveniently.
e1ae3fb4
AD
3297function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3298{
c5f84f48
DY
3299 if ($entity_type === NULL)
3300 throw new InvalidArgException ('$entity_type', $entity_type);
3301 if ($entity_id <= 0)
3302 throw new InvalidArgException ('$entity_id', $entity_id);
e1ae3fb4
AD
3303 global $dbxlink;
3304 $sql =
3305 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3306 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3307 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3308 $query = $dbxlink->prepare($sql);
3309 $query->bindParam(1, $entity_type);
3310 $query->bindParam(2, $entity_id);
3311 $query->execute();
3312 $ret = array();
3313 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3314 $ret[$row['file_id']] = array (
b3567368 3315 'id' => $row['file_id'],
e1ae3fb4
AD
3316 'link_id' => $row['link_id'],
3317 'name' => $row['name'],
3318 'type' => $row['type'],
3319 'size' => $row['size'],
3320 'ctime' => $row['ctime'],
3321 'mtime' => $row['mtime'],
3322 'atime' => $row['atime'],
3323 'comment' => $row['comment'],
3324 );
3325 return $ret;
3326}
3327
3328function getFile ($file_id = 0)
3329{
e1ae3fb4
AD
3330 global $dbxlink;
3331 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3332 $query->bindParam(1, $file_id);
3333 $query->execute();
3334 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3335 {
3336 showError ('Query succeeded, but returned no data', __FUNCTION__);
3337 $ret = NULL;
3338 }
3339 else
3340 {
3341 $ret = array();
3342 $ret['id'] = $row['id'];
3343 $ret['name'] = $row['name'];
3344 $ret['type'] = $row['type'];
3345 $ret['size'] = $row['size'];
3346 $ret['ctime'] = $row['ctime'];
3347 $ret['mtime'] = $row['mtime'];
3348 $ret['atime'] = $row['atime'];
3349 $ret['contents'] = $row['contents'];
3350 $ret['comment'] = $row['comment'];
bed9cd76 3351 $query->closeCursor();
e1ae3fb4 3352
deb3da1b 3353 // Someone accessed this file, update atime
e1ae3fb4
AD
3354 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3355 $q_atime->bindParam(1, date('YmdHis'));
3356 $q_atime->bindParam(2, $file_id);
3357 $q_atime->execute();
3358 }
e1ae3fb4
AD
3359 return $ret;
3360}
3361
e1ae3fb4
AD
3362function getFileLinks ($file_id = 0)
3363{
e1ae3fb4 3364 global $dbxlink;
8bc5d1e4 3365 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ? ORDER BY entity_type, entity_id');
e1ae3fb4
AD
3366 $query->bindParam(1, $file_id);
3367 $query->execute();
da3302ab 3368 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3369 $ret = array();
da3302ab 3370 foreach ($rows as $row)
e1ae3fb4
AD
3371 {
3372 // get info of the parent
3373 switch ($row['entity_type'])
3374 {
3375 case 'ipv4net':
3376 $page = 'ipv4net';
3377 $id_name = 'id';
d724d290 3378 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3379 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3380 break;
3381 case 'ipv4rspool':
3854af78 3382 $page = 'ipv4rspool';
e1ae3fb4 3383 $id_name = 'pool_id';
a6e91ac2 3384 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3385 $name = $parent['name'];
3386 break;
3387 case 'ipv4vs':
3388 $page = 'ipv4vs';
3389 $id_name = 'vs_id';
7c38462f 3390 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3391 $name = $parent['name'];
3392 break;
3393 case 'object':
3394 $page = 'object';
3395 $id_name = 'object_id';
6297d584 3396 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
7ddbcf59 3397 $name = $parent['dname'];
e1ae3fb4
AD
3398 break;
3399 case 'rack':
3400 $page = 'rack';
3401 $id_name = 'rack_id';
61a1d996 3402 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3403 $name = $parent['name'];
3404 break;
3405 case 'user':
3406 $page = 'user';
3407 $id_name = 'user_id';
0b2c74cb
DO
3408 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3409 $name = $parent['user_name'];
e1ae3fb4
AD
3410 break;
3411 }
3412
17d95c32 3413 // name needs to have some value for hrefs to work
59a83bd8 3414 if (!strlen ($name))
17d95c32
AD
3415 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3416
e1ae3fb4
AD
3417 $ret[$row['id']] = array(
3418 'page' => $page,
3419 'id_name' => $id_name,
3420 'entity_type' => $row['entity_type'],
3421 'entity_id' => $row['entity_id'],
3422 'name' => $name
3423 );
3424 }
3425 return $ret;
3426}
3427
0b97b8f0 3428function getFileStats ()
e1ae3fb4 3429{
e1ae3fb4 3430 $query = 'SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type';
e1ae3fb4
AD
3431 $result = useSelectBlade ($query, __FUNCTION__);
3432 $ret = array();
e1ae3fb4
AD
3433 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3434 if ($row['count'] > 0)
0b97b8f0
DO
3435 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3436 unset ($result);
e1ae3fb4
AD
3437
3438 // Find number of files without any linkage
3439 $linkless_sql =
3440 'SELECT COUNT(*) ' .
3441 'FROM File ' .
3442 'WHERE id NOT IN (SELECT file_id FROM FileLink)';
0b97b8f0
DO
3443 $result = useSelectBlade ($linkless_sql, __FUNCTION__);
3444 $ret["Unattached files"] = $result->fetchColumn ();
3445 unset ($result);
e1ae3fb4
AD
3446
3447 // Find total number of files
3448 $total_sql = 'SELECT COUNT(*) FROM File';
0b97b8f0
DO
3449 $result = useSelectBlade ($total_sql, __FUNCTION__);
3450 $ret["Total files"] = $result->fetchColumn ();
e1ae3fb4 3451
e1ae3fb4
AD
3452 return $ret;
3453}
3454
3455function commitAddFile ($name, $type, $size, $contents, $comment)
3456{
3457 $now = date('YmdHis');
3458
3459 global $dbxlink;
3460 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3461 $query->bindParam(1, $name);
3462 $query->bindParam(2, $type);
3463 $query->bindParam(3, $size);
3464 $query->bindParam(4, $now);
3465 $query->bindParam(5, $now);
3466 $query->bindParam(6, $now);
3467 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3468 $query->bindParam(8, $comment);
3469
3470 $result = $query->execute();
3471
3472
3473 if ($result)
3474 return '';
590e1281 3475 elseif ($query->errorCode() == 23000)
13edfa1c 3476 return "commitAddFile: File named '${name}' already exists";
e1ae3fb4
AD
3477 else
3478 return 'commitAddFile: SQL query failed';
3479}
3480
4a2c6c6b 3481function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4
AD
3482{
3483 global $dbxlink;
3484 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3485 $query->bindParam(1, $file_id);
4a2c6c6b
AD
3486 $query->bindParam(2, $entity_type);
3487 $query->bindParam(3, $entity_id);
e1ae3fb4
AD
3488
3489 $result = $query->execute();
3490
3491 if ($result)
3492 return '';
3493 else
3494 return 'commitLinkFile: SQL query failed';
3495}
3496
f8874cdb 3497function commitReplaceFile ($file_id = 0, $contents)
fd1fb420 3498{
fd1fb420 3499 global $dbxlink;
f8874cdb
DO
3500 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3501 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3502 $query->bindParam(2, $file_id);
fd1fb420
AD
3503
3504 $result = $query->execute();
3505 if (!$result)
3506 {
3507 showError ('commitReplaceFile: SQL query failed', __FUNCTION__);
3508 return FALSE;
3509 }
3510 return '';
3511}
3512
9db67d95 3513function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
e1ae3fb4 3514{
c5f84f48
DY
3515 if (!strlen ($new_name))
3516 throw new InvalidArgException ('$new_name', $new_name);
3517 if (!strlen ($new_type))
3518 throw new InvalidArgException ('$new_type', $new_type);
e1ae3fb4 3519 global $dbxlink;
9db67d95 3520 $query = $dbxlink->prepare('UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?');
6ee41bd4 3521 $query->bindParam(1, $new_name);
9db67d95
DO
3522 $query->bindParam(2, $new_type);
3523 $query->bindParam(3, $new_comment);
3524 $query->bindParam(4, $file_id);
e1ae3fb4
AD
3525
3526 $result = $query->execute();
3527 if (!$result)
6ee41bd4 3528 return 'SQL query failed in ' . __FUNCTION__;
e1ae3fb4
AD
3529 return '';
3530}
3531
3532function commitUnlinkFile ($link_id)
3533{
3534 if (useDeleteBlade ('FileLink', 'id', $link_id) != TRUE)
3535 return __FUNCTION__ . ': useDeleteBlade() failed';
3536 return '';
3537}
3538
3539function commitDeleteFile ($file_id)
3540{
29c3a4d8 3541 destroyTagsForEntity ('file', $file_id);
e1ae3fb4
AD
3542 if (useDeleteBlade ('File', 'id', $file_id) != TRUE)
3543 return __FUNCTION__ . ': useDeleteBlade() failed';
3544 return '';
3545}
3546
4034ab9e
DO
3547function getChapterList ()
3548{
3549 $ret = array();
c4d0dc30 3550 $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 3551 while ($row = $result->fetch (PDO::FETCH_ASSOC))
c4d0dc30 3552 $ret[$row['id']] = $row;
4034ab9e
DO
3553 return $ret;
3554}
3555
2d1e6b63 3556// Return file id by file name.
72d2a7ee
DO
3557function findFileByName ($filename)
3558{
2d1e6b63
AD
3559 global $dbxlink;
3560 $query = $dbxlink->prepare('SELECT id FROM File WHERE name = ?');
3561 $query->bindParam(1, $filename);
3562 $query->execute();
3563 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
72d2a7ee 3564 return $row['id'];
2d1e6b63
AD
3565
3566 return NULL;
72d2a7ee
DO
3567}
3568
9133d2c5
DO
3569function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3570{
3571 global $dbxlink;
3572 $dbxlink->beginTransaction();
3573 $query = "select now() - first_success as success_age, now() - last_retry as retry_age, displayed_name, memberof " .
3574 "from LDAPCache where presented_username = '${form_username}' and successful_hash = '${password_hash}' " .
3575 "having success_age < ${expiry} for update";
3576 $result = useSelectBlade ($query);
3577 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3578 {
3579 $row['memberof'] = unserialize (base64_decode ($row['memberof']));
3580 return $row;
3581 }
3582 return NULL;
3583}
3584
3585function releaseLDAPCache ()
3586{
3587 global $dbxlink;
3588 $dbxlink->commit();
3589}
3590
3591// This actually changes only last_retry.
3592function touchLDAPCacheRecord ($form_username)