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