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