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