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