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