r2121 - make getObjectIPv4Allocations() result indexed by IP address
[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
DO
367 $last_insert_id = lastInsertID();
368 return (addTagsForLastRecord ('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...
c63a8d6e
DO
397 $error = addTagsForLastRecord ('object', $taglist, $last_insert_id);
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
0ab782bc
DO
897function getObjectIPv4Allocations ($object_id = 0)
898{
899 $ret = array();
900 $query = 'select name as osif, type, inet_ntoa(ip) as dottedquad from IPBonds ' .
901 "where object_id = ${object_id} " .
902 'order by ip';
903 $result = useSelectBlade ($query, __FUNCTION__);
85970da2 904 // don't spawn a sub-query with unfetched buffer, it may fail
0ab782bc 905 while ($row = $result->fetch (PDO::FETCH_ASSOC))
85970da2
DO
906 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
907 unset ($result);
908 foreach (array_keys ($ret) as $dottedquad)
909 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
0ab782bc
DO
910 return $ret;
911}
912
6ef9683b
DO
913// Return a list of IPv4 allocations for the object. Each address will list
914// all other objects, to which it is allocated (except the current object).
e673ee24
DO
915function getObjectAddresses ($object_id = 0)
916{
917 if ($object_id == 0)
918 {
f41b492f 919 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
920 return;
921 }
e673ee24
DO
922 $query =
923 "select ".
924 "IPAddress.name as IPAddress_name, ".
925 "IPAddress.reserved as IPAddress_reserved, ".
926 "IPBonds.name as IPBonds_name, ".
927 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
928 "IPBonds.type as IPBonds_type, ".
929 "RemoteBonds.name as RemoteBonds_name, ".
930 "RemoteBonds.type as RemoteBonds_type, ".
6ef9683b
DO
931 "RemoteBonds.object_id as RemoteBonds_object_id ".
932 "from IPBonds " .
e673ee24
DO
933 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
934 "and IPBonds.object_id!=RemoteBonds.object_id " .
935 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
e673ee24
DO
936 "where ".
937 "IPBonds.object_id = ${object_id} ".
6ef9683b 938 "order by IPBonds.ip, RemoteBonds.object_id";
065eeb52 939 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
940 $ret=array();
941 $count=0;
942 $refcount=0;
943 $prev_ip = 0;
6ef9683b 944 // Free the DB connection to enable subqueries.
e425f895
DO
945 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
946 $result->closeCursor();
947 foreach ($rows as $row)
e673ee24 948 {
e425f895 949 if ($prev_ip != $row['IPBonds_ip'])
e673ee24 950 {
e425f895
DO
951 $count++;
952 $refcount=0;
953 $prev_ip = $row['IPBonds_ip'];
954 $ret[$count]['address_name'] = $row['IPAddress_name'];
955 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
956 $ret[$count]['ip'] = $row['IPBonds_ip'];
957 $ret[$count]['name'] = $row['IPBonds_name'];
958 $ret[$count]['type'] = $row['IPBonds_type'];
959 $ret[$count]['references'] = array();
960 }
e673ee24 961
e425f895
DO
962 if ($row['RemoteBonds_type'])
963 {
964 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
965 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
966 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
967 if (empty ($row['RemoteBonds_object_id']))
6ef9683b 968 $ret[$count]['references'][$refcount]['object_name'] = '';
e425f895 969 else
e673ee24 970 {
e425f895
DO
971 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
972 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
e673ee24 973 }
e425f895 974 $refcount++;
e673ee24
DO
975 }
976 }
e673ee24
DO
977 return $ret;
978}
979
e6ca609a
DO
980// Return minimal IPv4 address, optionally with "ip" key set, if requested.
981function constructIPv4Address ($dottedquad = NULL)
a910829d 982{
e6ca609a 983 $ret = array
a910829d
DO
984 (
985 'name' => '',
986 'reserved' => 'no',
a910829d
DO
987 'outpf' => array(),
988 'inpf' => array(),
a910829d 989 'rslist' => array(),
2d318652 990 'allocs' => array(),
a910829d
DO
991 'lblist' => array()
992 );
e6ca609a
DO
993 if ($dottedquad != NULL)
994 $ret['ip'] = $dottedquad;
995 return $ret;
996}
997
998// Check the range requested for meaningful IPv4 records, build them
999// into a list and return. Return an empty list if nothing matched.
1000// Both arguments are expected in signed int32 form. The resulting list
1001// is keyed by uint32 form of each IP address, items aren't sorted.
1002function scanIPv4Space ($i32_first, $i32_last)
1003{
1004 $ret = array();
a910829d
DO
1005 $dnamechache = array();
1006
2d318652
DO
1007 $db_first = sprintf ('%u', 0x00000000 + $i32_first);
1008 $db_last = sprintf ('%u', 0x00000000 + $i32_last);
a910829d 1009 // 1. collect labels and reservations
2d318652
DO
1010 $query = "select INET_NTOA(ip) as ip, name, reserved from IPAddress ".
1011 "where ip between ${db_first} and ${db_last} and (reserved = 'yes' or name != '')";
a910829d
DO
1012 $result = useSelectBlade ($query, __FUNCTION__);
1013 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1014 {
2d318652
DO
1015 $ip_bin = ip2long ($row['ip']);
1016 if (!isset ($ret[$ip_bin]))
e6ca609a 1017 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
2d318652
DO
1018 $ret[$ip_bin]['name'] = $row['name'];
1019 $ret[$ip_bin]['reserved'] = $row['reserved'];
a910829d
DO
1020 }
1021 unset ($result);
1022
1023 // 2. check for allocations
1024 $query =
2d318652 1025 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
a910829d
DO
1026 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
1027 "dict_value as objtype_name from " .
1028 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
1029 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
1030 "where ip between ${db_first} and ${db_last} " .
1031 "and chapter_name = 'RackObjectType'" .
1032 "order by ipb.type, object_name";
1033 $result = useSelectBlade ($query, __FUNCTION__);
1034 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1035 {
2d318652
DO
1036 $ip_bin = ip2long ($row['ip']);
1037 if (!isset ($ret[$ip_bin]))
e6ca609a 1038 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1039 if (!isset ($dnamecache[$row['object_id']]))
1040 {
1041 $quasiobject['name'] = $row['object_name'];
1042 $quasiobject['objtype_id'] = $row['objtype_id'];
1043 $quasiobject['objtype_name'] = $row['objtype_name'];
1044 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1045 }
1046 $tmp = array();
1047 foreach (array ('object_id', 'type', 'name') as $cname)
1048 $tmp[$cname] = $row[$cname];
1049 $tmp['object_name'] = $dnamecache[$row['object_id']];
2d318652 1050 $ret[$ip_bin]['allocs'][] = $tmp;
a910829d
DO
1051 }
1052 unset ($result);
1053
1054 // 3. look for virtual services and related LB
2d318652 1055 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
a910829d
DO
1056 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
1057 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
1058 "inner join RackObject as ro on lb.object_id = ro.id " .
1059 "left join Dictionary on objtype_id=dict_key " .
1060 "natural join Chapter " .
1061 "where vip between ${db_first} and ${db_last} " .
1062 "and chapter_name = 'RackObjectType'" .
1063 "order by vport, proto, ro.name, object_id";
1064 $result = useSelectBlade ($query, __FUNCTION__);
1065 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1066 {
2d318652 1067 $ip_bin = ip2long ($row['ip']);
e6ca609a 1068 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1069 if (!isset ($dnamecache[$row['object_id']]))
1070 {
1071 $quasiobject['name'] = $row['object_name'];
1072 $quasiobject['objtype_id'] = $row['objtype_id'];
1073 $quasiobject['objtype_name'] = $row['objtype_name'];
1074 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1075 }
1076 $tmp = array();
2d318652 1077 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
a910829d
DO
1078 $tmp[$cname] = $row[$cname];
1079 $tmp['object_name'] = $dnamecache[$row['object_id']];
2d318652
DO
1080 $tmp['vip'] = $row['ip'];
1081 $ret[$ip_bin]['lblist'][] = $tmp;
a910829d
DO
1082 }
1083 unset ($result);
1084
1085 // 4. don't forget about real servers along with pools
2d318652 1086 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
a910829d
DO
1087 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
1088 "where rsip between ${db_first} and ${db_last} " .
1089 "order by ip, rsport, rspool_id";
1090 $result = useSelectBlade ($query, __FUNCTION__);
1091 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1092 {
2d318652
DO
1093 $ip_bin = ip2long ($row['ip']);
1094 if (!isset ($ret[$ip_bin]))
e6ca609a 1095 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1096 $tmp = array();
1097 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1098 $tmp[$cname] = $row[$cname];
2d318652 1099 $ret[$ip_bin]['rslist'][] = $tmp;
a910829d
DO
1100 }
1101 unset ($result);
1102
1103 // 5. add NAT rules, part 1
1104 $query =
1105 "select " .
1106 "proto, " .
1107 "INET_NTOA(localip) as localip, " .
1108 "localport, " .
1109 "INET_NTOA(remoteip) as remoteip, " .
1110 "remoteport, " .
1111 "description " .
1112 "from PortForwarding " .
1113 "where remoteip between ${db_first} and ${db_last} or " .
1114 "localip between ${db_first} and ${db_last} " .
1115 "order by localip, localport, remoteip, remoteport, proto";
1116 $result = useSelectBlade ($query, __FUNCTION__);
1117 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1118 {
2d318652
DO
1119 $remoteip_bin = ip2long ($row['remoteip']);
1120 $localip_bin = ip2long ($row['localip']);
1121 if ($i32_first <= $remoteip_bin and $remoteip_bin <= $i32_last)
1122 {
1123 if (!isset ($ret[$remoteip_bin]))
e6ca609a 1124 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
2d318652
DO
1125 $ret[$remoteip_bin]['inpf'][] = $row;
1126 }
1127 if ($i32_first <= $localip_bin and $localip_bin <= $i32_last)
1128 {
1129 if (!isset ($ret[$localip_bin]))
e6ca609a 1130 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
2d318652
DO
1131 $ret[$localip_bin]['outpf'][] = $row;
1132 }
a910829d
DO
1133 }
1134 return $ret;
1135}
1136
1137// Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
2d318652 1138function getIPv4NetworkInfo ($id = 0)
a910829d
DO
1139{
1140 if ($id <= 0)
1141 {
1142 showError ('Invalid arg', __FUNCTION__);
1143 return NULL;
1144 }
2d318652 1145 $query = "select INET_NTOA(ip) as ip, mask, name ".
a910829d
DO
1146 "from IPRanges where id = $id";
1147 $result = useSelectBlade ($query, __FUNCTION__);
1148 $ret = $result->fetch (PDO::FETCH_ASSOC);
1149 if ($ret == NULL)
1150 return NULL;
1151 unset ($result);
1152 $ret['id'] = $id;
2d318652 1153 $ret['ip_bin'] = ip2long ($ret['ip']);
a910829d
DO
1154 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1155 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1156 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
1157 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
1158 return $ret;
1159}
1160
2d318652 1161function getIPv4Network ($id = 0)
a910829d 1162{
2d318652 1163 $ret = getIPv4NetworkInfo ($id);
a910829d
DO
1164 if (!$ret)
1165 {
1166 showError ('Record not found', __FUNCTION__);
1167 return NULL;
1168 }
1169 $ret['addrlist'] = scanIPv4Space ($ret['db_first'], $ret['db_last']);
2d318652
DO
1170 markupIPv4AddrList ($ret['addrlist']);
1171 return $ret;
1172}
1173
1174function getIPv4Address ($dottedquad = '')
1175{
1176 if ($dottedquad == '')
1177 {
1178 showError ('Invalid arg', __FUNCTION__);
1179 return NULL;
1180 }
1181 $i32 = ip2long ($dottedquad); // signed 32 bit
1182 $scanres = scanIPv4Space ($i32, $i32);
1183 if (!isset ($scanres[$i32]))
e6ca609a 1184 return constructIPv4Address ($dottedquad);
2d318652
DO
1185 markupIPv4AddrList ($scanres);
1186 return $scanres[$i32];
a910829d
DO
1187}
1188
5222f192
DO
1189function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1190{
1191 $result = useInsertBlade
1192 (
1193 'IPBonds',
1194 array
1195 (
1196 'ip' => "INET_ATON('$ip')",
1197 'object_id' => "'${object_id}'",
1198 'name' => "'${name}'",
1199 'type' => "'${type}'"
1200 )
1201 );
1202 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
1203}
1204
11c8e4be 1205function getAddressspaceList ($tagfilter = array(), $tfmode = 'any')
e673ee24 1206{
81736ac1 1207 $whereclause = getWhereClause ($tagfilter);
e673ee24 1208 $query =
0b4c0f17 1209 "select distinct ".
e673ee24
DO
1210 "id as IPRanges_id, ".
1211 "INET_NTOA(ip) as IPRanges_ip, ".
1212 "mask as IPRanges_mask, ".
1213 "name as IPRanges_name ".
74ccacff 1214 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
489a7502 1215 "where true ${whereclause} " .
74ccacff 1216 " order by ip";
065eeb52 1217 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
1218 $ret=array();
1219 $count=0;
1220 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 1221 {
e425f895
DO
1222 $ret[$count]['id'] = $row['IPRanges_id'];
1223 $ret[$count]['ip'] = $row['IPRanges_ip'];
1224 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
1225 $ret[$count]['name'] = $row['IPRanges_name'];
1226 $ret[$count]['mask'] = $row['IPRanges_mask'];
1227 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
1228 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
1229 $count++;
e673ee24
DO
1230 }
1231 $result->closeCursor();
1232 return $ret;
1233
1234}
1235
bb0a44e9
DO
1236// Return the id of the smallest IPv4 network containing the given IPv4 address
1237// or NULL, if nothing was found.
1238function getIPv4AddressNetworkId ($dottedquad)
e673ee24 1239{
bb0a44e9
DO
1240 $query = 'select id from IPRanges where ' .
1241 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1242 'order by mask desc limit 1';
065eeb52 1243 $result = useSelectBlade ($query, __FUNCTION__);
bb0a44e9
DO
1244 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1245 return $row['id'];
e673ee24
DO
1246 return NULL;
1247}
1248
1249function updateRange ($id=0, $name='')
1250{
1251 global $dbxlink;
1252 $query =
1253 "update IPRanges set name='$name' where id='$id'";
1254 $result = $dbxlink->exec ($query);
1255 return '';
e673ee24
DO
1256}
1257
1258// This function is actually used not only to update, but also to create records,
1259// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1260// (MySQL 4.0 workaround).
b4c1ef87 1261function updateAddress ($ip = 0, $name = '', $reserved = 'no')
e673ee24
DO
1262{
1263 // DELETE may safely fail.
1264 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1265 // INSERT may appear not necessary.
1266 if ($name == '' and $reserved == 'no')
1267 return '';
1268 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1269 return '';
1270 else
b4c1ef87 1271 return __FUNCTION__ . '(): useInsertBlade() failed';
e673ee24
DO
1272}
1273
e673ee24
DO
1274function updateBond ($ip='', $object_id=0, $name='', $type='')
1275{
1276 global $dbxlink;
1277
1278 $query =
1279 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1280 $result = $dbxlink->exec ($query);
1281 return '';
1282}
1283
1284function unbindIpFromObject ($ip='', $object_id=0)
1285{
1286 global $dbxlink;
1287
1288 $query =
1289 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1290 $result = $dbxlink->exec ($query);
1291 return '';
1292}
1293
1294// This function returns either all or one user account. Array key is user name.
11c8e4be 1295function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
e673ee24 1296{
81736ac1 1297 $whereclause = getWhereClause ($tagfilter);
e673ee24
DO
1298 $query =
1299 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
ebae41b3
DO
1300 'from UserAccount left join TagStorage ' .
1301 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1302 "where true ${whereclause} " .
1303 'order by user_name';
065eeb52 1304 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1305 $ret = array();
1306 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1307 while ($row = $result->fetch (PDO::FETCH_ASSOC))
64b95774 1308 foreach ($clist as $cname)
e673ee24
DO
1309 $ret[$row['user_name']][$cname] = $row[$cname];
1310 $result->closeCursor();
1311 return $ret;
1312}
1313
e673ee24
DO
1314function searchByl2address ($l2addr)
1315{
e673ee24
DO
1316 $l2addr = l2addressForDatabase ($l2addr);
1317 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1318 "where l2address = ${l2addr}";
065eeb52 1319 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1320 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1321 $result->closeCursor();
1322 if (count ($rows) == 0) // No results.
1323 return NULL;
1324 if (count ($rows) == 1) // Target found.
1325 return $rows[0];
f41b492f 1326 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
e673ee24
DO
1327 return NULL;
1328}
1329
ea5fc465
DO
1330function getIPv4PrefixSearchResult ($terms)
1331{
1332 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1333 $or = '';
1334 foreach (explode (' ', $terms) as $term)
1335 {
1336 $query .= $or . "name like '%${term}%'";
1337 $or = ' or ';
1338 }
065eeb52 1339 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1340 $ret = array();
1341 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1342 $ret[] = $row;
1343 return $ret;
1344}
1345
1346function getIPv4AddressSearchResult ($terms)
1347{
1348 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1349 $or = '';
1350 foreach (explode (' ', $terms) as $term)
1351 {
1352 $query .= $or . "name like '%${term}%'";
1353 $or = ' or ';
1354 }
065eeb52 1355 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1356 $ret = array();
1357 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1358 $ret[] = $row;
1359 return $ret;
1360}
1361
05411ccd
DO
1362function getIPv4RSPoolSearchResult ($terms)
1363{
1364 $query = "select id as pool_id, name from IPRSPool where ";
1365 $or = '';
1366 foreach (explode (' ', $terms) as $term)
1367 {
1368 $query .= $or . "name like '%${term}%'";
1369 $or = ' or ';
1370 }
065eeb52 1371 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1372 $ret = array();
1373 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1374 $ret[] = $row;
1375 return $ret;
1376}
1377
1378function getIPv4VServiceSearchResult ($terms)
1379{
1380 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1381 $or = '';
1382 foreach (explode (' ', $terms) as $term)
1383 {
1384 $query .= $or . "name like '%${term}%'";
1385 $or = ' or ';
1386 }
065eeb52 1387 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1388 $ret = array();
1389 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1390 $ret[] = $row;
1391 return $ret;
1392}
1393
6a88e734
DO
1394function getAccountSearchResult ($terms)
1395{
1396 return getSearchResultByField
1397 (
1398 'UserAccount',
1399 array ('user_id', 'user_name', 'user_realname'),
1400 'user_name',
1401 $terms,
1402 'user_name'
1403 );
1404}
1405
1406function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1407{
1408 $pfx = '';
1409 $query = 'select ';
1410 foreach ($rcolumns as $col)
1411 {
1412 $query .= $pfx . $col;
1413 $pfx = ', ';
1414 }
1415 $pfx = '';
1416 $query .= " from ${tname} where ";
1417 foreach (explode (' ', $terms) as $term)
1418 {
1419 $query .= $pfx . "${scolumn} like '%${term}%'";
1420 $pfx = ' or ';
1421 }
1422 if ($ocolumn != '')
1423 $query .= " order by ${ocolumn}";
1424 $result = useSelectBlade ($query, __FUNCTION__);
1425 $ret = array();
1426 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1427 $ret[] = $row;
1428 return $ret;
1429}
1430
e673ee24
DO
1431// This function returns either port ID or NULL for specified arguments.
1432function getPortID ($object_id, $port_name)
1433{
e673ee24 1434 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
065eeb52 1435 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1436 $rows = $result->fetchAll (PDO::FETCH_NUM);
1437 if (count ($rows) != 1)
1438 return NULL;
1439 $ret = $rows[0][0];
1440 $result->closeCursor();
1441 return $ret;
1442}
1443
1444function commitCreateUserAccount ($username, $realname, $password)
1445{
1446 return useInsertBlade
1447 (
1448 'UserAccount',
1449 array
1450 (
1451 'user_name' => "'${username}'",
1452 'user_realname' => "'${realname}'",
1453 'user_password_hash' => "'${password}'"
1454 )
1455 );
1456}
1457
1458function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1459{
1460 global $dbxlink;
1461 $query =
1462 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1463 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1464 $result = $dbxlink->query ($query);
1465 if ($result == NULL)
1466 {
f41b492f 1467 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1468 die;
1469 }
1470 return TRUE;
1471}
1472
1473function commitEnableUserAccount ($id, $new_enabled_value)
1474{
1475 global $dbxlink;
1476 $query =
1477 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1478 "where user_id = ${id} limit 1";
1479 $result = $dbxlink->query ($query);
1480 if ($result == NULL)
1481 {
f41b492f 1482 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1483 die;
1484 }
1485 return TRUE;
1486}
1487
e673ee24
DO
1488// This function returns an array of all port type pairs from PortCompat table.
1489function getPortCompat ()
1490{
e673ee24
DO
1491 $query =
1492 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1493 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1494 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1495 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1496 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1497 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
065eeb52 1498 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1499 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1500 $result->closeCursor();
1501 return $ret;
1502}
1503
1504function removePortCompat ($type1 = 0, $type2 = 0)
1505{
1506 global $dbxlink;
1507 if ($type1 == 0 or $type2 == 0)
1508 {
f41b492f 1509 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1510 die;
1511 }
1512 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1513 $result = $dbxlink->query ($query);
1514 if ($result == NULL)
1515 {
f41b492f 1516 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1517 die;
1518 }
1519 return TRUE;
1520}
1521
1522function addPortCompat ($type1 = 0, $type2 = 0)
1523{
1524 if ($type1 <= 0 or $type2 <= 0)
1525 {
f41b492f 1526 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1527 die;
1528 }
1529 return useInsertBlade
1530 (
1531 'PortCompat',
1532 array ('type1' => $type1, 'type2' => $type2)
1533 );
1534}
1535
1536// This function returns the dictionary as an array of trees, each tree
1537// representing a single chapter. Each element has 'id', 'name', 'sticky'
1538// and 'word' keys with the latter holding all the words within the chapter.
2dd59b15 1539function getDict ($parse_links = FALSE)
e673ee24 1540{
6bb8e41d 1541 $query1 =
e673ee24
DO
1542 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1543 "Chapter natural left join Dictionary order by chapter_name, dict_value";
065eeb52 1544 $result = useSelectBlade ($query1, __FUNCTION__);
e673ee24 1545 $dict = array();
89fa639f 1546 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
1547 {
1548 $chapter_no = $row['chapter_no'];
1549 if (!isset ($dict[$chapter_no]))
1550 {
1551 $dict[$chapter_no]['no'] = $chapter_no;
1552 $dict[$chapter_no]['name'] = $row['chapter_name'];
1553 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1554 $dict[$chapter_no]['word'] = array();
1555 }
1556 if ($row['dict_key'] != NULL)
6bb8e41d 1557 {
2dd59b15
DO
1558 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1559 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1560 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1561 }
e673ee24 1562 }
89fa639f
DO
1563 $result->closeCursor();
1564 unset ($result);
6bb8e41d
DO
1565// Find the list of all assigned values of dictionary-addressed attributes, each with
1566// chapter/word keyed reference counters. Use the structure to adjust reference counters
1567// of the returned disctionary words.
1568 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1569 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1570 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1571 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1572 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1573 "order by a.attr_id, am.chapter_no, uint_value";
065eeb52 1574 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1575 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1576 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1577 $result->closeCursor();
e673ee24
DO
1578 return $dict;
1579}
1580
da95280e
DO
1581function getDictStats ()
1582{
82f7e2e8 1583 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
da95280e 1584 $query =
5aa28abb
DO
1585 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1586 "Chapter natural left join Dictionary group by Chapter.chapter_no";
065eeb52 1587 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1588 $tc = $tw = $uc = $uw = 0;
89fa639f 1589 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1590 {
1591 $tc++;
1592 $tw += $row['wc'];;
1593 if (in_array ($row['chapter_no'], $stock_chapters))
1594 continue;
1595 $uc++;
1596 $uw += $row['wc'];;
1597 }
89fa639f
DO
1598 $result->closeCursor();
1599 unset ($result);
08b4cb24
DO
1600 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1601 "AttributeValue as av on ro.id = av.object_id group by ro.id";
065eeb52 1602 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1603 $to = $ta = $so = 0;
89fa639f 1604 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1605 {
1606 $to++;
1607 if ($row['attrc'] != 0)
1608 {
1609 $so++;
1610 $ta += $row['attrc'];
1611 }
1612 }
89fa639f 1613 $result->closeCursor();
da95280e
DO
1614 $ret = array();
1615 $ret['Total chapters in dictionary'] = $tc;
1616 $ret['Total words in dictionary'] = $tw;
1617 $ret['User chapters'] = $uc;
1618 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1619 $ret['Total objects'] = $to;
1620 $ret['Objects with stickers'] = $so;
1621 $ret['Total stickers attached'] = $ta;
da95280e
DO
1622 return $ret;
1623}
1624
9ec5fdf1
DO
1625function getIPv4Stats()
1626{
9ec5fdf1
DO
1627 $ret = array();
1628 $subject = array();
1629 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1630 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1631 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1632 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1633 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1634 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1635 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1636 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1637
1638 foreach ($subject as $item)
1639 {
065eeb52 1640 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
1641 $row = $result->fetch (PDO::FETCH_NUM);
1642 $ret[$item['txt']] = $row[0];
1643 $result->closeCursor();
1644 unset ($result);
1645 }
1646 return $ret;
1647}
1648
1649function getRackspaceStats()
1650{
9ec5fdf1
DO
1651 $ret = array();
1652 $subject = array();
1653 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1654 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1655 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1656 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1657
1658 foreach ($subject as $item)
1659 {
065eeb52 1660 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1661 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1662 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1663 $result->closeCursor();
1664 unset ($result);
1665 }
1666 return $ret;
1667}
1668
5bbbeaa2
DO
1669function getTagStats ()
1670{
1671 $ret = array();
1672 $query = "select tag, count(tag_id) as refcnt from " .
1673 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1674 "group by tag_id order by refcnt desc";
065eeb52 1675 $result = useSelectBlade ($query, __FUNCTION__);
5bbbeaa2
DO
1676 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1677 $ret[$row['tag']] = $row['refcnt'];
1678 $result->closeCursor();
1679 return $ret;
1680}
1681
e673ee24
DO
1682function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1683{
1684 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1685 {
f41b492f 1686 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1687 die;
1688 }
1689 global $dbxlink;
1690 $query =
1691 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1692 "and dict_key=${dict_key} limit 1";
1693 $result = $dbxlink->query ($query);
1694 if ($result == NULL)
1695 {
f41b492f 1696 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1697 die;
1698 }
1699 return TRUE;
1700}
1701
1702function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1703{
1704 if ($chapter_no <= 0 or empty ($dict_value))
1705 {
f41b492f 1706 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1707 die;
1708 }
1709 return useInsertBlade
1710 (
1711 'Dictionary',
1712 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1713 );
1714}
1715
1716function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1717{
1718 if ($chapter_no <= 0 or $dict_key <= 0)
1719 {
f41b492f 1720 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1721 die;
1722 }
1723 global $dbxlink;
1724 $query =
1725 "delete from Dictionary where chapter_no=${chapter_no} " .
1726 "and dict_key=${dict_key} limit 1";
1727 $result = $dbxlink->query ($query);
1728 if ($result == NULL)
1729 {
f41b492f 1730 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1731 die;
1732 }
1733 return TRUE;
1734}
1735
1736function commitAddChapter ($chapter_name = '')
1737{
1738 if (empty ($chapter_name))
1739 {
f41b492f 1740 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1741 die;
1742 }
1743 return useInsertBlade
1744 (
1745 'Chapter',
1746 array ('chapter_name' => "'${chapter_name}'")
1747 );
1748}
1749
1750function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1751{
1752 if ($chapter_no <= 0 or empty ($chapter_name))
1753 {
f41b492f 1754 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1755 die;
1756 }
1757 global $dbxlink;
1758 $query =
1759 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1760 "and sticky = 'no' limit 1";
1761 $result = $dbxlink->query ($query);
1762 if ($result == NULL)
1763 {
f41b492f 1764 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1765 die;
1766 }
1767 return TRUE;
1768}
1769
1770function commitDeleteChapter ($chapter_no = 0)
1771{
1772 if ($chapter_no <= 0)
1773 {
f41b492f 1774 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1775 die;
1776 }
1777 global $dbxlink;
1778 $query =
1779 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1780 $result = $dbxlink->query ($query);
1781 if ($result == NULL)
1782 {
f41b492f 1783 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1784 die;
1785 }
1786 return TRUE;
1787}
1788
4c330a14
DO
1789// This is a dictionary accessor. We perform link rendering, so the user sees
1790// nice <select> drop-downs.
e673ee24
DO
1791function readChapter ($chapter_name = '')
1792{
1793 if (empty ($chapter_name))
1794 {
f41b492f 1795 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1796 return NULL;
1797 }
e673ee24
DO
1798 $query =
1799 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1800 "where chapter_name = '${chapter_name}'";
065eeb52 1801 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1802 $chapter = array();
1803 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1804 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1805 $result->closeCursor();
4aa8609b
DO
1806 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1807 asort ($chapter);
e673ee24
DO
1808 return $chapter;
1809}
1810
1811function getAttrMap ()
1812{
e673ee24
DO
1813 $query =
1814 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1815 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1816 "Attribute as a natural left join AttributeMap as am " .
1817 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1818 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1819 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1820 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1821 "order by attr_name";
065eeb52 1822 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1823 $ret = array();
1824 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1825 {
1826 $attr_id = $row['attr_id'];
1827 if (!isset ($ret[$attr_id]))
1828 {
1829 $ret[$attr_id]['id'] = $attr_id;
1830 $ret[$attr_id]['type'] = $row['attr_type'];
1831 $ret[$attr_id]['name'] = $row['attr_name'];
1832 $ret[$attr_id]['application'] = array();
1833 }
1834 if ($row['objtype_id'] == '')
1835 continue;
1836 $application['objtype_id'] = $row['objtype_id'];
1837 $application['objtype_name'] = $row['objtype_name'];
1838 if ($row['attr_type'] == 'dict')
1839 {
1840 $application['chapter_no'] = $row['chapter_no'];
1841 $application['chapter_name'] = $row['chapter_name'];
1842 }
1843 $ret[$attr_id]['application'][] = $application;
1844 }
1845 $result->closeCursor();
1846 return $ret;
1847}
1848
1849function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1850{
1851 if ($attr_id <= 0 or empty ($attr_name))
1852 {
f41b492f 1853 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1854 die;
1855 }
1856 global $dbxlink;
1857 $query =
1858 "update Attribute set attr_name = '${attr_name}' " .
1859 "where attr_id = ${attr_id} limit 1";
1860 $result = $dbxlink->query ($query);
1861 if ($result == NULL)
1862 {
f41b492f 1863 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
1864 die;
1865 }
1866 return TRUE;
1867}
1868
1869function commitAddAttribute ($attr_name = '', $attr_type = '')
1870{
1871 if (empty ($attr_name))
1872 {
f41b492f 1873 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1874 die;
1875 }
1876 switch ($attr_type)
1877 {
1878 case 'uint':
1879 case 'float':
1880 case 'string':
1881 case 'dict':
1882 break;
1883 default:
f41b492f 1884 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1885 die;
1886 }
1887 return useInsertBlade
1888 (
1889 'Attribute',
1890 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1891 );
1892}
1893
1894function commitDeleteAttribute ($attr_id = 0)
1895{
1896 if ($attr_id <= 0)
1897 {
f41b492f 1898 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1899 die;
1900 }
aedf18af 1901 return useDeleteBlade ('Attribute', 'attr_id', $attr_id, FALSE);
e673ee24
DO
1902}
1903
1904// FIXME: don't store garbage in chapter_no for non-dictionary types.
1905function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1906{
1907 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1908 {
f41b492f 1909 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1910 die;
1911 }
1912 return useInsertBlade
1913 (
1914 'AttributeMap',
1915 array
1916 (
1917 'attr_id' => $attr_id,
1918 'objtype_id' => $objtype_id,
1919 'chapter_no' => $chapter_no
1920 )
1921 );
1922}
1923
1924function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1925{
1926 if ($attr_id <= 0 or $objtype_id <= 0)
1927 {
f41b492f 1928 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1929 die;
1930 }
1931 global $dbxlink;
1932 $query =
1933 "delete from AttributeMap where attr_id=${attr_id} " .
1934 "and objtype_id=${objtype_id} limit 1";
1935 $result = $dbxlink->query ($query);
1936 if ($result == NULL)
1937 {
f41b492f 1938 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1939 die;
1940 }
1941 return TRUE;
1942}
1943
1944// This function returns all optional attributes for requested object
1945// as an array of records. NULL is returned on error and empty array
1946// is returned, if there are no attributes found.
24cbe8af 1947function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
1948{
1949 if ($object_id <= 0)
1950 {
f41b492f 1951 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
1952 return NULL;
1953 }
e673ee24
DO
1954 $ret = array();
1955 $query =
1956 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1957 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1958 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1959 "inner join Attribute as A using (attr_id) " .
1960 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1961 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1962 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1a576609 1963 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
065eeb52 1964 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1965 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1966 {
1967 $record = array();
1968 $record['id'] = $row['attr_id'];
1969 $record['name'] = $row['attr_name'];
1970 $record['type'] = $row['attr_type'];
1971 switch ($row['attr_type'])
1972 {
1973 case 'uint':
1974 case 'float':
1975 case 'string':
24cbe8af
DO
1976 $record['value'] = $row[$row['attr_type'] . '_value'];
1977 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1978 break;
e673ee24 1979 case 'dict':
24cbe8af
DO
1980 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1981 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
1982 $record['chapter_name'] = $row['chapter_name'];
1983 $record['key'] = $row['uint_value'];
1984 break;
1985 default:
1986 $record['value'] = NULL;
1987 break;
1988 }
1989 $ret[$row['attr_id']] = $record;
1990 }
1991 $result->closeCursor();
1992 return $ret;
1993}
1994
1995function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1996{
1997 if ($object_id <= 0 or $attr_id <= 0)
1998 {
f41b492f 1999 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2000 die;
2001 }
2002 global $dbxlink;
2003 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2004 $result = $dbxlink->query ($query);
2005 if ($result == NULL)
2006 {
f41b492f 2007 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2008 die;
2009 }
2010 return TRUE;
2011}
2012
2013// FIXME: don't share common code with use commitResetAttrValue()
2014function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2015{
2016 if ($object_id <= 0 or $attr_id <= 0)
2017 {
f41b492f 2018 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2019 die;
2020 }
2021 if (empty ($value))
2022 return commitResetAttrValue ($object_id, $attr_id);
2023 global $dbxlink;
2024 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
2025 $result = $dbxlink->query ($query1);
2026 if ($result == NULL)
2027 {
f41b492f 2028 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
2029 die;
2030 }
2031 $row = $result->fetch (PDO::FETCH_NUM);
2032 if ($row == NULL)
2033 {
f41b492f 2034 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
2035 die;
2036 }
2037 $attr_type = $row[0];
2038 $result->closeCursor();
2039 switch ($attr_type)
2040 {
2041 case 'uint':
2042 case 'float':
2043 case 'string':
2044 $column = $attr_type . '_value';
2045 break;
2046 case 'dict':
2047 $column = 'uint_value';
2048 break;
2049 default:
f41b492f 2050 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
2051 die;
2052 }
2053 $query2 =
2054 "delete from AttributeValue where " .
2055 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2056 $result = $dbxlink->query ($query2);
2057 if ($result == NULL)
2058 {
f41b492f 2059 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
2060 die;
2061 }
2062 // We know $value isn't empty here.
2063 $query3 =
2064 "insert into AttributeValue set ${column} = '${value}', " .
2065 "object_id = ${object_id}, attr_id = ${attr_id} ";
2066 $result = $dbxlink->query ($query3);
2067 if ($result == NULL)
2068 {
f41b492f 2069 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
2070 die;
2071 }
2072 return TRUE;
2073}
2074
2075function commitUseupPort ($port_id = 0)
2076{
2077 if ($port_id <= 0)
2078 {
f41b492f 2079 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
2080 die;
2081 }
2082 global $dbxlink;
2083 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2084 $result = $dbxlink->exec ($query);
2085 if ($result == NULL)
2086 {
f41b492f 2087 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
2088 die;
2089 }
2090 return TRUE;
2091
2092}
2093
2094// This is a swiss-knife blade to insert a record into a table.
2095// The first argument is table name.
2096// The second argument is an array of "name" => "value" pairs.
2097// The function returns either TRUE or FALSE (we expect one row
2098// to be inserted).
2099function useInsertBlade ($tablename, $values)
2100{
2101 global $dbxlink;
2102 $namelist = $valuelist = '';
2103 foreach ($values as $name => $value)
2104 {
2105 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2106 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2107 }
2108 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2109 $result = $dbxlink->exec ($query);
2110 if ($result != 1)
2111 return FALSE;
2112 return TRUE;
2113}
2114
2115// This swiss-knife blade deletes one record from the specified table
2116// using the specified key name and value.
fe7044ad 2117function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
e673ee24
DO
2118{
2119 global $dbxlink;
2120 if ($quotekey == TRUE)
fe7044ad
DO
2121 $keyvalue = "'${keyvalue}'";
2122 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
2123 if (!$deleteall)
2124 $query .= ' limit 1';
e673ee24
DO
2125 $result = $dbxlink->exec ($query);
2126 if ($result === NULL)
2127 return FALSE;
aedf18af 2128 elseif (!$deleteall && $result != 1)
e673ee24
DO
2129 return FALSE;
2130 else
2131 return TRUE;
2132}
2133
5967b83d
DO
2134function useSelectBlade ($query, $caller = 'N/A')
2135{
2136 global $dbxlink;
2137 $result = $dbxlink->query ($query);
2138 if ($result == NULL)
2139 {
2140 $ei = $dbxlink->errorInfo();
105a3bc8 2141 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
2142 return NULL;
2143 }
2144 return $result;
2145}
2146
9c0b0016
DO
2147function loadConfigCache ()
2148{
4fe32e78 2149 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 2150 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
2151 $cache = array();
2152 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2153 $cache[$row['varname']] = $row;
2154 $result->closeCursor();
2155 return $cache;
2156}
2157
2158// setConfigVar() is expected to perform all necessary filtering
2159function storeConfigVar ($varname = NULL, $varvalue = NULL)
2160{
c461c579 2161 global $dbxlink;
bb6b9880 2162 if (empty ($varname) || $varvalue === NULL)
9c0b0016 2163 {
f41b492f 2164 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
2165 return FALSE;
2166 }
2167 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2168 $result = $dbxlink->query ($query);
2169 if ($result == NULL)
2170 {
f41b492f 2171 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
2172 return FALSE;
2173 }
2174 $rc = $result->rowCount();
2175 $result->closeCursor();
f7ee57a1 2176 if ($rc == 0 or $rc == 1)
9c0b0016 2177 return TRUE;
f41b492f 2178 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2179 return FALSE;
2180}
2181
fbbb74fb
DO
2182// Database version detector. Should behave corretly on any
2183// working dataset a user might have.
2184function getDatabaseVersion ()
2185{
2186 global $dbxlink;
2187 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2188 $result = $dbxlink->query ($query);
2189 if ($result == NULL)
2190 {
2191 $errorInfo = $dbxlink->errorInfo();
2192 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2193 return '0.14.4';
4d2e93f2 2194 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2195 }
2196 $rows = $result->fetchAll (PDO::FETCH_NUM);
2197 if (count ($rows) != 1 || empty ($rows[0][0]))
2198 {
2199 $result->closeCursor();
4d2e93f2 2200 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2201 }
2202 $ret = $rows[0][0];
2203 $result->closeCursor();
2204 return $ret;
2205}
2206
da04825a
DO
2207// Return an array of virtual services. For each of them list real server pools
2208// with their load balancers and other stats.
62a1dcb5
DO
2209function getSLBSummary ()
2210{
6fec9f39
DO
2211 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2212 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2213 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
3e56d972 2214 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
6fec9f39
DO
2215 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2216 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 2217 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2218 $ret = array();
2219 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2220 {
4cadac8f 2221 $vsid = $row['vsid'];
da04825a 2222 $object_id = $row['object_id'];
4cadac8f
DO
2223 if (!isset ($ret[$vsid]))
2224 {
2225 $ret[$vsid] = array();
13bffb29 2226 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2227 $ret[$vsid][$cname] = $row[$cname];
da04825a 2228 $ret[$vsid]['lblist'] = array();
4cadac8f 2229 }
6fec9f39
DO
2230 // There's only one assigned RS pool possible for each LB-VS combination.
2231 $ret[$vsid]['lblist'][$row['object_id']] = array
2232 (
2233 'id' => $row['rspool_id'],
2234 'size' => $row['rscount'],
2235 'name' => $row['pool_name']
2236 );
c3bdc503 2237 }
060ba26e 2238 $result->closeCursor();
c3bdc503 2239 return $ret;
62a1dcb5
DO
2240}
2241
da04825a
DO
2242// Get the detailed composition of a particular virtual service, namely the list
2243// of all pools, each shown with the list of objects servicing it. VS/RS configs
2244// will be returned as well.
060ba26e
DO
2245function getVServiceInfo ($vsid = 0)
2246{
2b4eee17
DO
2247 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2248 "from IPVirtualService where id = ${vsid}";
065eeb52 2249 $result = useSelectBlade ($query1, __FUNCTION__);
060ba26e 2250 $vsinfo = array ();
89fa639f 2251 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
2252 if (!$row)
2253 return NULL;
2254 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2255 $vsinfo[$cname] = $row[$cname];
2256 $vsinfo['rspool'] = array();
89fa639f
DO
2257 $result->closeCursor();
2258 unset ($result);
2b4eee17
DO
2259 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2260 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2261 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2262 "where vs_id = ${vsid} order by pool.name, object_id";
065eeb52 2263 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2264 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 2265 {
2b4eee17 2266 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 2267 {
2b4eee17
DO
2268 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2269 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2270 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2271 $vsinfo['rspool'][$row['id']]['lblist'] = array();
060ba26e 2272 }
2b4eee17
DO
2273 if ($row['object_id'] == NULL)
2274 continue;
2275 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2276 (
2277 'vsconfig' => $row['lb_vsconfig'],
2278 'rsconfig' => $row['lb_rsconfig']
2279 );
060ba26e 2280 }
89fa639f 2281 $result->closeCursor();
060ba26e
DO
2282 return $vsinfo;
2283}
2284
71b8bda1
DO
2285// Collect and return the following info about the given real server pool:
2286// basic information
2287// parent virtual service information
c1ca768c 2288// load balancers list (each with a list of VSes)
71b8bda1
DO
2289// real servers list
2290
2291function getRSPoolInfo ($id = 0)
2292{
c1ca768c 2293 $query1 = "select id, name, vsconfig, rsconfig from " .
481a7f8b 2294 "IPRSPool where id = ${id}";
065eeb52 2295 $result = useSelectBlade ($query1, __FUNCTION__);
71b8bda1 2296 $ret = array();
89fa639f 2297 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2298 if (!$row)
2299 return NULL;
70c24883 2300 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2301 $ret[$c] = $row[$c];
89fa639f
DO
2302 $result->closeCursor();
2303 unset ($result);
71b8bda1
DO
2304 $ret['lblist'] = array();
2305 $ret['rslist'] = array();
1519d6fa
DO
2306 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2307 "where rspool_id = ${id} order by object_id, vs_id";
065eeb52 2308 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2309 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2310 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2311 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2312 $result->closeCursor();
2313 unset ($result);
1f7d18fa 2314 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
676a8268 2315 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
065eeb52 2316 $result = useSelectBlade ($query3, __FUNCTION__);
89fa639f 2317 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2318 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2319 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2320 $result->closeCursor();
71b8bda1
DO
2321 return $ret;
2322}
2323
7e7a8387 2324function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127
DO
2325{
2326 if ($pool_id <= 0 or $rsport <= 0)
2327 {
2328 showError ('Invalid arguments', __FUNCTION__);
2329 die;
2330 }
ca461127
DO
2331 return useInsertBlade
2332 (
2333 'IPRealServer',
2334 array
2335 (
2336 'rsip' => "inet_aton('${rsip}')",
2337 'rsport' => $rsport,
2338 'rspool_id' => $pool_id,
bcbeadb4 2339 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2340 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2341 )
2342 );
2343}
2344
c63a8d6e 2345function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21
DO
2346{
2347 if (empty ($vip) or $vport <= 0 or empty ($proto))
c63a8d6e
DO
2348 return __FUNCTION__ . ': invalid arguments';
2349 if (!useInsertBlade
d6517a21
DO
2350 (
2351 'IPVirtualService',
2352 array
2353 (
2354 'vip' => "inet_aton('${vip}')",
2355 'vport' => $vport,
2356 'proto' => "'${proto}'",
2357 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2358 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2359 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2360 )
c63a8d6e
DO
2361 ))
2362 return __FUNCTION__ . ': SQL insertion failed';
2363 return addTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2364}
2365
c1ca768c 2366function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2367{
c1ca768c 2368 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2369 {
2370 showError ('Invalid arguments', __FUNCTION__);
2371 die;
2372 }
2373 return useInsertBlade
2374 (
2375 'IPLoadBalancer',
2376 array
2377 (
2378 'object_id' => $object_id,
2379 'rspool_id' => $pool_id,
c1ca768c 2380 'vs_id' => $vs_id,
3241551e
DO
2381 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2382 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2383 )
ca461127
DO
2384 );
2385}
2386
fb1c4a54
DO
2387function commitDeleteRS ($id = 0)
2388{
2389 if ($id <= 0)
2390 return FALSE;
aedf18af 2391 return useDeleteBlade ('IPRealServer', 'id', $id, FALSE);
fb1c4a54
DO
2392}
2393
d6517a21
DO
2394function commitDeleteVS ($id = 0)
2395{
2396 if ($id <= 0)
2397 return FALSE;
aedf18af 2398 return useDeleteBlade ('IPVirtualService', 'id', $id, FALSE) && deleteTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2399}
2400
c1ca768c 2401function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2402{
2403 global $dbxlink;
c4d85fd1 2404 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2405 return FALSE;
c1ca768c
DO
2406 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2407 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2408 $result = $dbxlink->exec ($query);
2409 if ($result === NULL)
2410 return FALSE;
2411 elseif ($result != 1)
2412 return FALSE;
2413 else
2414 return TRUE;
2415}
2416
fb1c4a54
DO
2417function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2418{
2419 if ($rsid <= 0 or $rsport <= 0)
2420 {
2421 showError ('Invalid args', __FUNCTION__);
2422 die;
2423 }
2424 if (long2ip (ip2long ($rsip)) !== $rsip)
2425 {
2426 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2427 die;
2428 }
2429 global $dbxlink;
2430 $query =
2431 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2432 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2433 " where id = ${rsid} limit 1";
2434 $result = $dbxlink->query ($query);
2435 if ($result == NULL)
2436 {
2437 showError ("SQL query '${query}' failed", __FUNCTION__);
2438 die;
2439 }
2440 return TRUE;
2441}
2442
c1ca768c 2443function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2444{
c1ca768c 2445 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2446 {
2447 showError ('Invalid args', __FUNCTION__);
2448 die;
2449 }
2450 global $dbxlink;
2451 $query =
2452 "update IPLoadBalancer set vsconfig = " .
2453 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2454 ', rsconfig = ' .
2455 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2456 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2457 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2458 $result = $dbxlink->exec ($query);
2459 if ($result === NULL)
2460 return FALSE;
3241551e
DO
2461 else
2462 return TRUE;
2463}
2464
d6517a21
DO
2465function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2466{
2467 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2468 {
2469 showError ('Invalid args', __FUNCTION__);
2470 die;
2471 }
2472 global $dbxlink;
2473 $query = "update IPVirtualService set " .
2474 "vip = inet_aton('${vip}'), " .
2475 "vport = ${vport}, " .
2476 "proto = '${proto}', " .
2477 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2478 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2479 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2480 " where id = ${vsid} limit 1";
d6517a21
DO
2481 $result = $dbxlink->exec ($query);
2482 if ($result === NULL)
2483 return FALSE;
d6517a21
DO
2484 else
2485 return TRUE;
2486}
2487
e57dca7f 2488// Return the list of virtual services, indexed by vs_id.
70c24883 2489// Each record will be shown with its basic info plus RS pools counter.
11c8e4be 2490function getVSList ($tagfilter = array(), $tfmode = 'any')
e57dca7f 2491{
81736ac1 2492 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2493 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2494 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
996b02ba 2495 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
83d3dde9 2496 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
065eeb52 2497 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2498 $ret = array ();
e57dca7f 2499 while ($row = $result->fetch (PDO::FETCH_ASSOC))
d6517a21 2500 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
4b0932b6 2501 $ret[$row['id']][$cname] = $row[$cname];
e57dca7f 2502 $result->closeCursor();
4b0932b6 2503 return $ret;
e57dca7f
DO
2504}
2505
9a81d416 2506// Return the list of RS pool, indexed by pool id.
11c8e4be 2507function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
9a81d416 2508{
81736ac1 2509 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2510 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2511 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2e4170aa 2512 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
56c076ed 2513 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
065eeb52 2514 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2515 $ret = array ();
9a81d416 2516 while ($row = $result->fetch (PDO::FETCH_ASSOC))
70c24883 2517 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
4b0932b6 2518 $ret[$row['id']][$cname] = $row[$cname];
9a81d416 2519 $result->closeCursor();
4b0932b6 2520 return $ret;
9a81d416
DO
2521}
2522
5a1680d2
DO
2523function loadThumbCache ($rack_id = 0)
2524{
5a1680d2
DO
2525 $ret = NULL;
2526 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2527 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2528 $row = $result->fetch (PDO::FETCH_ASSOC);
2529 if ($row)
2530 $ret = base64_decode ($row['thumb_data']);
2531 $result->closeCursor();
2532 return $ret;
2533}
2534
2535function saveThumbCache ($rack_id = 0, $cache = NULL)
2536{
2537 global $dbxlink;
2538 if ($rack_id == 0 or $cache == NULL)
2539 {
2540 showError ('Invalid arguments', __FUNCTION__);
2541 return;
2542 }
2543 $data = base64_encode ($cache);
2544 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2545 $result = $dbxlink->exec ($query);
2546}
9a81d416 2547
c7fe33be
DO
2548function resetThumbCache ($rack_id = 0)
2549{
2550 global $dbxlink;
2551 if ($rack_id == 0)
2552 {
2553 showError ('Invalid argument', __FUNCTION__);
2554 return;
2555 }
2556 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2557 $result = $dbxlink->exec ($query);
2558}
2559
748805bf
DO
2560// Return the list of attached RS pools for the given object. As long as we have
2561// the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2562// by vs_id, because there will be only one RS pool listed for each VS of the
2563// current object.
78e7b769
DO
2564function getRSPoolsForObject ($object_id = 0)
2565{
2566 if ($object_id <= 0)
2567 {
2568 showError ('Invalid object_id', __FUNCTION__);
2569 return NULL;
2570 }
748805bf 2571 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2572 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
748805bf
DO
2573 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2574 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2575 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2576 "where lb.object_id = ${object_id} " .
2577 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2578 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2579 $ret = array ();
78e7b769 2580 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2581 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2582 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2583 $result->closeCursor();
748805bf 2584 return $ret;
78e7b769
DO
2585}
2586
c63a8d6e 2587function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2588{
c63a8d6e
DO
2589 if (empty ($name))
2590 return __FUNCTION__ . ': invalid arguments';
2591 if (!useInsertBlade
5ad76f01
DO
2592 (
2593 'IPRSPool',
2594 array
2595 (
5ad76f01
DO
2596 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2597 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2598 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2599 )
c63a8d6e
DO
2600 ))
2601 return __FUNCTION__ . ': SQL insertion failed';
2602 return addTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2603}
2604
2605function commitDeleteRSPool ($pool_id = 0)
2606{
2607 global $dbxlink;
2608 if ($pool_id <= 0)
2609 return FALSE;
aedf18af 2610 return useDeleteBlade ('IPRSPool', 'id', $pool_id, FALSE) && deleteTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2611}
2612
2613function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2614{
2615 if ($pool_id <= 0)
2616 {
2617 showError ('Invalid arg', __FUNCTION__);
2618 die;
2619 }
2620 global $dbxlink;
2621 $query = "update IPRSPool set " .
2622 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2623 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2624 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2625 " where id = ${pool_id} limit 1";
2626 $result = $dbxlink->exec ($query);
2627 if ($result === NULL)
2628 return FALSE;
2629 elseif ($result != 1)
2630 return FALSE;
2631 else
2632 return TRUE;
2633}
2634
8253d9f0
DO
2635function getRSList ()
2636{
1f7d18fa 2637 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
8253d9f0 2638 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
065eeb52 2639 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2640 $ret = array ();
8253d9f0 2641 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2642 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2643 $ret[$row['id']][$cname] = $row[$cname];
2644 $result->closeCursor();
2645 return $ret;
2646}
2647
2648// Return the list of all currently configured load balancers with their pool count.
2649function getLBList ()
2650{
4b0932b6
DO
2651 $query = "select object_id, count(rspool_id) as poolcount " .
2652 "from IPLoadBalancer group by object_id order by object_id";
065eeb52 2653 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2654 $ret = array ();
2655 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2656 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2657 $result->closeCursor();
4b0932b6 2658 return $ret;
8253d9f0
DO
2659}
2660
9e677cbd
DO
2661// For the given object return: it vsconfig/rsconfig; the list of RS pools
2662// attached (each with vsconfig/rsconfig in turn), each with the list of
2663// virtual services terminating the pool. Each pool also lists all real
2664// servers with rsconfig.
2987fc1f 2665function getSLBConfig ($object_id)
9e677cbd
DO
2666{
2667 if ($object_id <= 0)
2668 {
2669 showError ('Invalid arg', __FUNCTION__);
2670 return NULL;
2671 }
9e677cbd 2672 $ret = array();
d91f08f3
DO
2673 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2674 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2675 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2676 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3
DO
2677 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2678 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2679 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
9e677cbd 2680 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2681 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2682 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2683 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2684 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2685 {
d91f08f3
DO
2686 $vs_id = $row['vs_id'];
2687 if (!isset ($ret[$vs_id]))
2688 {
2689 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)
2690 $ret[$vs_id][$c] = $row[$c];
2691 $ret[$vs_id]['rslist'] = array();
2692 }
2693 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2694 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2695 }
2696 $result->closeCursor();
2697 return $ret;
2698}
1f7d18fa
DO
2699
2700function commitSetInService ($rs_id = 0, $inservice = '')
2701{
2702 if ($rs_id <= 0 or empty ($inservice))
2703 {
2704 showError ('Invalid args', __FUNCTION__);
2705 return NULL;
2706 }
2707 global $dbxlink;
2708 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2709 $result = $dbxlink->exec ($query);
2710 if ($result === NULL)
2711 return FALSE;
2712 elseif ($result != 1)
2713 return FALSE;
2714 else
2715 return TRUE;
2716}
2717
ad0e4754
DO
2718function executeAutoPorts ($object_id = 0, $type_id = 0)
2719{
2720 if ($object_id == 0 or $type_id == 0)
2721 {
2722 showError ('Invalid arguments', __FUNCTION__);
2723 die;
2724 }
f3f0161f 2725 $ret = TRUE;
118e4c38 2726 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2727 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2728 return $ret;
ad0e4754
DO
2729}
2730
6e49bd1f 2731// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2732// generated/deducted later at higher levels.
f9bc186f 2733function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2734{
f9bc186f
DO
2735 if ($entity_realm == '' or $entity_id <= 0)
2736 {
2737 showError ('Invalid or missing arguments', __FUNCTION__);
2738 return NULL;
2739 }
a6e8d544 2740 $ret = array();
edf0993c
DO
2741 $query = "select tt.id, tag from " .
2742 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2743 "where target_realm = '${entity_realm}' and target_id = ${entity_id} " .
2744 "order by tt.tag";
2745 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2746 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2747 $ret[$row['id']] = $row;
a6e8d544
DO
2748 $result->closeCursor();
2749 return $ret;
5967b83d
DO
2750}
2751
f9bc186f
DO
2752function loadRackObjectTags ($id)
2753{
2754 return loadEntityTags ('object', $id);
2755}
2756
2757function loadIPv4PrefixTags ($id)
2758{
2759 return loadEntityTags ('ipv4net', $id);
2760}
2761
41bd8c87
DO
2762function loadRackTags ($id)
2763{
2764 return loadEntityTags ('rack', $id);
2765}
2766
d817ba03
DO
2767function loadIPv4VSTags ($id)
2768{
2769 return loadEntityTags ('ipv4vs', $id);
2770}
2771
2772function loadIPv4RSPoolTags ($id)
2773{
2774 return loadEntityTags ('ipv4rspool', $id);
2775}
2776
ebae41b3
DO
2777function loadUserTags ($user_id)
2778{
2779 return loadEntityTags ('user', $user_id);
2780}
2781
5967b83d
DO
2782function getTagList ()
2783{
20c901a7 2784 $ret = array();
5b7bd02e
DO
2785 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2786 "from TagTree left join TagStorage on id = tag_id " .
2787 "group by id, target_realm order by tag";
065eeb52 2788 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2789 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2790 {
7cc02fc1 2791 if (!isset ($ret[$row['id']]))
20c901a7 2792 $ret[$row['id']] = array
5b7bd02e
DO
2793 (
2794 'id' => $row['id'],
2795 'tag' => $row['tag'],
2796 'parent_id' => $row['parent_id'],
2797 'refcnt' => array()
2798 );
2799 if ($row['realm'])
20c901a7 2800 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2801 }
5967b83d 2802 $result->closeCursor();
20c901a7 2803 return $ret;
5967b83d
DO
2804}
2805
fe7044ad
DO
2806function commitCreateTag ($tagname = '', $parent_id = 0)
2807{
2808 if ($tagname == '' or $parent_id === 0)
2809 return "Invalid args to " . __FUNCTION__;
2810 $result = useInsertBlade
2811 (
2812 'TagTree',
2813 array
2814 (
2815 'tag' => "'${tagname}'",
2816 'parent_id' => $parent_id
2817 )
2818 );
2819 if ($result)
2820 return '';
2821 else
2822 return "SQL query failed in " . __FUNCTION__;
2823}
2824
2825function commitDestroyTag ($tagid = 0)
2826{
2827 if ($tagid == 0)
2828 return 'Invalid arg to ' . __FUNCTION__;
2829 if (useDeleteBlade ('TagTree', 'id', $tagid, FALSE))
2830 return '';
2831 else
2832 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2833}
f9bc186f 2834
49fb1027 2835function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2836{
49fb1027
DO
2837 if ($parent_id == 0)
2838 $parent_id = 'NULL';
f9bc186f 2839 global $dbxlink;
49fb1027
DO
2840 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2841 "where id = ${tag_id} limit 1";
f9bc186f
DO
2842 $result = $dbxlink->exec ($query);
2843 if ($result === NULL)
49fb1027
DO
2844 return 'SQL query failed in ' . __FUNCTION__;
2845 return '';
f9bc186f
DO
2846}
2847
aedf18af
DO
2848function deleteTagsForEntity ($entity_realm, $entity_id)
2849{
2850 global $dbxlink;
2851 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2852 $result = $dbxlink->exec ($query);
2853 if ($result === NULL)
2854 return FALSE;
2855 else
2856 return TRUE;
2857}
2858
eb6ea26f
DO
2859function addTagForEntity ($realm, $entity_id, $tag_id)
2860{
2861 return useInsertBlade
2862 (
2863 'TagStorage',
2864 array
2865 (
2866 'target_realm' => "'${realm}'",
2867 'target_id' => $entity_id,
2868 'tag_id' => $tag_id,
2869 )
2870 );
2871}
2872
c63a8d6e
DO
2873function addTagsForLastRecord ($realm, $taglist, $last_insert_id = 0)
2874{
2875 if (!count ($taglist))
2876 return '';
2877 if (!$last_insert_id)
2878 $last_insert_id = lastInsertID();
2879 $errcount = 0;
2880 foreach ($taglist as $tag_id)
2881 if (addTagForEntity ($realm, $last_insert_id, $tag_id) == FALSE)
2882 $errcount++;
2883 if (!$errcount)
2884 return '';
2885 else
2886 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2887}
2888
42023f03
DO
2889function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2890{
2891 // $range is in x.x.x.x/x format, split into ip/mask vars
2892 $rangeArray = explode('/', $range);
2893 if (count ($rangeArray) != 2)
2894 return "Invalid IPv4 prefix '${range}'";
2895 $ip = $rangeArray[0];
2896 $mask = $rangeArray[1];
2897
2898 if (empty ($ip) or empty ($mask))
2899 return "Invalid IPv4 prefix '${range}'";
2900 $ipL = ip2long($ip);
2901 $maskL = ip2long($mask);
2902 if ($ipL == -1 || $ipL === FALSE)
2903 return 'Bad IPv4 address';
2904 if ($mask < 32 && $mask > 0)
2905 $maskL = $mask;
2906 else
2907 {
2908 $maskB = decbin($maskL);
2909 if (strlen($maskB)!=32)
2910 return 'Invalid netmask';
2911 $ones=0;
2912 $zeroes=FALSE;
2913 foreach( str_split ($maskB) as $digit)
2914 {
2915 if ($digit == '0')
2916 $zeroes = TRUE;
2917 if ($digit == '1')
2918 {
2919 $ones++;
2920 if ($zeroes == TRUE)
2921 return 'Invalid netmask';
2922 }
2923 }
2924 $maskL = $ones;
2925 }
2926 $binmask = binMaskFromDec($maskL);
2927 $ipL = $ipL & $binmask;
2928
2929 $query =
2930 "select ".
2931 "id, ip, mask, name ".
2932 "from IPRanges ";
2933
065eeb52 2934 $result = useSelectBlade ($query, __FUNCTION__);
42023f03
DO
2935
2936 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2937 {
2938 $otherip = $row['ip'];
2939 $othermask = binMaskFromDec($row['mask']);
2940 if (($otherip & $othermask) == ($ipL & $othermask))
2941 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2942 if (($otherip & $binmask) == ($ipL & $binmask))
2943 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2944 }
2945 $result->closeCursor();
2946 unset ($result);
2947 $result = useInsertBlade
2948 (
2949 'IPRanges',
2950 array
2951 (
2952 'ip' => sprintf ('%u', $ipL),
2953 'mask' => "'${maskL}'",
2954 'name' => "'${name}'"
2955 )
2956 );
2957
2958 if ($is_bcast and $maskL < 31)
2959 {
2960 $network_addr = long2ip ($ipL);
2961 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2962 updateAddress ($network_addr, 'network', 'yes');
2963 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2964 }
c63a8d6e 2965 return addTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
2966}
2967
2968// FIXME: This function doesn't wipe relevant records from IPAddress table.
2969function destroyIPv4Prefix ($id = 0)
2970{
2971 if ($id <= 0)
2972 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
2973 if (!useDeleteBlade ('IPRanges', 'id', $id, FALSE))
2974 return __FUNCTION__ . ': SQL query #1 failed';
2975 if (!deleteTagsForEntity ('ipv4net', $id))
2976 return __FUNCTION__ . ': SQL query #2 failed';
2977 return '';
2978}
2979
ebae41b3
DO
2980function loadScript ($name)
2981{
2982 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
2983 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
2984 if ($row !== FALSE)
2985 return $row[0];
2986 else
2987 return NULL;
ebae41b3
DO
2988}
2989
2990function saveScript ($name, $text)
2991{
2992 if (empty ($name))
2993 {
2994 showError ('Invalid argument');
2995 return FALSE;
2996 }
4a6a28f1
DO
2997 // delete regardless of existence
2998 useDeleteBlade ('Script', 'script_name', $name, TRUE);
2999 return useInsertBlade
ebae41b3
DO
3000 (
3001 'Script',
3002 array
3003 (
3004 'script_name' => "'${name}'",
3005 'script_text' => "'${text}'"
3006 )
3007 );
3008}
3009
3010function saveUserPassword ($user_id, $newp)
bcd37231 3011{
ebae41b3
DO
3012 $newhash = hash (PASSWORD_HASH, $newp);
3013 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
bcd37231
DO
3014}
3015
cf6c472b
DO
3016function objectIsPortless ($id = 0)
3017{
3018 if ($id <= 0)
3019 {
3020 showError ('Invalid argument', __FUNCTION__);
3021 return;
3022 }
3023 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3024 {
3025 showError ('SQL query failed', __FUNCTION__);
3026 return;
3027 }
3028 $row = $result->fetch (PDO::FETCH_NUM);
3029 $count = $row[0];
3030 $result->closeCursor();
3031 unset ($result);
81736ac1 3032 return $count === '0';
cf6c472b
DO
3033}
3034
0f3c6639
DO
3035function tagExistsInDatabase ($tname)
3036{
3037 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3038 $row = $result->fetch (PDO::FETCH_NUM);
3039 $count = $row[0];
3040 $result->closeCursor();
3041 unset ($result);
3042 return $count !== '0';
3043}
3044
e673ee24 3045?>