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