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