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