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