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