r2760 - getRackSearchResult(): another variation of a standard helper (cloned from...
[racktables] / inc / database.php
CommitLineData
b325120a 1<?php
e673ee24
DO
2/*
3*
4* This file is a library of database access functions for RackTables.
5*
6*/
7
a6e91ac2
DO
8$SQLSchema = array
9(
10 'object' => array
11 (
12 'table' => 'RackObject',
13 'columns' => array
14 (
15 'id' => 'id',
16 'name' => 'name',
17 'label' => 'label',
18 'barcode' => 'barcode',
19 'asset_no' => 'asset_no',
20 'objtype_id' => 'objtype_id',
21 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
22 'Rack_name' => '(select name from Rack where id = rack_id)',
23 'row_id' => '(select row_id from Rack where id = rack_id)',
24 'Row_name' => '(select name from RackRow where id = row_id)',
25 'objtype_name' => '(select dict_value from Dictionary where dict_key = objtype_id)',
26 ),
27 'keycolumn' => 'id',
28 'ordcolumns' => array ('name'),
29 ),
30 'user' => array
31 (
32 'table' => 'UserAccount',
33 'columns' => array
34 (
35 'user_id' => 'user_id',
36 'user_name' => 'user_name',
37 'user_password_hash' => 'user_password_hash',
38 'user_realname' => 'user_realname',
39 ),
40 'keycolumn' => 'user_id',
41 'ordcolumns' => array ('user_name'),
42 ),
43 'ipv4net' => array
44 (
45 'table' => 'IPv4Network',
46 'columns' => array
47 (
48 'id' => 'id',
49 'ip' => 'INET_NTOA(IPv4Network.ip)',
50 'mask' => 'mask',
51 'name' => 'name',
52 ),
53 'keycolumn' => 'id',
54 'ordcolumns' => array ('ip', 'mask'),
55 ),
56 'file' => array
57 (
58 'table' => 'File',
59 'columns' => array
60 (
61 'id' => 'id',
62 'name' => 'name',
63 'type' => 'type',
64 'size' => 'size',
65 'ctime' => 'ctime',
66 'mtime' => 'mtime',
67 'atime' => 'atime',
68 'comment' => 'comment',
69 ),
70 'keycolumn' => 'id',
71 'ordcolumns' => array ('name'),
72 ),
73 'ipv4vs' => array
74 (
75 'table' => 'IPv4VS',
76 'columns' => array
77 (
78 'id' => 'id',
79 'vip' => 'INET_NTOA(vip)',
80 'vport' => 'vport',
81 'proto' => 'proto',
82 'name' => 'name',
83 'vsconfig' => 'vsconfig',
84 'rsconfig' => 'rsconfig',
85 'poolcount' => '(select count(vs_id) from IPv4LB where vs_id = id)',
86 'dname' => 'CONCAT_WS("/", CONCAT_WS(":", INET_NTOA(vip), vport), proto)',
87 ),
88 'keycolumn' => 'id',
89 'ordcolumns' => array ('vip', 'proto', 'vport'),
90 ),
91 'ipv4rspool' => array
92 (
93 'table' => 'IPv4RSPool',
94 'columns' => array
95 (
96 'id' => 'id',
97 'name' => 'name',
98 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
99 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
100 'vsconfig' => 'vsconfig',
101 'rsconfig' => 'rsconfig',
102 ),
103 'keycolumn' => 'id',
104 'ordcolumns' => array ('name', 'id'),
105 ),
106 'rack' => array
107 (
108 'table' => 'Rack',
109 'columns' => array
110 (
111 'id' => 'id',
112 'name' => 'name',
113 'height' => 'height',
114 'comment' => 'comment',
115 'row_id' => 'row_id',
116 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
117 ),
118 'keycolumn' => 'id',
119 'ordcolumns' => array ('row_id', 'name'),
120 'pidcolumn' => 'row_id',
121 ),
122);
123
e1ae3fb4
AD
124function isInnoDBSupported ($dbh = FALSE) {
125 global $dbxlink;
126
127 // sometimes db handle isn't available globally, must be passed
128 if (!$dbxlink)
129 $dbxlink = $dbh;
130
131 // create a temp table
132 $dbxlink->query("CREATE TABLE `innodb_test` (`id` int) ENGINE=InnoDB");
133 $row = $dbxlink->query("SHOW TABLE STATUS LIKE 'innodb_test'")->fetch(PDO::FETCH_ASSOC);
134 $dbxlink->query("DROP TABLE `innodb_test`");
135 if ($row['Engine'] == 'InnoDB')
136 return TRUE;
137
138 return FALSE;
139}
140
5f54485b 141function escapeString ($value, $do_db_escape = TRUE)
e673ee24 142{
b614498d 143 $ret = htmlspecialchars ($value, ENT_QUOTES, 'UTF-8');
5f54485b
DO
144 if ($do_db_escape)
145 {
146 global $dbxlink;
147 $ret = substr ($dbxlink->quote ($ret), 1, -1);
148 }
149 return $ret;
e673ee24
DO
150}
151
a8ce7234
DO
152// Return detailed information about one rack row.
153function getRackRowInfo ($rackrow_id)
e673ee24 154{
e673ee24 155 $query =
10bac82a 156 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
5332840f 157 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
10bac82a 158 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
cf5ff1a5 159 "where RackRow.id = ${rackrow_id} " .
1743cafe 160 "group by RackRow.id";
065eeb52 161 $result = useSelectBlade ($query, __FUNCTION__);
a8ce7234
DO
162 if ($row = $result->fetch (PDO::FETCH_ASSOC))
163 return $row;
e673ee24 164 else
a8ce7234 165 return NULL;
e673ee24
DO
166}
167
51690ad4
DY
168function getRackRows ()
169{
170 $query = "select id, name from RackRow ";
171 $result = useSelectBlade ($query, __FUNCTION__);
172 $rows = array();
173 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2a3f0501 174 $rows[$row['id']] = $row['name'];
51690ad4
DY
175 $result->closeCursor();
176 asort ($rows);
177 return $rows;
178}
179
10bac82a
DY
180function commitAddRow($rackrow_name)
181{
590e1281 182 return useInsertBlade('RackRow', array('name'=>"'$rackrow_name'"));
10bac82a
DY
183}
184
185function commitUpdateRow($rackrow_id, $rackrow_name)
186{
187 global $dbxlink;
188 $query = "update RackRow set name = '${rackrow_name}' where id=${rackrow_id}";
189 $result = $dbxlink->query ($query);
190 if ($result == NULL)
191 {
192 showError ("SQL query '${query}' failed", __FUNCTION__);
193 return FALSE;
194 }
195 $result->closeCursor();
196 return TRUE;
197}
198
9f14a7ef
DY
199function commitDeleteRow($rackrow_id)
200{
201 global $dbxlink;
5af82683 202 $query = "select count(*) from Rack where row_id=${rackrow_id}";
9f14a7ef 203 $result = $dbxlink->query ($query);
5af82683
DY
204 if (($result!=NULL) && ($row = $result->fetch(PDO::FETCH_NUM)) )
205 {
206 if ($row[0] == 0)
207 {
208 $query = "delete from RackRow where id=${rackrow_id}";
209 $result = $dbxlink->query ($query);
210 if ($result == NULL)
211 {
212 showError ("SQL query '${query}' failed", __FUNCTION__);
213 return FALSE;
214 }
215 }
216 }
217 else
9f14a7ef
DY
218 {
219 showError ("SQL query '${query}' failed", __FUNCTION__);
220 return FALSE;
221 }
222 $result->closeCursor();
223 return TRUE;
224}
225
e673ee24
DO
226// This function returns id->name map for all object types. The map is used
227// to build <select> input for objects.
228function getObjectTypeList ()
229{
230 return readChapter ('RackObjectType');
231}
232
8d4f7d18 233// Return a simple object list w/o related information, so that the returned value
c6bc0ac5
DO
234// can be directly used by printSelect(). An optional argument is the name of config
235// option with constraint in RackCode.
236function getNarrowObjectList ($varname = '')
e9132485 237{
212c9d8a 238 $wideList = listCells ('object');
59dce363 239 if (strlen ($varname) and strlen (getConfigVar ($varname)))
e9132485 240 {
59dce363
DO
241 global $parseCache;
242 if (!isset ($parseCache[$varname]))
243 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
244 if ($parseCache[$varname]['result'] != 'ACK')
245 return array();
212c9d8a 246 $wideList = filterCellList ($wideList, $parseCache[$varname]['load']);
e9132485 247 }
212c9d8a
DO
248 $ret = array();
249 foreach ($wideList as $cell)
250 $ret[$cell['id']] = $cell['dname'];
e9132485
DO
251 return $ret;
252}
253
d08d766d 254// For a given realm return a list of entity records, each with
212c9d8a 255// enough information for judgeCell() to execute.
a8efc03e 256function listCells ($realm, $parent_id = 0)
d08d766d 257{
a6e91ac2
DO
258 global $SQLSchema;
259 if (!isset ($SQLSchema[$realm]))
d08d766d 260 {
d08d766d 261 showError ('invalid arg', __FUNCTION__);
573214e0 262 return NULL;
d08d766d 263 }
a6e91ac2 264 $SQLinfo = $SQLSchema[$realm];
a8efc03e 265 $query = 'SELECT tag_id';
a6e91ac2 266 foreach ($SQLinfo['columns'] as $alias => $expression)
573214e0 267 // Automatically prepend table name to each single column, but leave all others intact.
a6e91ac2
DO
268 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
269 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = '${realm}' and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
270 if (isset ($SQLinfo['pidcolumn']) and $parent_id)
271 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ${parent_id}";
a8efc03e 272 $query .= " ORDER BY ";
a6e91ac2
DO
273 foreach ($SQLinfo['ordcolumns'] as $oc)
274 $query .= "${SQLinfo['table']}.${oc}, ";
0fbbfad0 275 $query .= " tag_id";
d08d766d
DO
276 $result = useSelectBlade ($query, __FUNCTION__);
277 $ret = array();
278 global $taglist;
279 // Index returned result by the value of key column.
280 while ($row = $result->fetch (PDO::FETCH_ASSOC))
281 {
a6e91ac2 282 $entity_id = $row[$SQLinfo['keycolumn']];
d08d766d
DO
283 // Init the first record anyway, but store tag only if there is one.
284 if (!isset ($ret[$entity_id]))
285 {
573214e0 286 $ret[$entity_id] = array ('realm' => $realm);
a6e91ac2 287 foreach (array_keys ($SQLinfo['columns']) as $alias)
573214e0
DO
288 $ret[$entity_id][$alias] = $row[$alias];
289 $ret[$entity_id]['etags'] = array();
d08d766d
DO
290 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
291 $ret[$entity_id]['etags'][] = array
292 (
293 'id' => $row['tag_id'],
294 'tag' => $taglist[$row['tag_id']]['tag'],
295 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
296 );
297 }
a6e91ac2 298 elseif (isset ($taglist[$row['tag_id']]))
d08d766d
DO
299 // Meeting existing key later is always more tags on existing list.
300 $ret[$entity_id]['etags'][] = array
301 (
302 'id' => $row['tag_id'],
303 'tag' => $taglist[$row['tag_id']]['tag'],
304 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
305 );
306 }
23cdc7e9 307 // Add necessary finish to the list before returning it.
d08d766d
DO
308 foreach (array_keys ($ret) as $entity_id)
309 {
6df2025d 310 $ret[$entity_id]['etags'] = getExplicitTagsOnly ($ret[$entity_id]['etags']);
d08d766d 311 $ret[$entity_id]['itags'] = getImplicitTags ($ret[$entity_id]['etags']);
53da7dca
DO
312 switch ($realm)
313 {
314 case 'ipv4net':
6e9a7d85 315 case 'object':
53da7dca
DO
316 $ret[$entity_id]['atags'] = generateEntityAutoTags ($realm, $ret[$entity_id]);
317 break;
318 default:
319 $ret[$entity_id]['atags'] = generateEntityAutoTags ($realm, $entity_id);
320 }
23cdc7e9
DO
321 switch ($realm)
322 {
323 case 'object':
324 $ret[$entity_id]['dname'] = displayedName ($ret[$entity_id]);
325 break;
d724d290
DO
326 case 'ipv4net':
327 $ret[$entity_id]['ip_bin'] = ip2long ($ret[$entity_id]['ip']);
328 $ret[$entity_id]['mask_bin'] = binMaskFromDec ($ret[$entity_id]['mask']);
329 $ret[$entity_id]['mask_bin_inv'] = binInvMaskFromDec ($ret[$entity_id]['mask']);
330 $ret[$entity_id]['db_first'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] & $ret[$entity_id]['mask_bin']);
331 $ret[$entity_id]['db_last'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] | ($ret[$entity_id]['mask_bin_inv']));
332 break;
23cdc7e9
DO
333 default:
334 break;
335 }
d08d766d
DO
336 }
337 return $ret;
338}
339
a6e91ac2
DO
340// Very much like listCells(), but return only one record requested (or NULL,
341// if it does not exist).
342function spotEntity ($realm, $id)
343{
344 global $SQLSchema;
345 if (!isset ($SQLSchema[$realm]))
346 {
347 showError ('invalid arg', __FUNCTION__);
348 return NULL;
349 }
350 $SQLinfo = $SQLSchema[$realm];
351 $query = 'SELECT tag_id';
352 foreach ($SQLinfo['columns'] as $alias => $expression)
353 // Automatically prepend table name to each single column, but leave all others intact.
354 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
355 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = '${realm}' and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
356 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ${id}";
357 $query .= " ORDER BY tag_id";
358 $result = useSelectBlade ($query, __FUNCTION__);
359 $ret = array();
360 global $taglist;
361 while ($row = $result->fetch (PDO::FETCH_ASSOC))
362 if (!isset ($ret['realm']))
363 {
364 $ret = array ('realm' => $realm);
365 foreach (array_keys ($SQLinfo['columns']) as $alias)
366 $ret[$alias] = $row[$alias];
367 $ret['etags'] = array();
368 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
369 $ret['etags'][] = array
370 (
371 'id' => $row['tag_id'],
372 'tag' => $taglist[$row['tag_id']]['tag'],
373 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
374 );
375 }
376 elseif (isset ($taglist[$row['tag_id']]))
377 $ret['etags'][] = array
378 (
379 'id' => $row['tag_id'],
380 'tag' => $taglist[$row['tag_id']]['tag'],
381 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
382 );
383 unset ($result);
384 if (!isset ($ret['realm'])) // no rows were returned
385 return NULL;
6df2025d 386 $ret['etags'] = getExplicitTagsOnly ($ret['etags']);
a6e91ac2 387 $ret['itags'] = getImplicitTags ($ret['etags']);
53da7dca
DO
388 switch ($realm)
389 {
390 case 'ipv4net':
6e9a7d85 391 case 'object':
53da7dca
DO
392 $ret['atags'] = generateEntityAutoTags ($realm, $ret);
393 break;
394 default:
395 $ret['atags'] = generateEntityAutoTags ($realm, $id);
396 }
a6e91ac2
DO
397 switch ($realm)
398 {
399 case 'object':
400 $ret['dname'] = displayedName ($ret);
401 break;
d724d290
DO
402 case 'ipv4net':
403 $ret['ip_bin'] = ip2long ($ret['ip']);
404 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
405 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
406 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
407 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
408 break;
a6e91ac2
DO
409 default:
410 break;
411 }
412 return $ret;
413}
414
d08d766d 415// This function can be used with array_walk().
573214e0 416function amplifyCell (&$record, $dummy = NULL)
d08d766d 417{
d08d766d
DO
418 switch ($record['realm'])
419 {
420 case 'object':
421 $record['ports'] = getObjectPortsAndLinks ($record['id']);
422 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
423 $record['nat4'] = getNATv4ForObject ($record['id']);
424 $record['ipv4rspools'] = getRSPoolsForObject ($record['id']);
425 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
426 break;
573214e0
DO
427 case 'ipv4net':
428 $record['ip_bin'] = ip2long ($record['ip']);
429 $record['parent_id'] = getIPv4AddressNetworkId ($record['ip'], $record['mask']);
430 break;
8bc5d1e4
DO
431 case 'file':
432 $record['links'] = getFileLinks ($record['id']);
433 break;
a6e91ac2
DO
434 case 'ipv4rspool':
435 $record['lblist'] = array();
436 $query = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
437 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
438 "where rspool_id = ${record['id']} order by object_id, vip, vport";
439 $result = useSelectBlade ($query, __FUNCTION__);
440 while ($row = $result->fetch (PDO::FETCH_ASSOC))
441 $record['lblist'][$row['object_id']][$row['vs_id']] = array
442 (
443 'rsconfig' => $row['rsconfig'],
444 'vsconfig' => $row['vsconfig'],
445 );
446 unset ($result);
7c38462f 447 $record['rslist'] = array();
a6e91ac2
DO
448 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
449 "IPv4RS where rspool_id = ${record['id']} order by IPv4RS.rsip, rsport";
450 $result = useSelectBlade ($query, __FUNCTION__);
451 while ($row = $result->fetch (PDO::FETCH_ASSOC))
452 $record['rslist'][$row['id']] = array
453 (
454 'inservice' => $row['inservice'],
455 'rsip' => $row['rsip'],
456 'rsport' => $row['rsport'],
457 'rsconfig' => $row['rsconfig'],
458 );
459 unset ($result);
7c38462f
DO
460 break;
461 case 'ipv4vs':
462 // Get the detailed composition of a particular virtual service, namely the list
463 // of all pools, each shown with the list of objects servicing it. VS/RS configs
464 // will be returned as well.
465 $record['rspool'] = array();
466 $query = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
467 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
468 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
469 "where vs_id = ${record['id']} order by pool.name, object_id";
470 $result = useSelectBlade ($query, __FUNCTION__);
471 while ($row = $result->fetch (PDO::FETCH_ASSOC))
472 {
473 if (!isset ($record['rspool'][$row['id']]))
474 $record['rspool'][$row['id']] = array
475 (
476 'name' => $row['name'],
477 'vsconfig' => $row['vsconfig'],
478 'rsconfig' => $row['rsconfig'],
479 'lblist' => array(),
480 );
481 if ($row['object_id'] == NULL)
482 continue;
483 $record['rspool'][$row['id']]['lblist'][$row['object_id']] = array
484 (
485 'vsconfig' => $row['lb_vsconfig'],
486 'rsconfig' => $row['lb_rsconfig'],
487 );
488 }
489 unset ($result);
490 break;
61a1d996
DO
491 case 'rack':
492 $record['mountedObjects'] = array();
493 // start with default rackspace
494 for ($i = $record['height']; $i > 0; $i--)
495 for ($locidx = 0; $locidx < 3; $locidx++)
496 $record[$i][$locidx]['state'] = 'F';
497 // load difference
498 $query =
499 "select unit_no, atom, state, object_id " .
500 "from RackSpace where rack_id = ${record['id']} and " .
501 "unit_no between 1 and " . $record['height'] . " order by unit_no";
502 $result = useSelectBlade ($query, __FUNCTION__);
503 global $loclist;
504 $mounted_objects = array();
505 while ($row = $result->fetch (PDO::FETCH_ASSOC))
506 {
507 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
508 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
509 if ($row['state'] == 'T' and $row['object_id'] != NULL)
510 $mounted_objects[$row['object_id']] = TRUE;
511 }
512 $record['mountedObjects'] = array_keys ($mounted_objects);
513 unset ($result);
514 break;
d08d766d
DO
515 default:
516 }
517}
518
e673ee24 519// This is a popular helper.
7ddbcf59 520function getObjectInfo ($object_id = 0, $set_dname = TRUE)
e673ee24 521{
e673ee24 522 $query =
1743cafe 523 "select RackObject.id as id, RackObject.name as name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
10bac82a 524 "RackObject inner join Dictionary on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
aa9a0fb4 525 "where RackObject.id = '${object_id}' and Chapter.name = 'RackObjectType'";
105a3bc8 526 $result = useSelectBlade ($query, __FUNCTION__);
f08ed0b2 527 if (($ret = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
e673ee24 528 {
105a3bc8 529 showError ('Query succeeded, but returned no data', __FUNCTION__);
f08ed0b2 530 return NULL;
e673ee24
DO
531 }
532 $result->closeCursor();
f08ed0b2
DO
533 // It's safe now to run subsequent queries.
534 if ($set_dname)
535 $ret['dname'] = displayedName ($ret);
e673ee24
DO
536 return $ret;
537}
538
539function getPortTypes ()
540{
fe6e3bd7 541 return readChapter ('PortType');
e673ee24
DO
542}
543
125b5f39 544function getObjectPortsAndLinks ($object_id)
e673ee24 545{
1919110a
DO
546 // prepare decoder
547 $ptd = readChapter ('PortType');
548 $query = "select id, name, label, l2address, type as type_id, reservation_comment from Port where object_id = ${object_id}";
549 // list and decode all ports of the current object
065eeb52 550 $result = useSelectBlade ($query, __FUNCTION__);
e425f895 551 $ret=array();
e425f895 552 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 553 {
1919110a
DO
554 $row['type'] = $ptd[$row['type_id']];
555 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
556 $row['remote_id'] = NULL;
557 $row['remote_name'] = NULL;
558 $row['remote_object_id'] = NULL;
559 $row['remote_object_name'] = NULL;
560 $ret[] = $row;
561 }
562 unset ($result);
563 // now find and decode remote ends for all locally terminated connections
125b5f39 564 // FIXME: can't this data be extracted in one pass with sub-queries?
1919110a
DO
565 foreach (array_keys ($ret) as $tmpkey)
566 {
567 $portid = $ret[$tmpkey]['id'];
568 $remote_id = NULL;
569 $query = "select porta, portb from Link where porta = {$portid} or portb = ${portid}";
570 $result = useSelectBlade ($query, __FUNCTION__);
571 if ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 572 {
1919110a
DO
573 if ($portid != $row['porta'])
574 $remote_id = $row['porta'];
575 elseif ($portid != $row['portb'])
576 $remote_id = $row['portb'];
577 }
578 unset ($result);
579 if ($remote_id) // there's a remote end here
580 {
581 $query = "select Port.name as port_name, Port.type as port_type, object_id, RackObject.name as object_name " .
582 "from Port left join RackObject on Port.object_id = RackObject.id " .
583 "where Port.id = ${remote_id}";
584 $result = useSelectBlade ($query, __FUNCTION__);
585 if ($row = $result->fetch (PDO::FETCH_ASSOC))
586 {
587 $ret[$tmpkey]['remote_name'] = $row['port_name'];
588 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
589 $ret[$tmpkey]['remote_object_name'] = $row['object_name'];
590 }
591 $ret[$tmpkey]['remote_id'] = $remote_id;
592 unset ($result);
593 // only call displayedName() when necessary
594 if (empty ($ret[$tmpkey]['remote_object_name']) and !empty ($ret[$tmpkey]['remote_object_id']))
595 {
596 $oi = getObjectInfo ($ret[$tmpkey]['remote_object_id']);
7ddbcf59 597 $ret[$tmpkey]['remote_object_name'] = $oi['dname'];
1919110a 598 }
e673ee24
DO
599 }
600 }
e673ee24
DO
601 return $ret;
602}
603
f19c75d6 604function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
e673ee24 605{
f19c75d6
DO
606 if ($row_id <= 0 or $height <= 0 or empty ($name))
607 return FALSE;
406b54bd
DO
608 $result = useInsertBlade
609 (
610 'Rack',
611 array
612 (
613 'row_id' => $row_id,
614 'name' => "'${name}'",
615 'height' => $height,
616 'comment' => "'${comment}'"
617 )
618 );
619 if ($result == NULL)
e673ee24 620 {
406b54bd 621 showError ('useInsertBlade() failed', __FUNCTION__);
e673ee24
DO
622 return FALSE;
623 }
c63a8d6e 624 $last_insert_id = lastInsertID();
351c0966 625 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', "id = ${last_insert_id}");
e673ee24
DO
626}
627
f60bb422 628function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
e673ee24
DO
629{
630 global $dbxlink;
f60bb422
DO
631 // Maintain UNIQUE INDEX for common names and asset tags by
632 // filtering out empty strings (not NULLs).
633 $result1 = useInsertBlade
634 (
635 'RackObject',
636 array
637 (
638 'name' => empty ($new_name) ? 'NULL' : "'${new_name}'",
639 'label' => "'${new_label}'",
640 'barcode' => empty ($new_barcode) ? 'NULL' : "'${new_barcode}'",
641 'objtype_id' => $new_type_id,
642 'asset_no' => empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'"
643 )
644 );
e673ee24
DO
645 if ($result1 == NULL)
646 {
f60bb422 647 showError ("SQL query #1 failed", __FUNCTION__);
e673ee24
DO
648 return FALSE;
649 }
c63a8d6e 650 $last_insert_id = lastInsertID();
ad0e4754
DO
651 // Do AutoPorts magic
652 executeAutoPorts ($last_insert_id, $new_type_id);
f60bb422 653 // Now tags...
351c0966 654 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
c63a8d6e
DO
655 if ($error != '')
656 {
657 showError ("Error adding tags for the object: ${error}");
658 return FALSE;
659 }
e673ee24
DO
660 return recordHistory ('RackObject', "id = ${last_insert_id}");
661}
662
663function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
664{
665 if ($object_id == 0 || $new_type_id == 0)
666 {
f41b492f 667 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
668 return FALSE;
669 }
670 global $dbxlink;
671 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
672 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
673 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
674 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
675 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
676 "where id='${object_id}' limit 1";
677 $result = $dbxlink->query ($query);
678 if ($result == NULL)
679 {
f41b492f 680 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
681 return FALSE;
682 }
e673ee24
DO
683 $result->closeCursor();
684 return recordHistory ('RackObject', "id = ${object_id}");
685}
686
52b34485
AD
687// There are times when you want to delete all traces of an object
688function commitDeleteObject ($object_id = 0)
689{
690 if ($object_id <= 0)
691 {
692 showError ('Invalid args', __FUNCTION__);
693 die;
694 }
695 global $dbxlink;
9f8dbae6
AD
696 $dbxlink->query("DELETE FROM AttributeValue WHERE object_id = ${object_id}");
697 $dbxlink->query("DELETE FROM File WHERE id IN (SELECT file_id FROM FileLink WHERE entity_id = 'object' AND entity_id = ${object_id})");
706ce117
DO
698 $dbxlink->query("DELETE FROM IPv4LB WHERE object_id = ${object_id}");
699 $dbxlink->query("DELETE FROM IPv4Allocation WHERE object_id = ${object_id}");
9f8dbae6 700 $dbxlink->query("DELETE FROM Port WHERE object_id = ${object_id}");
706ce117 701 $dbxlink->query("DELETE FROM IPv4NAT WHERE object_id = ${object_id}");
9f8dbae6 702 $dbxlink->query("DELETE FROM RackSpace WHERE object_id = ${object_id}");
120e9ddd 703 $dbxlink->query("DELETE FROM TagStorage WHERE entity_realm = 'object' and entity_id = ${object_id}");
9f8dbae6
AD
704 $dbxlink->query("DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ${object_id})");
705 $dbxlink->query("DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ${object_id})");
706 $dbxlink->query("DELETE FROM MountOperation WHERE object_id = ${object_id}");
707 $dbxlink->query("DELETE FROM RackObjectHistory WHERE id = ${object_id}");
708 $dbxlink->query("DELETE FROM RackObject WHERE id = ${object_id}");
52b34485
AD
709
710 return '';
711}
712
c8187437
DY
713function commitDeleteRack($rack_id)
714{
715 global $dbxlink;
716 $query = "delete from RackSpace where rack_id = '${rack_id}'";
717 $dbxlink->query ($query);
718 $query = "delete from TagStorage where entity_realm='rack' and entity_id='${rack_id}'";
719 $dbxlink->query ($query);
720 $query = "delete from RackHistory where id = '${rack_id}'";
721 $dbxlink->query ($query);
722 $query = "delete from Rack where id = '${rack_id}'";
723 $dbxlink->query ($query);
724 return TRUE;
725}
726
e673ee24
DO
727function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
728{
729 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
730 {
f41b492f 731 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
732 return FALSE;
733 }
734 global $dbxlink;
7d70d643
AD
735
736 // Can't shrink a rack if rows being deleted contain mounted objects
737 $check_sql = "SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = '${rack_id}' AND unit_no > '{$new_height}'";
738 $check_result = $dbxlink->query($check_sql);
739 $check_row = $check_result->fetch (PDO::FETCH_ASSOC);
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{
706ce117 1516 $query = "select id as pool_id, name from IPv4RSPool where ";
05411ccd
DO
1517 $or = '';
1518 foreach (explode (' ', $terms) as $term)
1519 {
1520 $query .= $or . "name like '%${term}%'";
1521 $or = ' or ';
1522 }
065eeb52 1523 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1524 $ret = array();
1525 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1526 $ret[] = $row;
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);
a6e91ac2 2403 debug_print_backtrace();
5967b83d
DO
2404 return NULL;
2405 }
2406 return $result;
2407}
2408
9c0b0016
DO
2409function loadConfigCache ()
2410{
4fe32e78 2411 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 2412 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
2413 $cache = array();
2414 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2415 $cache[$row['varname']] = $row;
2416 $result->closeCursor();
2417 return $cache;
2418}
2419
2420// setConfigVar() is expected to perform all necessary filtering
2421function storeConfigVar ($varname = NULL, $varvalue = NULL)
2422{
c461c579 2423 global $dbxlink;
bb6b9880 2424 if (empty ($varname) || $varvalue === NULL)
9c0b0016 2425 {
f41b492f 2426 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
2427 return FALSE;
2428 }
2429 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2430 $result = $dbxlink->query ($query);
2431 if ($result == NULL)
2432 {
f41b492f 2433 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
2434 return FALSE;
2435 }
2436 $rc = $result->rowCount();
2437 $result->closeCursor();
f7ee57a1 2438 if ($rc == 0 or $rc == 1)
9c0b0016 2439 return TRUE;
f41b492f 2440 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2441 return FALSE;
2442}
2443
fbbb74fb
DO
2444// Database version detector. Should behave corretly on any
2445// working dataset a user might have.
2446function getDatabaseVersion ()
2447{
2448 global $dbxlink;
2449 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2450 $result = $dbxlink->query ($query);
2451 if ($result == NULL)
2452 {
2453 $errorInfo = $dbxlink->errorInfo();
2454 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2455 return '0.14.4';
4d2e93f2 2456 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2457 }
2458 $rows = $result->fetchAll (PDO::FETCH_NUM);
2459 if (count ($rows) != 1 || empty ($rows[0][0]))
2460 {
2461 $result->closeCursor();
4d2e93f2 2462 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2463 }
2464 $ret = $rows[0][0];
2465 $result->closeCursor();
2466 return $ret;
2467}
2468
da04825a
DO
2469// Return an array of virtual services. For each of them list real server pools
2470// with their load balancers and other stats.
62a1dcb5
DO
2471function getSLBSummary ()
2472{
6fec9f39
DO
2473 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2474 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2475 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2476 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2477 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
6fec9f39 2478 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 2479 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2480 $ret = array();
2481 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2482 {
4cadac8f 2483 $vsid = $row['vsid'];
da04825a 2484 $object_id = $row['object_id'];
4cadac8f
DO
2485 if (!isset ($ret[$vsid]))
2486 {
2487 $ret[$vsid] = array();
13bffb29 2488 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2489 $ret[$vsid][$cname] = $row[$cname];
da04825a 2490 $ret[$vsid]['lblist'] = array();
4cadac8f 2491 }
6fec9f39
DO
2492 // There's only one assigned RS pool possible for each LB-VS combination.
2493 $ret[$vsid]['lblist'][$row['object_id']] = array
2494 (
2495 'id' => $row['rspool_id'],
2496 'size' => $row['rscount'],
2497 'name' => $row['pool_name']
2498 );
c3bdc503 2499 }
060ba26e 2500 $result->closeCursor();
c3bdc503 2501 return $ret;
62a1dcb5
DO
2502}
2503
7e7a8387 2504function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2505{
79a9edb4 2506 if ($pool_id <= 0)
ca461127
DO
2507 {
2508 showError ('Invalid arguments', __FUNCTION__);
2509 die;
2510 }
79a9edb4
DO
2511 if (empty ($rsport) or $rsport == 0)
2512 $rsport = 'NULL';
ca461127
DO
2513 return useInsertBlade
2514 (
706ce117 2515 'IPv4RS',
ca461127
DO
2516 array
2517 (
2518 'rsip' => "inet_aton('${rsip}')",
2519 'rsport' => $rsport,
2520 'rspool_id' => $pool_id,
bcbeadb4 2521 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2522 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2523 )
2524 );
2525}
2526
c63a8d6e 2527function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21
DO
2528{
2529 if (empty ($vip) or $vport <= 0 or empty ($proto))
c63a8d6e
DO
2530 return __FUNCTION__ . ': invalid arguments';
2531 if (!useInsertBlade
d6517a21 2532 (
706ce117 2533 'IPv4VS',
d6517a21
DO
2534 array
2535 (
2536 'vip' => "inet_aton('${vip}')",
2537 'vport' => $vport,
2538 'proto' => "'${proto}'",
2539 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2540 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2541 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2542 )
c63a8d6e
DO
2543 ))
2544 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2545 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2546}
2547
c1ca768c 2548function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2549{
c1ca768c 2550 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2551 {
2552 showError ('Invalid arguments', __FUNCTION__);
2553 die;
2554 }
2555 return useInsertBlade
2556 (
706ce117 2557 'IPv4LB',
3241551e
DO
2558 array
2559 (
2560 'object_id' => $object_id,
2561 'rspool_id' => $pool_id,
c1ca768c 2562 'vs_id' => $vs_id,
3241551e
DO
2563 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2564 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2565 )
ca461127
DO
2566 );
2567}
2568
fb1c4a54
DO
2569function commitDeleteRS ($id = 0)
2570{
2571 if ($id <= 0)
2572 return FALSE;
706ce117 2573 return useDeleteBlade ('IPv4RS', 'id', $id);
fb1c4a54
DO
2574}
2575
d6517a21
DO
2576function commitDeleteVS ($id = 0)
2577{
2578 if ($id <= 0)
2579 return FALSE;
706ce117 2580 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2581}
2582
c1ca768c 2583function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2584{
2585 global $dbxlink;
c4d85fd1 2586 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2587 return FALSE;
706ce117 2588 $query = "delete from IPv4LB where object_id = ${object_id} and " .
c1ca768c 2589 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2590 $result = $dbxlink->exec ($query);
2591 if ($result === NULL)
2592 return FALSE;
2593 elseif ($result != 1)
2594 return FALSE;
2595 else
2596 return TRUE;
2597}
2598
fb1c4a54
DO
2599function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2600{
79a9edb4 2601 if ($rsid <= 0)
fb1c4a54
DO
2602 {
2603 showError ('Invalid args', __FUNCTION__);
2604 die;
2605 }
2606 if (long2ip (ip2long ($rsip)) !== $rsip)
2607 {
2608 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2609 die;
2610 }
79a9edb4
DO
2611 if (empty ($rsport) or $rsport == 0)
2612 $rsport = 'NULL';
fb1c4a54
DO
2613 global $dbxlink;
2614 $query =
706ce117 2615 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2616 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2617 " where id = ${rsid} limit 1";
2618 $result = $dbxlink->query ($query);
2619 if ($result == NULL)
2620 {
2621 showError ("SQL query '${query}' failed", __FUNCTION__);
2622 die;
2623 }
2624 return TRUE;
2625}
2626
c1ca768c 2627function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2628{
c1ca768c 2629 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2630 {
2631 showError ('Invalid args', __FUNCTION__);
2632 die;
2633 }
2634 global $dbxlink;
2635 $query =
706ce117 2636 "update IPv4LB set vsconfig = " .
3241551e
DO
2637 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2638 ', rsconfig = ' .
2639 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2640 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2641 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2642 $result = $dbxlink->exec ($query);
2643 if ($result === NULL)
2644 return FALSE;
3241551e
DO
2645 else
2646 return TRUE;
2647}
2648
d6517a21
DO
2649function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2650{
2651 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2652 {
2653 showError ('Invalid args', __FUNCTION__);
2654 die;
2655 }
2656 global $dbxlink;
706ce117 2657 $query = "update IPv4VS set " .
d6517a21
DO
2658 "vip = inet_aton('${vip}'), " .
2659 "vport = ${vport}, " .
2660 "proto = '${proto}', " .
2661 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2662 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2663 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2664 " where id = ${vsid} limit 1";
d6517a21
DO
2665 $result = $dbxlink->exec ($query);
2666 if ($result === NULL)
2667 return FALSE;
d6517a21
DO
2668 else
2669 return TRUE;
2670}
2671
5a1680d2
DO
2672function loadThumbCache ($rack_id = 0)
2673{
5a1680d2
DO
2674 $ret = NULL;
2675 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2676 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2677 $row = $result->fetch (PDO::FETCH_ASSOC);
2678 if ($row)
2679 $ret = base64_decode ($row['thumb_data']);
2680 $result->closeCursor();
2681 return $ret;
2682}
2683
2684function saveThumbCache ($rack_id = 0, $cache = NULL)
2685{
2686 global $dbxlink;
2687 if ($rack_id == 0 or $cache == NULL)
2688 {
2689 showError ('Invalid arguments', __FUNCTION__);
2690 return;
2691 }
2692 $data = base64_encode ($cache);
2693 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2694 $result = $dbxlink->exec ($query);
2695}
9a81d416 2696
c7fe33be
DO
2697function resetThumbCache ($rack_id = 0)
2698{
2699 global $dbxlink;
2700 if ($rack_id == 0)
2701 {
2702 showError ('Invalid argument', __FUNCTION__);
2703 return;
2704 }
2705 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2706 $result = $dbxlink->exec ($query);
2707}
2708
748805bf 2709// Return the list of attached RS pools for the given object. As long as we have
706ce117 2710// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2711// by vs_id, because there will be only one RS pool listed for each VS of the
2712// current object.
78e7b769
DO
2713function getRSPoolsForObject ($object_id = 0)
2714{
2715 if ($object_id <= 0)
2716 {
2717 showError ('Invalid object_id', __FUNCTION__);
2718 return NULL;
2719 }
748805bf 2720 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2721 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2722 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2723 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2724 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
748805bf
DO
2725 "where lb.object_id = ${object_id} " .
2726 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2727 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2728 $ret = array ();
78e7b769 2729 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2730 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2731 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2732 $result->closeCursor();
748805bf 2733 return $ret;
78e7b769
DO
2734}
2735
c63a8d6e 2736function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2737{
c63a8d6e
DO
2738 if (empty ($name))
2739 return __FUNCTION__ . ': invalid arguments';
2740 if (!useInsertBlade
5ad76f01 2741 (
706ce117 2742 'IPv4RSPool',
5ad76f01
DO
2743 array
2744 (
5ad76f01
DO
2745 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2746 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2747 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2748 )
c63a8d6e
DO
2749 ))
2750 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2751 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2752}
2753
2754function commitDeleteRSPool ($pool_id = 0)
2755{
2756 global $dbxlink;
2757 if ($pool_id <= 0)
2758 return FALSE;
706ce117 2759 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2760}
2761
2762function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2763{
2764 if ($pool_id <= 0)
2765 {
2766 showError ('Invalid arg', __FUNCTION__);
2767 die;
2768 }
2769 global $dbxlink;
706ce117 2770 $query = "update IPv4RSPool set " .
5ad76f01
DO
2771 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2772 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2773 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2774 " where id = ${pool_id} limit 1";
2775 $result = $dbxlink->exec ($query);
2776 if ($result === NULL)
2777 return FALSE;
2778 elseif ($result != 1)
2779 return FALSE;
2780 else
2781 return TRUE;
2782}
2783
8253d9f0
DO
2784function getRSList ()
2785{
1f7d18fa 2786 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
706ce117 2787 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
065eeb52 2788 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2789 $ret = array ();
8253d9f0 2790 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2791 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2792 $ret[$row['id']][$cname] = $row[$cname];
2793 $result->closeCursor();
2794 return $ret;
2795}
2796
2797// Return the list of all currently configured load balancers with their pool count.
2798function getLBList ()
2799{
4b0932b6 2800 $query = "select object_id, count(rspool_id) as poolcount " .
706ce117 2801 "from IPv4LB group by object_id order by object_id";
065eeb52 2802 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2803 $ret = array ();
2804 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2805 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2806 $result->closeCursor();
4b0932b6 2807 return $ret;
8253d9f0
DO
2808}
2809
9e677cbd
DO
2810// For the given object return: it vsconfig/rsconfig; the list of RS pools
2811// attached (each with vsconfig/rsconfig in turn), each with the list of
2812// virtual services terminating the pool. Each pool also lists all real
2813// servers with rsconfig.
2987fc1f 2814function getSLBConfig ($object_id)
9e677cbd
DO
2815{
2816 if ($object_id <= 0)
2817 {
2818 showError ('Invalid arg', __FUNCTION__);
2819 return NULL;
2820 }
9e677cbd 2821 $ret = array();
d91f08f3
DO
2822 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2823 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2824 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2825 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2826 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2827 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2828 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2829 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2830 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2831 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2832 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2833 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2834 {
d91f08f3
DO
2835 $vs_id = $row['vs_id'];
2836 if (!isset ($ret[$vs_id]))
2837 {
2838 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)
2839 $ret[$vs_id][$c] = $row[$c];
2840 $ret[$vs_id]['rslist'] = array();
2841 }
2842 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2843 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2844 }
2845 $result->closeCursor();
2846 return $ret;
2847}
1f7d18fa
DO
2848
2849function commitSetInService ($rs_id = 0, $inservice = '')
2850{
2851 if ($rs_id <= 0 or empty ($inservice))
2852 {
2853 showError ('Invalid args', __FUNCTION__);
2854 return NULL;
2855 }
2856 global $dbxlink;
706ce117 2857 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
1f7d18fa
DO
2858 $result = $dbxlink->exec ($query);
2859 if ($result === NULL)
2860 return FALSE;
2861 elseif ($result != 1)
2862 return FALSE;
2863 else
2864 return TRUE;
2865}
2866
ad0e4754
DO
2867function executeAutoPorts ($object_id = 0, $type_id = 0)
2868{
2869 if ($object_id == 0 or $type_id == 0)
2870 {
2871 showError ('Invalid arguments', __FUNCTION__);
2872 die;
2873 }
f3f0161f 2874 $ret = TRUE;
118e4c38 2875 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2876 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2877 return $ret;
ad0e4754
DO
2878}
2879
6e49bd1f 2880// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2881// generated/deducted later at higher levels.
aab37bc0 2882// Result is a chain: randomly indexed taginfo list.
f9bc186f 2883function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2884{
a6e8d544 2885 $ret = array();
2c21a10c
DO
2886 if (!in_array ($entity_realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2887 return $ret;
edf0993c
DO
2888 $query = "select tt.id, tag from " .
2889 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
120e9ddd 2890 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
edf0993c
DO
2891 "order by tt.tag";
2892 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2893 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2894 $ret[$row['id']] = $row;
a6e8d544 2895 $result->closeCursor();
aab37bc0 2896 return getExplicitTagsOnly ($ret);
5967b83d
DO
2897}
2898
351c0966 2899// Return a tag chain with all DB tags on it.
5967b83d
DO
2900function getTagList ()
2901{
20c901a7 2902 $ret = array();
120e9ddd 2903 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2904 "from TagTree left join TagStorage on id = tag_id " .
120e9ddd 2905 "group by id, entity_realm order by tag";
065eeb52 2906 $result = useSelectBlade ($query, __FUNCTION__);
fb7a4967
DO
2907 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2908 // which is utf8_general_ci for UTF-8.
5967b83d 2909 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2910 {
7cc02fc1 2911 if (!isset ($ret[$row['id']]))
20c901a7 2912 $ret[$row['id']] = array
5b7bd02e
DO
2913 (
2914 'id' => $row['id'],
2915 'tag' => $row['tag'],
fb7a4967 2916 'ci' => $ci++,
5b7bd02e
DO
2917 'parent_id' => $row['parent_id'],
2918 'refcnt' => array()
2919 );
2920 if ($row['realm'])
20c901a7 2921 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2922 }
5967b83d 2923 $result->closeCursor();
20c901a7 2924 return $ret;
5967b83d
DO
2925}
2926
fe7044ad
DO
2927function commitCreateTag ($tagname = '', $parent_id = 0)
2928{
2929 if ($tagname == '' or $parent_id === 0)
2930 return "Invalid args to " . __FUNCTION__;
2931 $result = useInsertBlade
2932 (
2933 'TagTree',
2934 array
2935 (
2936 'tag' => "'${tagname}'",
2937 'parent_id' => $parent_id
2938 )
2939 );
590e1281 2940 global $dbxlink;
fe7044ad
DO
2941 if ($result)
2942 return '';
590e1281
DO
2943 elseif ($dbxlink->errorCode() == 23000)
2944 return "name '${tag_name}' is already used";
fe7044ad
DO
2945 else
2946 return "SQL query failed in " . __FUNCTION__;
2947}
2948
2949function commitDestroyTag ($tagid = 0)
2950{
2951 if ($tagid == 0)
2952 return 'Invalid arg to ' . __FUNCTION__;
f5575f12 2953 if (useDeleteBlade ('TagTree', 'id', $tagid))
fe7044ad
DO
2954 return '';
2955 else
2956 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2957}
f9bc186f 2958
49fb1027 2959function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2960{
49fb1027
DO
2961 if ($parent_id == 0)
2962 $parent_id = 'NULL';
f9bc186f 2963 global $dbxlink;
49fb1027
DO
2964 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2965 "where id = ${tag_id} limit 1";
f9bc186f 2966 $result = $dbxlink->exec ($query);
590e1281
DO
2967 if ($result !== FALSE)
2968 return '';
2969 elseif ($dbxlink->errorCode() == 23000)
2970 return "name '${tag_name}' is already used";
2971 else
49fb1027 2972 return 'SQL query failed in ' . __FUNCTION__;
f9bc186f
DO
2973}
2974
01b6b4d6
DO
2975// Drop the whole chain stored.
2976function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af
DO
2977{
2978 global $dbxlink;
120e9ddd 2979 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
aedf18af
DO
2980 $result = $dbxlink->exec ($query);
2981 if ($result === NULL)
2982 return FALSE;
2983 else
2984 return TRUE;
2985}
2986
01b6b4d6
DO
2987// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2988function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2989{
2990 global $dbxlink;
120e9ddd 2991 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
01b6b4d6
DO
2992 $result = $dbxlink->exec ($query);
2993 if ($result === NULL)
2994 return FALSE;
2995 else
2996 return TRUE;
2997}
2998
351c0966 2999// Push a record into TagStorage unconditionally.
3355ca56 3000function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 3001{
3355ca56
DO
3002 if (empty ($realm))
3003 return FALSE;
eb6ea26f
DO
3004 return useInsertBlade
3005 (
3006 'TagStorage',
3007 array
3008 (
120e9ddd
DO
3009 'entity_realm' => "'${realm}'",
3010 'entity_id' => $entity_id,
eb6ea26f
DO
3011 'tag_id' => $tag_id,
3012 )
3013 );
3014}
3015
351c0966 3016// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
3017// on the implicit list already). Then remove any other records, which
3018// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
3019// that both the tag base is still minimal and all requested tags appear on
3020// the resulting tag chain.
abef7149
DO
3021// Return TRUE, if any changes were committed.
3022function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3023{
3024 // Put the current explicit sub-chain into a buffer and merge all tags from
3025 // the extra chain, which aren't there yet.
3026 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3027 foreach ($extrachain as $extratag)
3028 if (!tagOnChain ($extratag, $newchain))
3029 $newchain[] = $extratag;
3030 // Then minimize the working buffer and check if it differs from the original
3031 // chain we started with. If it is so, save the work and signal the upper layer.
3032 $newchain = getExplicitTagsOnly ($newchain);
3033 if (tagChainCmp ($oldchain, $newchain))
3034 {
01b6b4d6 3035 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
3036 foreach ($newchain as $taginfo)
3037 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3038 return TRUE;
3039 }
3040 return FALSE;
351c0966
DO
3041}
3042
3043// Presume, that the target record has no tags attached.
3044function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3045{
3046 if (!count ($tagidlist))
c63a8d6e
DO
3047 return '';
3048 if (!$last_insert_id)
3049 $last_insert_id = lastInsertID();
3050 $errcount = 0;
abef7149 3051 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 3052 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
3053 $errcount++;
3054 if (!$errcount)
3055 return '';
3056 else
3057 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3058}
3059
42023f03
DO
3060function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3061{
3062 // $range is in x.x.x.x/x format, split into ip/mask vars
3063 $rangeArray = explode('/', $range);
3064 if (count ($rangeArray) != 2)
3065 return "Invalid IPv4 prefix '${range}'";
3066 $ip = $rangeArray[0];
3067 $mask = $rangeArray[1];
3068
3069 if (empty ($ip) or empty ($mask))
3070 return "Invalid IPv4 prefix '${range}'";
3071 $ipL = ip2long($ip);
3072 $maskL = ip2long($mask);
3073 if ($ipL == -1 || $ipL === FALSE)
3074 return 'Bad IPv4 address';
3075 if ($mask < 32 && $mask > 0)
3076 $maskL = $mask;
3077 else
3078 {
3079 $maskB = decbin($maskL);
3080 if (strlen($maskB)!=32)
3081 return 'Invalid netmask';
3082 $ones=0;
3083 $zeroes=FALSE;
3084 foreach( str_split ($maskB) as $digit)
3085 {
3086 if ($digit == '0')
3087 $zeroes = TRUE;
3088 if ($digit == '1')
3089 {
3090 $ones++;
3091 if ($zeroes == TRUE)
3092 return 'Invalid netmask';
3093 }
3094 }
3095 $maskL = $ones;
3096 }
3097 $binmask = binMaskFromDec($maskL);
3098 $ipL = $ipL & $binmask;
42023f03
DO
3099 $result = useInsertBlade
3100 (
706ce117 3101 'IPv4Network',
42023f03
DO
3102 array
3103 (
3104 'ip' => sprintf ('%u', $ipL),
3105 'mask' => "'${maskL}'",
3106 'name' => "'${name}'"
3107 )
3108 );
e782fca4
DO
3109 if ($result != TRUE)
3110 return "Could not add ${range} (already exists?).";
42023f03
DO
3111
3112 if ($is_bcast and $maskL < 31)
3113 {
3114 $network_addr = long2ip ($ipL);
3115 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3116 updateAddress ($network_addr, 'network', 'yes');
3117 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3118 }
351c0966 3119 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
3120}
3121
706ce117 3122// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
3123function destroyIPv4Prefix ($id = 0)
3124{
3125 if ($id <= 0)
3126 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
706ce117 3127 if (!useDeleteBlade ('IPv4Network', 'id', $id))
42023f03 3128 return __FUNCTION__ . ': SQL query #1 failed';
01b6b4d6 3129 if (!destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
3130 return __FUNCTION__ . ': SQL query #2 failed';
3131 return '';
3132}
3133
ebae41b3
DO
3134function loadScript ($name)
3135{
3136 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3137 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
3138 if ($row !== FALSE)
3139 return $row[0];
3140 else
3141 return NULL;
ebae41b3
DO
3142}
3143
3144function saveScript ($name, $text)
3145{
3146 if (empty ($name))
3147 {
3148 showError ('Invalid argument');
3149 return FALSE;
3150 }
4a6a28f1 3151 // delete regardless of existence
f5575f12 3152 useDeleteBlade ('Script', 'script_name', "'${name}'");
4a6a28f1 3153 return useInsertBlade
ebae41b3
DO
3154 (
3155 'Script',
3156 array
3157 (
3158 'script_name' => "'${name}'",
3159 'script_text' => "'${text}'"
3160 )
3161 );
3162}
3163
d983f70a
DO
3164function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3165{
3166 if (NULL === getIPv4AddressNetworkId ($localip))
3167 return "$localip: Non existant ip";
3168 if (NULL === getIPv4AddressNetworkId ($localip))
3169 return "$remoteip: Non existant ip";
3170 if ( ($localport <= 0) or ($localport >= 65536) )
3171 return "$localport: invaild port";
3172 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3173 return "$remoteport: invaild port";
3174
3175 $result = useInsertBlade
3176 (
706ce117 3177 'IPv4NAT',
d983f70a
DO
3178 array
3179 (
3180 'object_id' => $object_id,
3181 'localip' => "INET_ATON('${localip}')",
3182 'remoteip' => "INET_ATON('$remoteip')",
3183 'localport' => $localport,
3184 'remoteport' => $remoteport,
3185 'proto' => "'${proto}'",
3186 'description' => "'${description}'",
3187 )
3188 );
3189 if ($result)
3190 return '';
3191 else
3192 return __FUNCTION__ . ': Failed to insert the rule.';
3193}
3194
3195function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3196{
3197 global $dbxlink;
3198
3199 $query =
706ce117 3200 "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
3201 $result = $dbxlink->exec ($query);
3202 return '';
3203}
3204
3205function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3206{
3207 global $dbxlink;
3208
3209 $query =
706ce117 3210 "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
3211 $result = $dbxlink->exec ($query);
3212 return '';
3213}
3214
3215function getNATv4ForObject ($object_id)
3216{
3217 $ret = array();
3218 $ret['out'] = array();
3219 $ret['in'] = array();
3220 $query =
3221 "select ".
3222 "proto, ".
3223 "INET_NTOA(localip) as localip, ".
3224 "localport, ".
3225 "INET_NTOA(remoteip) as remoteip, ".
3226 "remoteport, ".
3227 "ipa1.name as local_addr_name, " .
3228 "ipa2.name as remote_addr_name, " .
3229 "description ".
706ce117
DO
3230 "from IPv4NAT ".
3231 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3232 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
d983f70a
DO
3233 "where object_id='$object_id' ".
3234 "order by localip, localport, proto, remoteip, remoteport";
3235 $result = useSelectBlade ($query, __FUNCTION__);
3236 $count=0;
3237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3238 {
3239 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3240 $ret['out'][$count][$cname] = $row[$cname];
3241 $count++;
3242 }
3243 $result->closeCursor();
3244 unset ($result);
3245
3246 $query =
3247 "select ".
3248 "proto, ".
3249 "INET_NTOA(localip) as localip, ".
3250 "localport, ".
3251 "INET_NTOA(remoteip) as remoteip, ".
3252 "remoteport, ".
706ce117 3253 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
3254 "RackObject.name as object_name, ".
3255 "description ".
706ce117
DO
3256 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3257 "where IPv4Allocation.object_id='$object_id' ".
d983f70a
DO
3258 "order by remoteip, remoteport, proto, localip, localport";
3259 $result = useSelectBlade ($query, __FUNCTION__);
3260 $count=0;
3261 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3262 {
3263 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3264 $ret['in'][$count][$cname] = $row[$cname];
3265 $count++;
3266 }
3267 $result->closeCursor();
3268
3269 return $ret;
3270}
3271
3272// This function performs search and then calculates score for each result.
3273// Given previous search results in $objects argument, it adds new results
3274// to the array and updates score for existing results, if it is greater than
3275// existing score.
3276function mergeSearchResults (&$objects, $terms, $fieldname)
3277{
3278 global $dbxlink;
3279 $query =
b89ba713 3280 "select ro.name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
d983f70a 3281 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
10bac82a 3282 "on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id where Chapter.name = 'RackObjectType' and ";
d983f70a
DO
3283 $count = 0;
3284 foreach (explode (' ', $terms) as $term)
3285 {
3286 if ($count) $query .= ' or ';
b89ba713 3287 $query .= "ro.${fieldname} like '%$term%'";
d983f70a
DO
3288 $count++;
3289 }
3290 $query .= " order by ${fieldname}";
3291 $result = useSelectBlade ($query, __FUNCTION__);
d983f70a
DO
3292 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3293 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3294 {
3295 foreach ($clist as $cname)
3296 $object[$cname] = $row[$cname];
3297 $object['score'] = 0;
3298 $object['dname'] = displayedName ($object);
3299 unset ($object['objtype_id']);
3300 foreach (explode (' ', $terms) as $term)
3301 if (strstr ($object['name'], $term))
3302 $object['score'] += 1;
3303 unset ($object['name']);
3304 if (!isset ($objects[$row['id']]))
3305 $objects[$row['id']] = $object;
3306 elseif ($objects[$row['id']]['score'] < $object['score'])
3307 $objects[$row['id']]['score'] = $object['score'];
3308 }
3309 return $objects;
3310}
3311
09620506
DO
3312function getLostIPv4Addresses ()
3313{
f7414fa5 3314 dragon();
09620506
DO
3315}
3316
121496b6
DO
3317// Return a list of files which are not linked to the specified record. This list
3318// will be used by printSelect().
e1ae3fb4
AD
3319function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3320{
3321 if ($entity_type == NULL || $entity_id == 0)
3322 {
3323 showError ('Invalid parameters', __FUNCTION__);
3324 return NULL;
3325 }
3326 global $dbxlink;
3327 $sql =
121496b6 3328 'SELECT id, name FROM File ' .
e1ae3fb4 3329 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
121496b6 3330 'ORDER BY name, id';
e1ae3fb4
AD
3331 $query = $dbxlink->prepare($sql);
3332 $query->bindParam(1, $entity_type);
3333 $query->bindParam(2, $entity_id);
3334 $query->execute();
3335 $ret=array();
e1ae3fb4 3336 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3337 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3338 return $ret;
3339}
3340
6df2025d
DO
3341// FIXME: return a standard cell list, so upper layer can iterate over
3342// it conveniently.
e1ae3fb4
AD
3343function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3344{
3345 if ($entity_type == NULL || $entity_id == 0)
3346 {
3347 showError ('Invalid parameters', __FUNCTION__);
3348 return NULL;
3349 }
3350 global $dbxlink;
3351 $sql =
3352 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3353 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3354 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3355 $query = $dbxlink->prepare($sql);
3356 $query->bindParam(1, $entity_type);
3357 $query->bindParam(2, $entity_id);
3358 $query->execute();
3359 $ret = array();
3360 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3361 $ret[$row['file_id']] = array (
b3567368 3362 'id' => $row['file_id'],
e1ae3fb4
AD
3363 'link_id' => $row['link_id'],
3364 'name' => $row['name'],
3365 'type' => $row['type'],
3366 'size' => $row['size'],
3367 'ctime' => $row['ctime'],
3368 'mtime' => $row['mtime'],
3369 'atime' => $row['atime'],
3370 'comment' => $row['comment'],
3371 );
3372 return $ret;
3373}
3374
3375function getFile ($file_id = 0)
3376{
3377 if ($file_id == 0)
3378 {
3379 showError ('Invalid file_id', __FUNCTION__);
3380 return NULL;
3381 }
3382 global $dbxlink;
3383 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3384 $query->bindParam(1, $file_id);
3385 $query->execute();
3386 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3387 {
3388 showError ('Query succeeded, but returned no data', __FUNCTION__);
3389 $ret = NULL;
3390 }
3391 else
3392 {
3393 $ret = array();
3394 $ret['id'] = $row['id'];
3395 $ret['name'] = $row['name'];
3396 $ret['type'] = $row['type'];
3397 $ret['size'] = $row['size'];
3398 $ret['ctime'] = $row['ctime'];
3399 $ret['mtime'] = $row['mtime'];
3400 $ret['atime'] = $row['atime'];
3401 $ret['contents'] = $row['contents'];
3402 $ret['comment'] = $row['comment'];
bed9cd76 3403 $query->closeCursor();
e1ae3fb4 3404
deb3da1b 3405 // Someone accessed this file, update atime
e1ae3fb4
AD
3406 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3407 $q_atime->bindParam(1, date('YmdHis'));
3408 $q_atime->bindParam(2, $file_id);
3409 $q_atime->execute();
3410 }
e1ae3fb4
AD
3411 return $ret;
3412}
3413
3414function getFileInfo ($file_id = 0)
3415{
3416 if ($file_id == 0)
3417 {
3418 showError ('Invalid file_id', __FUNCTION__);
3419 return NULL;
3420 }
3421 global $dbxlink;
3422 $query = $dbxlink->prepare('SELECT id, name, type, size, ctime, mtime, atime, comment FROM File WHERE id = ?');
3423 $query->bindParam(1, $file_id);
3424 $query->execute();
3425 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3426 {
3427 showError ('Query succeeded, but returned no data', __FUNCTION__);
3428 $ret = NULL;
3429 }
3430 else
3431 {
3432 $ret = array();
3433 $ret['id'] = $row['id'];
3434 $ret['name'] = $row['name'];
3435 $ret['type'] = $row['type'];
3436 $ret['size'] = $row['size'];
3437 $ret['ctime'] = $row['ctime'];
3438 $ret['mtime'] = $row['mtime'];
3439 $ret['atime'] = $row['atime'];
3440 $ret['comment'] = $row['comment'];
da3302ab 3441 $query->closeCursor();
e1ae3fb4 3442 }
e1ae3fb4
AD
3443 return $ret;
3444}
3445
3446function getFileLinks ($file_id = 0)
3447{
3448 if ($file_id <= 0)
3449 {
3450 showError ('Invalid file_id', __FUNCTION__);
3451 return NULL;
3452 }
3453
3454 global $dbxlink;
8bc5d1e4 3455 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ? ORDER BY entity_type, entity_id');
e1ae3fb4
AD
3456 $query->bindParam(1, $file_id);
3457 $query->execute();
da3302ab 3458 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3459 $ret = array();
da3302ab 3460 foreach ($rows as $row)
e1ae3fb4
AD
3461 {
3462 // get info of the parent
3463 switch ($row['entity_type'])
3464 {
3465 case 'ipv4net':
3466 $page = 'ipv4net';
3467 $id_name = 'id';
d724d290 3468 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3469 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3470 break;
3471 case 'ipv4rspool':
3854af78 3472 $page = 'ipv4rspool';
e1ae3fb4 3473 $id_name = 'pool_id';
a6e91ac2 3474 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3475 $name = $parent['name'];
3476 break;
3477 case 'ipv4vs':
3478 $page = 'ipv4vs';
3479 $id_name = 'vs_id';
7c38462f 3480 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3481 $name = $parent['name'];
3482 break;
3483 case 'object':
3484 $page = 'object';
3485 $id_name = 'object_id';
3486 $parent = getObjectInfo($row['entity_id']);
7ddbcf59 3487 $name = $parent['dname'];
e1ae3fb4
AD
3488 break;
3489 case 'rack':
3490 $page = 'rack';
3491 $id_name = 'rack_id';
61a1d996 3492 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
e1ae3fb4
AD
3493 $name = $parent['name'];
3494 break;
3495 case 'user':
3496 $page = 'user';
3497 $id_name = 'user_id';
b82cce3f
DO
3498 $userinfo = getUserInfo ($row['entity_id']);
3499 $name = $userinfo['user_name'];
e1ae3fb4
AD
3500 break;
3501 }
3502
17d95c32
AD
3503 // name needs to have some value for hrefs to work
3504 if (empty($name))
3505 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3506
e1ae3fb4
AD
3507 $ret[$row['id']] = array(
3508 'page' => $page,
3509 'id_name' => $id_name,
3510 'entity_type' => $row['entity_type'],
3511 'entity_id' => $row['entity_id'],
3512 'name' => $name
3513 );
3514 }
3515 return $ret;
3516}
3517
3518// Return list of possible file parents along with the number of children.
3519// Used on main Files listing page.
3520function getFileLinkInfo ()
3521{
3522 global $dbxlink;
3523 $query = 'SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type';
3524
3525 $result = useSelectBlade ($query, __FUNCTION__);
3526 $ret = array();
3527 $ret[0] = array ('entity_type' => 'all', 'name' => 'ALL files');
3528 $clist = array ('entity_type', 'name', 'count');
3529 $total = 0;
3530 $i=2;
3531 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3532 if ($row['count'] > 0)
3533 {
3534 $total += $row['count'];
3535 $row['name'] = formatEntityName ($row['entity_type']);
3536 foreach ($clist as $cname)
3537 $ret[$i][$cname] = $row[$cname];
3538 $i++;
3539 }
3540 $result->closeCursor();
3541
3542 // Find number of files without any linkage
3543 $linkless_sql =
3544 'SELECT COUNT(*) ' .
3545 'FROM File ' .
3546 'WHERE id NOT IN (SELECT file_id FROM FileLink)';
3547 $q_linkless = useSelectBlade ($linkless_sql, __FUNCTION__);
3548 $ret[1] = array ('entity_type' => 'no_links', 'name' => 'Files w/no links', 'count' => $q_linkless->fetchColumn ());
3549 $q_linkless->closeCursor();
3550
3551 // Find total number of files
3552 $total_sql = 'SELECT COUNT(*) FROM File';
3553 $q_total = useSelectBlade ($total_sql, __FUNCTION__);
3554 $ret[0]['count'] = $q_total->fetchColumn ();
3555 $q_total->closeCursor();
3556
3557 ksort($ret);
3558 return $ret;
3559}
3560
3561function commitAddFile ($name, $type, $size, $contents, $comment)
3562{
3563 $now = date('YmdHis');
3564
3565 global $dbxlink;
3566 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3567 $query->bindParam(1, $name);
3568 $query->bindParam(2, $type);
3569 $query->bindParam(3, $size);
3570 $query->bindParam(4, $now);
3571 $query->bindParam(5, $now);
3572 $query->bindParam(6, $now);
3573 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3574 $query->bindParam(8, $comment);
3575
3576 $result = $query->execute();
3577
3578
3579 if ($result)
3580 return '';
590e1281 3581 elseif ($query->errorCode() == 23000)
13edfa1c 3582 return "commitAddFile: File named '${name}' already exists";
e1ae3fb4
AD
3583 else
3584 return 'commitAddFile: SQL query failed';
3585}
3586
4a2c6c6b 3587function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4
AD
3588{
3589 global $dbxlink;
3590 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3591 $query->bindParam(1, $file_id);
4a2c6c6b
AD
3592 $query->bindParam(2, $entity_type);
3593 $query->bindParam(3, $entity_id);
e1ae3fb4
AD
3594
3595 $result = $query->execute();
3596
3597 if ($result)
3598 return '';
3599 else
3600 return 'commitLinkFile: SQL query failed';
3601}
3602
f8874cdb 3603function commitReplaceFile ($file_id = 0, $contents)
fd1fb420
AD
3604{
3605 if ($file_id == 0)
3606 {
3607 showError ('Not all required args are present.', __FUNCTION__);
3608 return FALSE;
3609 }
fd1fb420
AD
3610
3611 global $dbxlink;
f8874cdb
DO
3612 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3613 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3614 $query->bindParam(2, $file_id);
fd1fb420
AD
3615
3616 $result = $query->execute();
3617 if (!$result)
3618 {
3619 showError ('commitReplaceFile: SQL query failed', __FUNCTION__);
3620 return FALSE;
3621 }
3622 return '';
3623}
3624
9db67d95 3625function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
e1ae3fb4 3626{
9db67d95 3627 if ($file_id <= 0 or empty ($new_name) or empty ($new_type))
e1ae3fb4
AD
3628 {
3629 showError ('Not all required args are present.', __FUNCTION__);
3630 return FALSE;
3631 }
3632 global $dbxlink;
9db67d95 3633 $query = $dbxlink->prepare('UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?');
6ee41bd4 3634 $query->bindParam(1, $new_name);
9db67d95
DO
3635 $query->bindParam(2, $new_type);
3636 $query->bindParam(3, $new_comment);
3637 $query->bindParam(4, $file_id);
e1ae3fb4
AD
3638
3639 $result = $query->execute();
3640 if (!$result)
6ee41bd4 3641 return 'SQL query failed in ' . __FUNCTION__;
e1ae3fb4
AD
3642 return '';
3643}
3644
3645function commitUnlinkFile ($link_id)
3646{
3647 if (useDeleteBlade ('FileLink', 'id', $link_id) != TRUE)
3648 return __FUNCTION__ . ': useDeleteBlade() failed';
3649 return '';
3650}
3651