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