r2779 - semanticFilter(): don't allow redefining predicates (ticket:214)
[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{
6bb8e41d 1759 $query1 =
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";
065eeb52 1762 $result = useSelectBlade ($query1, __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
DO
1781 $result->closeCursor();
1782 unset ($result);
6bb8e41d
DO
1783// Find the list of all assigned values of dictionary-addressed attributes, each with
1784// chapter/word keyed reference counters. Use the structure to adjust reference counters
1785// of the returned disctionary words.
10bac82a
DY
1786 $query2 = "select a.id as attr_id, am.chapter_id as chapter_no, uint_value, count(object_id) as refcnt " .
1787 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1788 "inner join AttributeValue as av on a.id = av.attr_id " .
1789 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
1790 "where a.type = 'dict' group by a.id, am.chapter_id, uint_value " .
1791 "order by a.id, am.chapter_id, uint_value";
065eeb52 1792 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1793 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1794 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1795 $result->closeCursor();
e673ee24
DO
1796 return $dict;
1797}
1798
da95280e
DO
1799function getDictStats ()
1800{
590e1281 1801 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25);
da95280e 1802 $query =
10bac82a 1803 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
6530f34e 1804 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id";
065eeb52 1805 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1806 $tc = $tw = $uc = $uw = 0;
89fa639f 1807 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1808 {
1809 $tc++;
1810 $tw += $row['wc'];;
1811 if (in_array ($row['chapter_no'], $stock_chapters))
1812 continue;
1813 $uc++;
1814 $uw += $row['wc'];;
1815 }
89fa639f
DO
1816 $result->closeCursor();
1817 unset ($result);
10bac82a 1818 $query = "select count(id) as attrc from RackObject as ro left join " .
08b4cb24 1819 "AttributeValue as av on ro.id = av.object_id group by ro.id";
065eeb52 1820 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1821 $to = $ta = $so = 0;
89fa639f 1822 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1823 {
1824 $to++;
1825 if ($row['attrc'] != 0)
1826 {
1827 $so++;
1828 $ta += $row['attrc'];
1829 }
1830 }
89fa639f 1831 $result->closeCursor();
da95280e
DO
1832 $ret = array();
1833 $ret['Total chapters in dictionary'] = $tc;
1834 $ret['Total words in dictionary'] = $tw;
1835 $ret['User chapters'] = $uc;
1836 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1837 $ret['Total objects'] = $to;
1838 $ret['Objects with stickers'] = $so;
1839 $ret['Total stickers attached'] = $ta;
da95280e
DO
1840 return $ret;
1841}
1842
6807f0be 1843function getIPv4Stats ()
9ec5fdf1 1844{
9ec5fdf1
DO
1845 $ret = array();
1846 $subject = array();
706ce117
DO
1847 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1848 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1849 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1850 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1851 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1852 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1853 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1854 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
9ec5fdf1
DO
1855
1856 foreach ($subject as $item)
1857 {
065eeb52 1858 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
1859 $row = $result->fetch (PDO::FETCH_NUM);
1860 $ret[$item['txt']] = $row[0];
1861 $result->closeCursor();
1862 unset ($result);
1863 }
1864 return $ret;
1865}
1866
6807f0be 1867function getRackspaceStats ()
9ec5fdf1 1868{
9ec5fdf1
DO
1869 $ret = array();
1870 $subject = array();
10bac82a 1871 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
9ec5fdf1
DO
1872 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1873 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1874 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1875
1876 foreach ($subject as $item)
1877 {
065eeb52 1878 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1879 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1880 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1881 $result->closeCursor();
1882 unset ($result);
1883 }
1884 return $ret;
1885}
1886
e9b9a095 1887function renderTagStats ()
5bbbeaa2 1888{
e9b9a095
DO
1889 global $taglist, $root;
1890 $query = "select id, tag, count(tag_id) as refcnt from " .
5bbbeaa2 1891 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
e9b9a095
DO
1892 "group by tag_id order by refcnt desc limit 50";
1893 // The same data is already present in pre-loaded tag list, but not in
1894 // the form we need. So let's ask the DB server for cooked top list and
1895 // use the cooked tag list to break it down.
065eeb52 1896 $result = useSelectBlade ($query, __FUNCTION__);
e9b9a095
DO
1897 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1898 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
19ea3ebf 1899 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th><th>files</th></tr>';
e9b9a095
DO
1900 $pagebyrealm = array
1901 (
939f9b03 1902 'file' => 'files&tab=default',
e9b9a095 1903 'ipv4net' => 'ipv4space&tab=default',
e9b9a095
DO
1904 'ipv4vs' => 'ipv4vslist&tab=default',
1905 'ipv4rspool' => 'ipv4rsplist&tab=default',
939f9b03 1906 'object' => 'depot&tab=default',
e1ae3fb4 1907 'rack' => 'rackspace&tab=default',
e9b9a095
DO
1908 'user' => 'userlist&tab=default'
1909 );
1910 foreach ($refc as $ref)
1911 {
1912 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
19ea3ebf 1913 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user', 'file') as $realm)
e9b9a095
DO
1914 {
1915 echo '<td>';
1916 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1917 echo '&nbsp;';
1918 else
1919 {
a8efc03e 1920 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&cft[]=${ref['id']}'>";
e9b9a095
DO
1921 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1922 }
1923 echo '</td>';
1924 }
1925 echo '</tr>';
1926 }
1927 echo '</table>';
5bbbeaa2
DO
1928}
1929
6807f0be
DO
1930/*
1931
1932The following allows figuring out records in TagStorage, which refer to non-existing entities:
1933
120e9ddd
DO
1934mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1935mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1936mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1937mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1938mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1939mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1940mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
6807f0be
DO
1941
1942Accordingly, these are the records, which refer to non-existent tags:
1943
1944mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1945
1946*/
1947
e673ee24
DO
1948function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1949{
1950 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1951 {
f41b492f 1952 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1953 die;
1954 }
1955 global $dbxlink;
1956 $query =
10bac82a 1957 "update Dictionary set dict_value = '${dict_value}' where chapter_id=${chapter_no} " .
e673ee24
DO
1958 "and dict_key=${dict_key} limit 1";
1959 $result = $dbxlink->query ($query);
1960 if ($result == NULL)
1961 {
f41b492f 1962 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1963 die;
1964 }
1965 return TRUE;
1966}
1967
1968function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1969{
1970 if ($chapter_no <= 0 or empty ($dict_value))
1971 {
f41b492f 1972 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1973 die;
1974 }
1975 return useInsertBlade
1976 (
1977 'Dictionary',
10bac82a 1978 array ('chapter_id' => $chapter_no, 'dict_value' => "'${dict_value}'")
e673ee24
DO
1979 );
1980}
1981
1982function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1983{
1984 if ($chapter_no <= 0 or $dict_key <= 0)
1985 {
f41b492f 1986 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1987 die;
1988 }
1989 global $dbxlink;
1990 $query =
10bac82a 1991 "delete from Dictionary where chapter_id=${chapter_no} " .
e673ee24
DO
1992 "and dict_key=${dict_key} limit 1";
1993 $result = $dbxlink->query ($query);
1994 if ($result == NULL)
1995 {
f41b492f 1996 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1997 die;
1998 }
1999 return TRUE;
2000}
2001
2002function commitAddChapter ($chapter_name = '')
2003{
2004 if (empty ($chapter_name))
2005 {
f41b492f 2006 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2007 die;
2008 }
2009 return useInsertBlade
2010 (
2011 'Chapter',
10bac82a 2012 array ('name' => "'${chapter_name}'")
e673ee24
DO
2013 );
2014}
2015
2016function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
2017{
2018 if ($chapter_no <= 0 or empty ($chapter_name))
2019 {
f41b492f 2020 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2021 die;
2022 }
2023 global $dbxlink;
2024 $query =
10bac82a 2025 "update Chapter set name = '${chapter_name}' where id = ${chapter_no} " .
e673ee24
DO
2026 "and sticky = 'no' limit 1";
2027 $result = $dbxlink->query ($query);
2028 if ($result == NULL)
2029 {
f41b492f 2030 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2031 die;
2032 }
2033 return TRUE;
2034}
2035
2036function commitDeleteChapter ($chapter_no = 0)
2037{
2038 if ($chapter_no <= 0)
2039 {
f41b492f 2040 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2041 die;
2042 }
2043 global $dbxlink;
2044 $query =
10bac82a 2045 "delete from Chapter where id = ${chapter_no} and sticky = 'no' limit 1";
e673ee24
DO
2046 $result = $dbxlink->query ($query);
2047 if ($result == NULL)
2048 {
f41b492f 2049 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2050 die;
2051 }
2052 return TRUE;
2053}
2054
4c330a14
DO
2055// This is a dictionary accessor. We perform link rendering, so the user sees
2056// nice <select> drop-downs.
e673ee24
DO
2057function readChapter ($chapter_name = '')
2058{
2059 if (empty ($chapter_name))
2060 {
f41b492f 2061 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
2062 return NULL;
2063 }
e673ee24 2064 $query =
10bac82a
DY
2065 "select dict_key, dict_value from Dictionary join Chapter on Chapter.id = Dictionary.chapter_id " .
2066 "where Chapter.name = '${chapter_name}'";
065eeb52 2067 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2068 $chapter = array();
2069 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 2070 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 2071 $result->closeCursor();
4aa8609b
DO
2072 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2073 asort ($chapter);
e673ee24
DO
2074 return $chapter;
2075}
2076
2077function getAttrMap ()
2078{
e673ee24 2079 $query =
10bac82a
DY
2080 "select a.id as attr_id, a.type as attr_type, a.name as attr_name, am.objtype_id, " .
2081 "d.dict_value as objtype_name, am.chapter_id, c2.name as chapter_name from " .
2082 "Attribute as a left join AttributeMap as am on a.id = am.attr_id " .
e673ee24 2083 "left join Dictionary as d on am.objtype_id = d.dict_key " .
10bac82a 2084 "left join Chapter as c1 on d.chapter_id = c1.id " .
291115e4 2085 "left join Chapter as c2 on am.chapter_id = c2.id " .
10bac82a
DY
2086 "where c1.name = 'RackObjectType' or c1.name is null " .
2087 "order by a.name";
065eeb52 2088 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2089 $ret = array();
2090 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2091 {
2092 $attr_id = $row['attr_id'];
2093 if (!isset ($ret[$attr_id]))
2094 {
2095 $ret[$attr_id]['id'] = $attr_id;
2096 $ret[$attr_id]['type'] = $row['attr_type'];
2097 $ret[$attr_id]['name'] = $row['attr_name'];
2098 $ret[$attr_id]['application'] = array();
2099 }
2100 if ($row['objtype_id'] == '')
2101 continue;
2102 $application['objtype_id'] = $row['objtype_id'];
2103 $application['objtype_name'] = $row['objtype_name'];
2104 if ($row['attr_type'] == 'dict')
2105 {
50393983 2106 $application['chapter_no'] = $row['chapter_id'];
e673ee24
DO
2107 $application['chapter_name'] = $row['chapter_name'];
2108 }
2109 $ret[$attr_id]['application'][] = $application;
2110 }
2111 $result->closeCursor();
2112 return $ret;
2113}
2114
2115function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2116{
2117 if ($attr_id <= 0 or empty ($attr_name))
2118 {
f41b492f 2119 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2120 die;
2121 }
2122 global $dbxlink;
2123 $query =
10bac82a
DY
2124 "update Attribute set name = '${attr_name}' " .
2125 "where id = ${attr_id} limit 1";
e673ee24
DO
2126 $result = $dbxlink->query ($query);
2127 if ($result == NULL)
2128 {
f41b492f 2129 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
2130 die;
2131 }
2132 return TRUE;
2133}
2134
2135function commitAddAttribute ($attr_name = '', $attr_type = '')
2136{
2137 if (empty ($attr_name))
2138 {
f41b492f 2139 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2140 die;
2141 }
2142 switch ($attr_type)
2143 {
2144 case 'uint':
2145 case 'float':
2146 case 'string':
2147 case 'dict':
2148 break;
2149 default:
f41b492f 2150 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2151 die;
2152 }
2153 return useInsertBlade
2154 (
2155 'Attribute',
10bac82a 2156 array ('name' => "'${attr_name}'", 'type' => "'${attr_type}'")
e673ee24
DO
2157 );
2158}
2159
2160function commitDeleteAttribute ($attr_id = 0)
2161{
2162 if ($attr_id <= 0)
2163 {
f41b492f 2164 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2165 die;
2166 }
10bac82a 2167 return useDeleteBlade ('Attribute', 'id', $attr_id);
e673ee24
DO
2168}
2169
2170// FIXME: don't store garbage in chapter_no for non-dictionary types.
2171function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2172{
2173 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
2174 {
f41b492f 2175 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2176 die;
2177 }
2178 return useInsertBlade
2179 (
2180 'AttributeMap',
2181 array
2182 (
2183 'attr_id' => $attr_id,
2184 'objtype_id' => $objtype_id,
10bac82a 2185 'chapter_id' => $chapter_no
e673ee24
DO
2186 )
2187 );
2188}
2189
2190function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2191{
2192 if ($attr_id <= 0 or $objtype_id <= 0)
2193 {
f41b492f 2194 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2195 die;
2196 }
2197 global $dbxlink;
2198 $query =
2199 "delete from AttributeMap where attr_id=${attr_id} " .
2200 "and objtype_id=${objtype_id} limit 1";
2201 $result = $dbxlink->query ($query);
2202 if ($result == NULL)
2203 {
f41b492f 2204 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2205 die;
2206 }
2207 return TRUE;
2208}
2209
2210// This function returns all optional attributes for requested object
2211// as an array of records. NULL is returned on error and empty array
2212// is returned, if there are no attributes found.
24cbe8af 2213function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
2214{
2215 if ($object_id <= 0)
2216 {
f41b492f 2217 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
2218 return NULL;
2219 }
e673ee24
DO
2220 $ret = array();
2221 $query =
10bac82a 2222 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
e673ee24
DO
2223 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2224 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
10bac82a 2225 "inner join Attribute as A on AM.attr_id = A.id " .
e673ee24 2226 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
10bac82a
DY
2227 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2228 "left join Chapter as C on AM.chapter_id = C.id " .
2229 "where RO.id = ${object_id} order by A.type, A.name";
065eeb52 2230 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2231 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2232 {
2233 $record = array();
2234 $record['id'] = $row['attr_id'];
2235 $record['name'] = $row['attr_name'];
2236 $record['type'] = $row['attr_type'];
2237 switch ($row['attr_type'])
2238 {
2239 case 'uint':
2240 case 'float':
2241 case 'string':
24cbe8af
DO
2242 $record['value'] = $row[$row['attr_type'] . '_value'];
2243 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2244 break;
e673ee24 2245 case 'dict':
24cbe8af
DO
2246 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2247 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
2248 $record['chapter_name'] = $row['chapter_name'];
2249 $record['key'] = $row['uint_value'];
2250 break;
2251 default:
2252 $record['value'] = NULL;
2253 break;
2254 }
2255 $ret[$row['attr_id']] = $record;
2256 }
2257 $result->closeCursor();
2258 return $ret;
2259}
2260
2261function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2262{
2263 if ($object_id <= 0 or $attr_id <= 0)
2264 {
f41b492f 2265 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2266 die;
2267 }
2268 global $dbxlink;
2269 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2270 $result = $dbxlink->query ($query);
2271 if ($result == NULL)
2272 {
f41b492f 2273 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2274 die;
2275 }
2276 return TRUE;
2277}
2278
2279// FIXME: don't share common code with use commitResetAttrValue()
2280function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2281{
2282 if ($object_id <= 0 or $attr_id <= 0)
2283 {
f41b492f 2284 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2285 die;
2286 }
2287 if (empty ($value))
2288 return commitResetAttrValue ($object_id, $attr_id);
2289 global $dbxlink;
10bac82a 2290 $query1 = "select type as attr_type from Attribute where id = ${attr_id}";
e673ee24
DO
2291 $result = $dbxlink->query ($query1);
2292 if ($result == NULL)
2293 {
f41b492f 2294 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
2295 die;
2296 }
2297 $row = $result->fetch (PDO::FETCH_NUM);
2298 if ($row == NULL)
2299 {
f41b492f 2300 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
2301 die;
2302 }
2303 $attr_type = $row[0];
2304 $result->closeCursor();
2305 switch ($attr_type)
2306 {
2307 case 'uint':
2308 case 'float':
2309 case 'string':
2310 $column = $attr_type . '_value';
2311 break;
2312 case 'dict':
2313 $column = 'uint_value';
2314 break;
2315 default:
f41b492f 2316 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
2317 die;
2318 }
2319 $query2 =
2320 "delete from AttributeValue where " .
2321 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2322 $result = $dbxlink->query ($query2);
2323 if ($result == NULL)
2324 {
f41b492f 2325 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
2326 die;
2327 }
2328 // We know $value isn't empty here.
2329 $query3 =
2330 "insert into AttributeValue set ${column} = '${value}', " .
2331 "object_id = ${object_id}, attr_id = ${attr_id} ";
2332 $result = $dbxlink->query ($query3);
2333 if ($result == NULL)
2334 {
f41b492f 2335 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
2336 die;
2337 }
2338 return TRUE;
2339}
2340
2341function commitUseupPort ($port_id = 0)
2342{
2343 if ($port_id <= 0)
2344 {
f41b492f 2345 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
2346 die;
2347 }
2348 global $dbxlink;
2349 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2350 $result = $dbxlink->exec ($query);
2351 if ($result == NULL)
2352 {
f41b492f 2353 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
2354 die;
2355 }
2356 return TRUE;
2357
2358}
2359
2360// This is a swiss-knife blade to insert a record into a table.
2361// The first argument is table name.
2362// The second argument is an array of "name" => "value" pairs.
2363// The function returns either TRUE or FALSE (we expect one row
2364// to be inserted).
2365function useInsertBlade ($tablename, $values)
2366{
2367 global $dbxlink;
2368 $namelist = $valuelist = '';
2369 foreach ($values as $name => $value)
2370 {
2371 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2372 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2373 }
2374 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2375 $result = $dbxlink->exec ($query);
2376 if ($result != 1)
2377 return FALSE;
2378 return TRUE;
2379}
2380
2381// This swiss-knife blade deletes one record from the specified table
2382// using the specified key name and value.
f5575f12 2383function useDeleteBlade ($tablename, $keyname, $keyvalue)
e673ee24
DO
2384{
2385 global $dbxlink;
f5575f12 2386 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
e673ee24
DO
2387}
2388
5967b83d
DO
2389function useSelectBlade ($query, $caller = 'N/A')
2390{
2391 global $dbxlink;
2392 $result = $dbxlink->query ($query);
2393 if ($result == NULL)
2394 {
2395 $ei = $dbxlink->errorInfo();
105a3bc8 2396 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
2397 return NULL;
2398 }
2399 return $result;
2400}
2401
9c0b0016
DO
2402function loadConfigCache ()
2403{
4fe32e78 2404 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 2405 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
2406 $cache = array();
2407 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2408 $cache[$row['varname']] = $row;
2409 $result->closeCursor();
2410 return $cache;
2411}
2412
2413// setConfigVar() is expected to perform all necessary filtering
2414function storeConfigVar ($varname = NULL, $varvalue = NULL)
2415{
c461c579 2416 global $dbxlink;
bb6b9880 2417 if (empty ($varname) || $varvalue === NULL)
9c0b0016 2418 {
f41b492f 2419 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
2420 return FALSE;
2421 }
2422 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2423 $result = $dbxlink->query ($query);
2424 if ($result == NULL)
2425 {
f41b492f 2426 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
2427 return FALSE;
2428 }
2429 $rc = $result->rowCount();
2430 $result->closeCursor();
f7ee57a1 2431 if ($rc == 0 or $rc == 1)
9c0b0016 2432 return TRUE;
f41b492f 2433 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2434 return FALSE;
2435}
2436
fbbb74fb
DO
2437// Database version detector. Should behave corretly on any
2438// working dataset a user might have.
2439function getDatabaseVersion ()
2440{
2441 global $dbxlink;
2442 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2443 $result = $dbxlink->query ($query);
2444 if ($result == NULL)
2445 {
2446 $errorInfo = $dbxlink->errorInfo();
2447 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2448 return '0.14.4';
4d2e93f2 2449 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2450 }
2451 $rows = $result->fetchAll (PDO::FETCH_NUM);
2452 if (count ($rows) != 1 || empty ($rows[0][0]))
2453 {
2454 $result->closeCursor();
4d2e93f2 2455 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2456 }
2457 $ret = $rows[0][0];
2458 $result->closeCursor();
2459 return $ret;
2460}
2461
da04825a
DO
2462// Return an array of virtual services. For each of them list real server pools
2463// with their load balancers and other stats.
62a1dcb5
DO
2464function getSLBSummary ()
2465{
6fec9f39
DO
2466 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2467 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2468 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2469 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2470 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
6fec9f39 2471 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 2472 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2473 $ret = array();
2474 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2475 {
4cadac8f 2476 $vsid = $row['vsid'];
da04825a 2477 $object_id = $row['object_id'];
4cadac8f
DO
2478 if (!isset ($ret[$vsid]))
2479 {
2480 $ret[$vsid] = array();
13bffb29 2481 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2482 $ret[$vsid][$cname] = $row[$cname];
da04825a 2483 $ret[$vsid]['lblist'] = array();
4cadac8f 2484 }
6fec9f39
DO
2485 // There's only one assigned RS pool possible for each LB-VS combination.
2486 $ret[$vsid]['lblist'][$row['object_id']] = array
2487 (
2488 'id' => $row['rspool_id'],
2489 'size' => $row['rscount'],
2490 'name' => $row['pool_name']
2491 );
c3bdc503 2492 }
060ba26e 2493 $result->closeCursor();
c3bdc503 2494 return $ret;
62a1dcb5
DO
2495}
2496
7e7a8387 2497function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2498{
79a9edb4 2499 if ($pool_id <= 0)
ca461127
DO
2500 {
2501 showError ('Invalid arguments', __FUNCTION__);
2502 die;
2503 }
79a9edb4
DO
2504 if (empty ($rsport) or $rsport == 0)
2505 $rsport = 'NULL';
ca461127
DO
2506 return useInsertBlade
2507 (
706ce117 2508 'IPv4RS',
ca461127
DO
2509 array
2510 (
2511 'rsip' => "inet_aton('${rsip}')",
2512 'rsport' => $rsport,
2513 'rspool_id' => $pool_id,
bcbeadb4 2514 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2515 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2516 )
2517 );
2518}
2519
c63a8d6e 2520function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21
DO
2521{
2522 if (empty ($vip) or $vport <= 0 or empty ($proto))
c63a8d6e
DO
2523 return __FUNCTION__ . ': invalid arguments';
2524 if (!useInsertBlade
d6517a21 2525 (
706ce117 2526 'IPv4VS',
d6517a21
DO
2527 array
2528 (
2529 'vip' => "inet_aton('${vip}')",
2530 'vport' => $vport,
2531 'proto' => "'${proto}'",
2532 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2533 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2534 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2535 )
c63a8d6e
DO
2536 ))
2537 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2538 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2539}
2540
c1ca768c 2541function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2542{
c1ca768c 2543 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2544 {
2545 showError ('Invalid arguments', __FUNCTION__);
2546 die;
2547 }
2548 return useInsertBlade
2549 (
706ce117 2550 'IPv4LB',
3241551e
DO
2551 array
2552 (
2553 'object_id' => $object_id,
2554 'rspool_id' => $pool_id,
c1ca768c 2555 'vs_id' => $vs_id,
3241551e
DO
2556 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2557 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2558 )
ca461127
DO
2559 );
2560}
2561
fb1c4a54
DO
2562function commitDeleteRS ($id = 0)
2563{
2564 if ($id <= 0)
2565 return FALSE;
706ce117 2566 return useDeleteBlade ('IPv4RS', 'id', $id);
fb1c4a54
DO
2567}
2568
d6517a21
DO
2569function commitDeleteVS ($id = 0)
2570{
2571 if ($id <= 0)
2572 return FALSE;
6657739e 2573 releaseFiles ('ipv4vs', $id);
706ce117 2574 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2575}
2576
c1ca768c 2577function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2578{
2579 global $dbxlink;
c4d85fd1 2580 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2581 return FALSE;
706ce117 2582 $query = "delete from IPv4LB where object_id = ${object_id} and " .
c1ca768c 2583 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2584 $result = $dbxlink->exec ($query);
2585 if ($result === NULL)
2586 return FALSE;
2587 elseif ($result != 1)
2588 return FALSE;
2589 else
2590 return TRUE;
2591}
2592
fb1c4a54
DO
2593function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2594{
79a9edb4 2595 if ($rsid <= 0)
fb1c4a54
DO
2596 {
2597 showError ('Invalid args', __FUNCTION__);
2598 die;
2599 }
2600 if (long2ip (ip2long ($rsip)) !== $rsip)
2601 {
2602 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2603 die;
2604 }
79a9edb4
DO
2605 if (empty ($rsport) or $rsport == 0)
2606 $rsport = 'NULL';
fb1c4a54
DO
2607 global $dbxlink;
2608 $query =
706ce117 2609 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2610 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2611 " where id = ${rsid} limit 1";
2612 $result = $dbxlink->query ($query);
2613 if ($result == NULL)
2614 {
2615 showError ("SQL query '${query}' failed", __FUNCTION__);
2616 die;
2617 }
2618 return TRUE;
2619}
2620
c1ca768c 2621function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2622{
c1ca768c 2623 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2624 {
2625 showError ('Invalid args', __FUNCTION__);
2626 die;
2627 }
2628 global $dbxlink;
2629 $query =
706ce117 2630 "update IPv4LB set vsconfig = " .
3241551e
DO
2631 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2632 ', rsconfig = ' .
2633 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2634 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2635 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2636 $result = $dbxlink->exec ($query);
2637 if ($result === NULL)
2638 return FALSE;
3241551e
DO
2639 else
2640 return TRUE;
2641}
2642
d6517a21
DO
2643function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2644{
2645 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2646 {
2647 showError ('Invalid args', __FUNCTION__);
2648 die;
2649 }
2650 global $dbxlink;
706ce117 2651 $query = "update IPv4VS set " .
d6517a21
DO
2652 "vip = inet_aton('${vip}'), " .
2653 "vport = ${vport}, " .
2654 "proto = '${proto}', " .
2655 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2656 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2657 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2658 " where id = ${vsid} limit 1";
d6517a21
DO
2659 $result = $dbxlink->exec ($query);
2660 if ($result === NULL)
2661 return FALSE;
d6517a21
DO
2662 else
2663 return TRUE;
2664}
2665
5a1680d2
DO
2666function loadThumbCache ($rack_id = 0)
2667{
5a1680d2
DO
2668 $ret = NULL;
2669 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2670 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2671 $row = $result->fetch (PDO::FETCH_ASSOC);
2672 if ($row)
2673 $ret = base64_decode ($row['thumb_data']);
2674 $result->closeCursor();
2675 return $ret;
2676}
2677
2678function saveThumbCache ($rack_id = 0, $cache = NULL)
2679{
2680 global $dbxlink;
2681 if ($rack_id == 0 or $cache == NULL)
2682 {
2683 showError ('Invalid arguments', __FUNCTION__);
2684 return;
2685 }
2686 $data = base64_encode ($cache);
2687 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2688 $result = $dbxlink->exec ($query);
2689}
9a81d416 2690
c7fe33be
DO
2691function resetThumbCache ($rack_id = 0)
2692{
2693 global $dbxlink;
2694 if ($rack_id == 0)
2695 {
2696 showError ('Invalid argument', __FUNCTION__);
2697 return;
2698 }
2699 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2700 $result = $dbxlink->exec ($query);
2701}
2702
748805bf 2703// Return the list of attached RS pools for the given object. As long as we have
706ce117 2704// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2705// by vs_id, because there will be only one RS pool listed for each VS of the
2706// current object.
78e7b769
DO
2707function getRSPoolsForObject ($object_id = 0)
2708{
2709 if ($object_id <= 0)
2710 {
2711 showError ('Invalid object_id', __FUNCTION__);
2712 return NULL;
2713 }
748805bf 2714 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2715 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2716 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2717 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2718 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
748805bf
DO
2719 "where lb.object_id = ${object_id} " .
2720 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2721 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2722 $ret = array ();
78e7b769 2723 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2724 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2725 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2726 $result->closeCursor();
748805bf 2727 return $ret;
78e7b769
DO
2728}
2729
c63a8d6e 2730function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2731{
c63a8d6e
DO
2732 if (empty ($name))
2733 return __FUNCTION__ . ': invalid arguments';
2734 if (!useInsertBlade
5ad76f01 2735 (
706ce117 2736 'IPv4RSPool',
5ad76f01
DO
2737 array
2738 (
5ad76f01
DO
2739 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2740 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2741 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2742 )
c63a8d6e
DO
2743 ))
2744 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2745 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2746}
2747
2748function commitDeleteRSPool ($pool_id = 0)
2749{
2750 global $dbxlink;
2751 if ($pool_id <= 0)
2752 return FALSE;
6657739e 2753 releaseFiles ('ipv4rspool', $pool_id);
706ce117 2754 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2755}
2756
2757function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2758{
2759 if ($pool_id <= 0)
2760 {
2761 showError ('Invalid arg', __FUNCTION__);
2762 die;
2763 }
2764 global $dbxlink;
706ce117 2765 $query = "update IPv4RSPool set " .
5ad76f01
DO
2766 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2767 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2768 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2769 " where id = ${pool_id} limit 1";
2770 $result = $dbxlink->exec ($query);
2771 if ($result === NULL)
2772 return FALSE;
2773 elseif ($result != 1)
2774 return FALSE;
2775 else
2776 return TRUE;
2777}
2778
8253d9f0
DO
2779function getRSList ()
2780{
1f7d18fa 2781 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
706ce117 2782 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
065eeb52 2783 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2784 $ret = array ();
8253d9f0 2785 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2786 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2787 $ret[$row['id']][$cname] = $row[$cname];
2788 $result->closeCursor();
2789 return $ret;
2790}
2791
2792// Return the list of all currently configured load balancers with their pool count.
2793function getLBList ()
2794{
4b0932b6 2795 $query = "select object_id, count(rspool_id) as poolcount " .
706ce117 2796 "from IPv4LB group by object_id order by object_id";
065eeb52 2797 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2798 $ret = array ();
2799 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2800 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2801 $result->closeCursor();
4b0932b6 2802 return $ret;
8253d9f0
DO
2803}
2804
9e677cbd
DO
2805// For the given object return: it vsconfig/rsconfig; the list of RS pools
2806// attached (each with vsconfig/rsconfig in turn), each with the list of
2807// virtual services terminating the pool. Each pool also lists all real
2808// servers with rsconfig.
2987fc1f 2809function getSLBConfig ($object_id)
9e677cbd
DO
2810{
2811 if ($object_id <= 0)
2812 {
2813 showError ('Invalid arg', __FUNCTION__);
2814 return NULL;
2815 }
9e677cbd 2816 $ret = array();
d91f08f3
DO
2817 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2818 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2819 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2820 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2821 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2822 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2823 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2824 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2825 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2826 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2827 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2828 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2829 {
d91f08f3
DO
2830 $vs_id = $row['vs_id'];
2831 if (!isset ($ret[$vs_id]))
2832 {
2833 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)
2834 $ret[$vs_id][$c] = $row[$c];
2835 $ret[$vs_id]['rslist'] = array();
2836 }
2837 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2838 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2839 }
2840 $result->closeCursor();
2841 return $ret;
2842}
1f7d18fa
DO
2843
2844function commitSetInService ($rs_id = 0, $inservice = '')
2845{
2846 if ($rs_id <= 0 or empty ($inservice))
2847 {
2848 showError ('Invalid args', __FUNCTION__);
2849 return NULL;
2850 }
2851 global $dbxlink;
706ce117 2852 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
1f7d18fa
DO
2853 $result = $dbxlink->exec ($query);
2854 if ($result === NULL)
2855 return FALSE;
2856 elseif ($result != 1)
2857 return FALSE;
2858 else
2859 return TRUE;
2860}
2861
ad0e4754
DO
2862function executeAutoPorts ($object_id = 0, $type_id = 0)
2863{
2864 if ($object_id == 0 or $type_id == 0)
2865 {
2866 showError ('Invalid arguments', __FUNCTION__);
2867 die;
2868 }
f3f0161f 2869 $ret = TRUE;
118e4c38 2870 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2871 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2872 return $ret;
ad0e4754
DO
2873}
2874
6e49bd1f 2875// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2876// generated/deducted later at higher levels.
aab37bc0 2877// Result is a chain: randomly indexed taginfo list.
f9bc186f 2878function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2879{
a6e8d544 2880 $ret = array();
2c21a10c
DO
2881 if (!in_array ($entity_realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2882 return $ret;
edf0993c
DO
2883 $query = "select tt.id, tag from " .
2884 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
120e9ddd 2885 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
edf0993c
DO
2886 "order by tt.tag";
2887 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2888 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2889 $ret[$row['id']] = $row;
a6e8d544 2890 $result->closeCursor();
aab37bc0 2891 return getExplicitTagsOnly ($ret);
5967b83d
DO
2892}
2893
351c0966 2894// Return a tag chain with all DB tags on it.
5967b83d
DO
2895function getTagList ()
2896{
20c901a7 2897 $ret = array();
120e9ddd 2898 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2899 "from TagTree left join TagStorage on id = tag_id " .
120e9ddd 2900 "group by id, entity_realm order by tag";
065eeb52 2901 $result = useSelectBlade ($query, __FUNCTION__);
fb7a4967
DO
2902 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2903 // which is utf8_general_ci for UTF-8.
5967b83d 2904 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2905 {
7cc02fc1 2906 if (!isset ($ret[$row['id']]))
20c901a7 2907 $ret[$row['id']] = array
5b7bd02e
DO
2908 (
2909 'id' => $row['id'],
2910 'tag' => $row['tag'],
fb7a4967 2911 'ci' => $ci++,
5b7bd02e
DO
2912 'parent_id' => $row['parent_id'],
2913 'refcnt' => array()
2914 );
2915 if ($row['realm'])
20c901a7 2916 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2917 }
5967b83d 2918 $result->closeCursor();
20c901a7 2919 return $ret;
5967b83d
DO
2920}
2921
fe7044ad
DO
2922function commitCreateTag ($tagname = '', $parent_id = 0)
2923{
2924 if ($tagname == '' or $parent_id === 0)
2925 return "Invalid args to " . __FUNCTION__;
2926 $result = useInsertBlade
2927 (
2928 'TagTree',
2929 array
2930 (
2931 'tag' => "'${tagname}'",
2932 'parent_id' => $parent_id
2933 )
2934 );
590e1281 2935 global $dbxlink;
fe7044ad
DO
2936 if ($result)
2937 return '';
590e1281
DO
2938 elseif ($dbxlink->errorCode() == 23000)
2939 return "name '${tag_name}' is already used";
fe7044ad
DO
2940 else
2941 return "SQL query failed in " . __FUNCTION__;
2942}
2943
2944function commitDestroyTag ($tagid = 0)
2945{
2946 if ($tagid == 0)
2947 return 'Invalid arg to ' . __FUNCTION__;
f5575f12 2948 if (useDeleteBlade ('TagTree', 'id', $tagid))
fe7044ad
DO
2949 return '';
2950 else
2951 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2952}
f9bc186f 2953
49fb1027 2954function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2955{
49fb1027
DO
2956 if ($parent_id == 0)
2957 $parent_id = 'NULL';
f9bc186f 2958 global $dbxlink;
49fb1027
DO
2959 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2960 "where id = ${tag_id} limit 1";
f9bc186f 2961 $result = $dbxlink->exec ($query);
590e1281
DO
2962 if ($result !== FALSE)
2963 return '';
2964 elseif ($dbxlink->errorCode() == 23000)
2965 return "name '${tag_name}' is already used";
2966 else
49fb1027 2967 return 'SQL query failed in ' . __FUNCTION__;
f9bc186f
DO
2968}
2969
01b6b4d6
DO
2970// Drop the whole chain stored.
2971function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af
DO
2972{
2973 global $dbxlink;
120e9ddd 2974 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
aedf18af
DO
2975 $result = $dbxlink->exec ($query);
2976 if ($result === NULL)
2977 return FALSE;
2978 else
2979 return TRUE;
2980}
2981
01b6b4d6
DO
2982// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2983function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2984{
2985 global $dbxlink;
120e9ddd 2986 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
01b6b4d6
DO
2987 $result = $dbxlink->exec ($query);
2988 if ($result === NULL)
2989 return FALSE;
2990 else
2991 return TRUE;
2992}
2993
351c0966 2994// Push a record into TagStorage unconditionally.
3355ca56 2995function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2996{
3355ca56
DO
2997 if (empty ($realm))
2998 return FALSE;
eb6ea26f
DO
2999 return useInsertBlade
3000 (
3001 'TagStorage',
3002 array
3003 (
120e9ddd
DO
3004 'entity_realm' => "'${realm}'",
3005 'entity_id' => $entity_id,
eb6ea26f
DO
3006 'tag_id' => $tag_id,
3007 )
3008 );
3009}
3010
351c0966 3011// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
3012// on the implicit list already). Then remove any other records, which
3013// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
3014// that both the tag base is still minimal and all requested tags appear on
3015// the resulting tag chain.
abef7149
DO
3016// Return TRUE, if any changes were committed.
3017function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3018{
3019 // Put the current explicit sub-chain into a buffer and merge all tags from
3020 // the extra chain, which aren't there yet.
3021 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3022 foreach ($extrachain as $extratag)
3023 if (!tagOnChain ($extratag, $newchain))
3024 $newchain[] = $extratag;
3025 // Then minimize the working buffer and check if it differs from the original
3026 // chain we started with. If it is so, save the work and signal the upper layer.
3027 $newchain = getExplicitTagsOnly ($newchain);
3028 if (tagChainCmp ($oldchain, $newchain))
3029 {
01b6b4d6 3030 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
3031 foreach ($newchain as $taginfo)
3032 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3033 return TRUE;
3034 }
3035 return FALSE;
351c0966
DO
3036}
3037
3038// Presume, that the target record has no tags attached.
3039function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3040{
3041 if (!count ($tagidlist))
c63a8d6e
DO
3042 return '';
3043 if (!$last_insert_id)
3044 $last_insert_id = lastInsertID();
3045 $errcount = 0;
abef7149 3046 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 3047 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
3048 $errcount++;
3049 if (!$errcount)
3050 return '';
3051 else
3052 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3053}
3054
42023f03
DO
3055function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3056{
3057 // $range is in x.x.x.x/x format, split into ip/mask vars
3058 $rangeArray = explode('/', $range);
3059 if (count ($rangeArray) != 2)
3060 return "Invalid IPv4 prefix '${range}'";
3061 $ip = $rangeArray[0];
3062 $mask = $rangeArray[1];
3063
3064 if (empty ($ip) or empty ($mask))
3065 return "Invalid IPv4 prefix '${range}'";
3066 $ipL = ip2long($ip);
3067 $maskL = ip2long($mask);
3068 if ($ipL == -1 || $ipL === FALSE)
3069 return 'Bad IPv4 address';
3070 if ($mask < 32 && $mask > 0)
3071 $maskL = $mask;
3072 else
3073 {
3074 $maskB = decbin($maskL);
3075 if (strlen($maskB)!=32)
3076 return 'Invalid netmask';
3077 $ones=0;
3078 $zeroes=FALSE;
3079 foreach( str_split ($maskB) as $digit)
3080 {
3081 if ($digit == '0')
3082 $zeroes = TRUE;
3083 if ($digit == '1')
3084 {
3085 $ones++;
3086 if ($zeroes == TRUE)
3087 return 'Invalid netmask';
3088 }
3089 }
3090 $maskL = $ones;
3091 }
3092 $binmask = binMaskFromDec($maskL);
3093 $ipL = $ipL & $binmask;
42023f03
DO
3094 $result = useInsertBlade
3095 (
706ce117 3096 'IPv4Network',
42023f03
DO
3097 array
3098 (
3099 'ip' => sprintf ('%u', $ipL),
3100 'mask' => "'${maskL}'",
3101 'name' => "'${name}'"
3102 )
3103 );
e782fca4
DO
3104 if ($result != TRUE)
3105 return "Could not add ${range} (already exists?).";
42023f03
DO
3106
3107 if ($is_bcast and $maskL < 31)
3108 {
3109 $network_addr = long2ip ($ipL);
3110 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3111 updateAddress ($network_addr, 'network', 'yes');
3112 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3113 }
351c0966 3114 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
3115}
3116
706ce117 3117// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
3118function destroyIPv4Prefix ($id = 0)
3119{
3120 if ($id <= 0)
3121 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
6657739e 3122 releaseFiles ('ipv4net', $id);
706ce117 3123 if (!useDeleteBlade ('IPv4Network', 'id', $id))
42023f03 3124 return __FUNCTION__ . ': SQL query #1 failed';
01b6b4d6 3125 if (!destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
3126 return __FUNCTION__ . ': SQL query #2 failed';
3127 return '';
3128}
3129
ebae41b3
DO
3130function loadScript ($name)
3131{
3132 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3133 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
3134 if ($row !== FALSE)
3135 return $row[0];
3136 else
3137 return NULL;
ebae41b3
DO
3138}
3139
3140function saveScript ($name, $text)
3141{
3142 if (empty ($name))
3143 {
3144 showError ('Invalid argument');
3145 return FALSE;
3146 }
4a6a28f1 3147 // delete regardless of existence
f5575f12 3148 useDeleteBlade ('Script', 'script_name', "'${name}'");
4a6a28f1 3149 return useInsertBlade
ebae41b3
DO
3150 (
3151 'Script',
3152 array
3153 (
3154 'script_name' => "'${name}'",
3155 'script_text' => "'${text}'"
3156 )
3157 );
3158}
3159
d983f70a
DO
3160function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3161{
3162 if (NULL === getIPv4AddressNetworkId ($localip))
3163 return "$localip: Non existant ip";
3164 if (NULL === getIPv4AddressNetworkId ($localip))
3165 return "$remoteip: Non existant ip";
3166 if ( ($localport <= 0) or ($localport >= 65536) )
3167 return "$localport: invaild port";
3168 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3169 return "$remoteport: invaild port";
3170
3171 $result = useInsertBlade
3172 (
706ce117 3173 'IPv4NAT',
d983f70a
DO
3174 array
3175 (
3176 'object_id' => $object_id,
3177 'localip' => "INET_ATON('${localip}')",
3178 'remoteip' => "INET_ATON('$remoteip')",
3179 'localport' => $localport,
3180 'remoteport' => $remoteport,
3181 'proto' => "'${proto}'",
3182 'description' => "'${description}'",
3183 )
3184 );
3185 if ($result)
3186 return '';
3187 else
3188 return __FUNCTION__ . ': Failed to insert the rule.';
3189}
3190
3191function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3192{
3193 global $dbxlink;
3194
3195 $query =
706ce117 3196 "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
3197 $result = $dbxlink->exec ($query);
3198 return '';
3199}
3200
3201function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3202{
3203 global $dbxlink;
3204
3205 $query =
706ce117 3206 "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
3207 $result = $dbxlink->exec ($query);
3208 return '';
3209}
3210
3211function getNATv4ForObject ($object_id)
3212{
3213 $ret = array();
3214 $ret['out'] = array();
3215 $ret['in'] = array();
3216 $query =
3217 "select ".
3218 "proto, ".
3219 "INET_NTOA(localip) as localip, ".
3220 "localport, ".
3221 "INET_NTOA(remoteip) as remoteip, ".
3222 "remoteport, ".
3223 "ipa1.name as local_addr_name, " .
3224 "ipa2.name as remote_addr_name, " .
3225 "description ".
706ce117
DO
3226 "from IPv4NAT ".
3227 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3228 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
d983f70a
DO
3229 "where object_id='$object_id' ".
3230 "order by localip, localport, proto, remoteip, remoteport";
3231 $result = useSelectBlade ($query, __FUNCTION__);
3232 $count=0;
3233 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3234 {
3235 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3236 $ret['out'][$count][$cname] = $row[$cname];
3237 $count++;
3238 }
3239 $result->closeCursor();
3240 unset ($result);
3241
3242 $query =
3243 "select ".
3244 "proto, ".
3245 "INET_NTOA(localip) as localip, ".
3246 "localport, ".
3247 "INET_NTOA(remoteip) as remoteip, ".
3248 "remoteport, ".
706ce117 3249 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
3250 "RackObject.name as object_name, ".
3251 "description ".
706ce117
DO
3252 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3253 "where IPv4Allocation.object_id='$object_id' ".
d983f70a
DO
3254 "order by remoteip, remoteport, proto, localip, localport";
3255 $result = useSelectBlade ($query, __FUNCTION__);
3256 $count=0;
3257 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3258 {
3259 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3260 $ret['in'][$count][$cname] = $row[$cname];
3261 $count++;
3262 }
3263 $result->closeCursor();
3264
3265 return $ret;
3266}
3267
3268// This function performs search and then calculates score for each result.
3269// Given previous search results in $objects argument, it adds new results
3270// to the array and updates score for existing results, if it is greater than
3271// existing score.
3272function mergeSearchResults (&$objects, $terms, $fieldname)
3273{
3274 global $dbxlink;
3275 $query =
b89ba713 3276 "select ro.name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
d983f70a 3277 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
10bac82a 3278 "on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id where Chapter.name = 'RackObjectType' and ";
d983f70a
DO
3279 $count = 0;
3280 foreach (explode (' ', $terms) as $term)
3281 {
3282 if ($count) $query .= ' or ';
b89ba713 3283 $query .= "ro.${fieldname} like '%$term%'";
d983f70a
DO
3284 $count++;
3285 }
3286 $query .= " order by ${fieldname}";
3287 $result = useSelectBlade ($query, __FUNCTION__);
d983f70a
DO
3288 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3289 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3290 {
3291 foreach ($clist as $cname)
3292 $object[$cname] = $row[$cname];
3293 $object['score'] = 0;
3294 $object['dname'] = displayedName ($object);
3295 unset ($object['objtype_id']);
3296 foreach (explode (' ', $terms) as $term)
3297 if (strstr ($object['name'], $term))
3298 $object['score'] += 1;
3299 unset ($object['name']);
3300 if (!isset ($objects[$row['id']]))
3301 $objects[$row['id']] = $object;
3302 elseif ($objects[$row['id']]['score'] < $object['score'])
3303 $objects[$row['id']]['score'] = $object['score'];
3304 }
3305 return $objects;
3306}
3307
09620506
DO
3308function getLostIPv4Addresses ()
3309{
f7414fa5 3310 dragon();
09620506
DO
3311}
3312
121496b6
DO
3313// Return a list of files which are not linked to the specified record. This list
3314// will be used by printSelect().
e1ae3fb4
AD
3315function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3316{
3317 if ($entity_type == NULL || $entity_id == 0)
3318 {
3319 showError ('Invalid parameters', __FUNCTION__);
3320 return NULL;
3321 }
3322 global $dbxlink;
3323 $sql =
121496b6 3324 'SELECT id, name FROM File ' .
e1ae3fb4 3325 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
121496b6 3326 'ORDER BY name, id';
e1ae3fb4
AD
3327 $query = $dbxlink->prepare($sql);
3328 $query->bindParam(1, $entity_type);
3329 $query->bindParam(2, $entity_id);
3330 $query->execute();
3331 $ret=array();
e1ae3fb4 3332 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3333 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3334 return $ret;
3335}
3336
6df2025d
DO
3337// FIXME: return a standard cell list, so upper layer can iterate over
3338// it conveniently.
e1ae3fb4
AD
3339function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3340{
3341 if ($entity_type == NULL || $entity_id == 0)
3342 {
3343 showError ('Invalid parameters', __FUNCTION__);
3344 return NULL;
3345 }
3346 global $dbxlink;
3347 $sql =
3348 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3349 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3350 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3351 $query = $dbxlink->prepare($sql);
3352 $query->bindParam(1, $entity_type);
3353 $query->bindParam(2, $entity_id);
3354 $query->execute();
3355 $ret = array();
3356 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3357 $ret[$row['file_id']] = array (
b3567368 3358 'id' => $row['file_id'],
e1ae3fb4
AD
3359 'link_id' => $row['link_id'],
3360 'name' => $row['name'],
3361 'type' => $row['type'],
3362 'size' => $row['size'],
3363 'ctime' => $row['ctime'],
3364 'mtime' => $row['mtime'],
3365 'atime' => $row['atime'],
3366 'comment' => $row['comment'],
3367 );
3368 return $ret;
3369}
3370
3371function getFile ($file_id = 0)
3372{
3373 if ($file_id == 0)
3374 {
3375 showError ('Invalid file_id', __FUNCTION__);
3376 return NULL;
3377 }
3378 global $dbxlink;
3379 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3380 $query->bindParam(1, $file_id);
3381 $query->execute();
3382 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3383 {
3384 showError ('Query succeeded, but returned no data', __FUNCTION__);
3385 $ret = NULL;
3386 }
3387 else
3388 {
3389 $ret = array();
3390 $ret['id'] = $row['id'];
3391 $ret['name'] = $row['name'];
3392 $ret['type'] = $row['type'];
3393 $ret['size'] = $row['size'];
3394 $ret['ctime'] = $row['ctime'];
3395 $ret['mtime'] = $row['mtime'];
3396 $ret['atime'] = $row['atime'];
3397 $ret['contents'] = $row['contents'];
3398 $ret['comment'] = $row['comment'];
bed9cd76 3399 $query->closeCursor();
e1ae3fb4 3400
deb3da1b 3401 // Someone accessed this file, update atime
e1ae3fb4
AD
3402 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3403 $q_atime->bindParam(1, date('YmdHis'));
3404 $q_atime->bindParam(2, $file_id);
3405 $q_atime->execute();
3406 }
e1ae3fb4
AD
3407 return $ret;
3408}
3409
e1ae3fb4
AD
3410function getFileLinks ($file_id = 0)
3411{
3412 if ($file_id <= 0)
3413 {
3414 showError ('Invalid file_id', __FUNCTION__);
3415 return NULL;
3416 }
3417
3418 global $dbxlink;
8bc5d1e4 3419 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ? ORDER BY entity_type, entity_id');
e1ae3fb4
AD
3420 $query->bindParam(1, $file_id);
3421 $query->execute();
da3302ab 3422 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3423 $ret = array();
da3302ab 3424 foreach ($rows as $row)
e1ae3fb4
AD
3425 {
3426 // get info of the parent
3427 switch ($row['entity_type'])
3428 {
3429 case 'ipv4net':
3430 $page = 'ipv4net';
3431 $id_name = 'id';
d724d290 3432 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3433 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3434 break;
3435 case 'ipv4rspool':
3854af78 3436 $page = 'ipv4rspool';
e1ae3fb4 3437 $id_name = 'pool_id';
a6e91ac2 3438 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3439 $name = $parent['name'];
3440 break;
3441 case 'ipv4vs':
3442 $page = 'ipv4vs';
3443 $id_name = 'vs_id';
7c38462f 3444 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3445 $name = $parent['name'];
3446 break;
3447 case 'object':
3448 $page = 'object';
3449 $id_name = 'object_id';
6297d584 3450 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
7ddbcf59 3451 $name = $parent['dname'];
e1ae3fb4
AD
3452 break;
3453 case 'rack':
3454 $page = 'rack';
3455 $id_name = 'rack_id';
61a1d996 3456 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3457 $name = $parent['name'];
3458 break;
3459 case 'user':
3460 $page = 'user';
3461 $id_name = 'user_id';
0b2c74cb
DO
3462 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3463 $name = $parent['user_name'];
e1ae3fb4
AD
3464 break;
3465 }
3466
17d95c32
AD
3467 // name needs to have some value for hrefs to work
3468 if (empty($name))
3469 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3470
e1ae3fb4
AD
3471 $ret[$row['id']] = array(
3472 'page' => $page,
3473 'id_name' => $id_name,
3474 'entity_type' => $row['entity_type'],
3475 'entity_id' => $row['entity_id'],
3476 'name' => $name
3477 );
3478 }
3479 return $ret;
3480}
3481
3482// Return list of possible file parents along with the number of children.
3483// Used on main Files listing page.
3484function getFileLinkInfo ()
3485{
3486 global $dbxlink;
3487 $query = 'SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type';
3488
3489 $result = useSelectBlade ($query, __FUNCTION__);
3490 $ret = array();
3491 $ret[0] = array ('entity_type' => 'all', 'name' => 'ALL files');
3492 $clist = array ('entity_type', 'name', 'count');
3493 $total = 0;
3494 $i=2;
3495 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3496 if ($row['count'] > 0)
3497 {
3498 $total += $row['count'];
3499 $row['name'] = formatEntityName ($row['entity_type']);
3500 foreach ($clist as $cname)
3501 $ret[$i][$cname] = $row[$cname];
3502 $i++;
3503 }
3504 $result->closeCursor();
3505
3506 // Find number of files without any linkage
3507 $linkless_sql =
3508 'SELECT COUNT(*) ' .
3509 'FROM File ' .
3510 'WHERE id NOT IN (SELECT file_id FROM FileLink)';
3511 $q_linkless = useSelectBlade ($linkless_sql, __FUNCTION__);
3512 $ret[1] = array ('entity_type' => 'no_links', 'name' => 'Files w/no links', 'count' => $q_linkless->fetchColumn ());
3513 $q_linkless->closeCursor();
3514
3515 // Find total number of files
3516 $total_sql = 'SELECT COUNT(*) FROM File';
3517 $q_total = useSelectBlade ($total_sql, __FUNCTION__);
3518 $ret[0]['count'] = $q_total->fetchColumn ();
3519 $q_total->closeCursor();
3520
3521 ksort($ret);
3522 return $ret;
3523}
3524
3525function commitAddFile ($name, $type, $size, $contents, $comment)
3526{
3527 $now = date('YmdHis');
3528
3529 global $dbxlink;
3530 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3531 $query->bindParam(1, $name);
3532 $query->bindParam(2, $type);
3533 $query->bindParam(3, $size);
3534 $query->bindParam(4, $now);
3535 $query->bindParam(5, $now);
3536 $query->bindParam(6, $now);
3537 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3538 $query->bindParam(8, $comment);
3539
3540 $result = $query->execute();
3541
3542
3543 if ($result)
3544 return '';
590e1281 3545 elseif ($query->errorCode() == 23000)
13edfa1c 3546 return "commitAddFile: File named '${name}' already exists";
e1ae3fb4
AD
3547 else
3548 return 'commitAddFile: SQL query failed';
3549}
3550
4a2c6c6b 3551function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4
AD
3552{
3553 global $dbxlink;
3554 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3555 $query->bindParam(1, $file_id);
4a2c6c6b
AD
3556 $query->bindParam(2, $entity_type);
3557 $query->bindParam(3, $entity_id);
e1ae3fb4
AD
3558
3559 $result = $query->execute();
3560
3561 if ($result)
3562 return '';
3563 else
3564 return 'commitLinkFile: SQL query failed';
3565}
3566
f8874cdb 3567function commitReplaceFile ($file_id = 0, $contents)
fd1fb420
AD
3568{
3569 if ($file_id == 0)
3570 {
3571 showError ('Not all required args are present.', __FUNCTION__);
3572 return FALSE;
3573 }
fd1fb420
AD
3574
3575 global $dbxlink;
f8874cdb
DO
3576 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3577 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3578 $query->bindParam(2, $file_id);
fd1fb420
AD
3579
3580 $result = $query->execute();
3581 if (!$result)
3582 {
3583 showError ('commitReplaceFile: SQL query failed', __FUNCTION__);
3584 return FALSE;
3585 }
3586 return '';
3587}
3588
9db67d95 3589function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
e1ae3fb4 3590{
9db67d95 3591 if ($file_id <= 0 or empty ($new_name) or empty ($new_type))
e1ae3fb4
AD
3592 {
3593 showError ('Not all required args are present.', __FUNCTION__);
3594 return FALSE;
3595 }
3596 global $dbxlink;
9db67d95 3597 $query = $dbxlink->prepare('UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?');
6ee41bd4 3598 $query->bindParam(1, $new_name);
9db67d95
DO
3599 $query->bindParam(2, $new_type);
3600 $query->bindParam(3, $new_comment);
3601 $query->bindParam(4, $file_id);
e1ae3fb4
AD
3602
3603 $result = $query->execute();
3604 if (!$result)
6ee41bd4 3605 return 'SQL query failed in ' . __FUNCTION__;
e1ae3fb4
AD
3606 return '';
3607}
3608
3609function commitUnlinkFile ($link_id)
3610{
3611 if (useDeleteBlade ('FileLink', 'id', $link_id) != TRUE)
3612 return __FUNCTION__ . ': useDeleteBlade() failed';
3613 return '';
3614}
3615
3616function commitDeleteFile ($file_id)
3617{
3618 if (useDeleteBlade ('File', 'id', $file_id) != TRUE)
3619 return __FUNCTION__ . ': useDeleteBlade() failed';
3620 return '';
3621}
3622
4034ab9e
DO
3623function getChapterList ()
3624{
3625 $ret = array();
c4d0dc30 3626 $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 3627 while ($row = $result->fetch (PDO::FETCH_ASSOC))
c4d0dc30 3628 $ret[$row['id']] = $row;
4034ab9e
DO
3629 return $ret;
3630}
3631
2d1e6b63 3632// Return file id by file name.
72d2a7ee
DO
3633function findFileByName ($filename)
3634{
2d1e6b63
AD
3635 global $dbxlink;
3636 $query = $dbxlink->prepare('SELECT id FROM File WHERE name = ?');
3637 $query->bindParam(1, $filename);
3638 $query->execute();
3639 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
72d2a7ee 3640 return $row['id'];
2d1e6b63
AD
3641
3642 return NULL;
72d2a7ee
DO
3643}