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