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