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