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