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