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