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