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