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