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