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