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