r1939 + introduce IPV4_AUTO_RELEASE option
[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{
6c6f62e8 10 $ret = htmlentities ($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
489a7502
DO
19function getRackspace ($tagfilter = array())
20{
21 $whereclause = getWhereClause ($tagfilter);
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";
489a7502
DO
29 $result = useSelectBlade ($query);
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
e673ee24
DO
39// This function returns detailed information about either all or one
40// rack row depending on its argument.
41function getRackRowInfo ($rackrow_id = 0)
42{
e673ee24 43 $query =
5332840f
DO
44 "select dict_key, dict_value, count(Rack.id) as count, " .
45 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
46 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
e673ee24
DO
47 "where chapter_name = 'RackRow' " .
48 ($rackrow_id > 0 ? "and dict_key = ${rackrow_id} " : '') .
49 "group by dict_key order by dict_value";
e425f895 50 $result = useSelectBlade ($query);
e673ee24
DO
51 $ret = array();
52 $clist = array ('dict_key', 'dict_value', 'count', 'sum');
53 while ($row = $result->fetch (PDO::FETCH_ASSOC))
64b95774 54 foreach ($clist as $cname)
e673ee24
DO
55 $ret[$row['dict_key']][$cname] = $row[$cname];
56 $result->closeCursor();
57 if ($rackrow_id > 0)
58 return current ($ret);
59 else
60 return $ret;
61}
62
63// This function returns id->name map for all object types. The map is used
64// to build <select> input for objects.
65function getObjectTypeList ()
66{
67 return readChapter ('RackObjectType');
68}
69
489a7502
DO
70// Return a part of SQL query suitable for embeding into a bigger text.
71// The returned result should list all tag IDs shown in the tag filter.
72function getWhereClause ($tagfilter = array())
e673ee24 73{
105cea6e 74 $whereclause = '';
105cea6e 75 if (count ($tagfilter))
7cc02fc1 76 {
105cea6e 77 $whereclause .= ' and (';
7cc02fc1
DO
78 $orclause = '';
79 foreach ($tagfilter as $tag_id)
80 {
81 $whereclause .= $orclause . 'tag_id = ' . $tag_id;
82 $orclause = ' or ';
83 }
84 $whereclause .= ') ';
85 }
489a7502
DO
86 return $whereclause;
87}
88
89function getObjectList ($type_id = 0, $tagfilter = array())
90{
91 $whereclause = getWhereClause ($tagfilter);
92 if ($type_id != 0)
93 $whereclause .= " and objtype_id = '${type_id}' ";
e673ee24
DO
94 $query =
95 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
96 "RackObject.label as label, RackObject.barcode as barcode, " .
97 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name from " .
98 "((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
99 "left join RackSpace on RackObject.id = object_id) " .
100 "left join Rack on rack_id = Rack.id " .
7cc02fc1 101 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
105cea6e 102 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
7cc02fc1
DO
103 $whereclause .
104 "order by name";
e425f895 105 $result = useSelectBlade ($query);
e673ee24 106 $ret = array();
e673ee24
DO
107 while ($row = $result->fetch (PDO::FETCH_ASSOC))
108 {
2ac47ae4
DO
109 foreach (array (
110 'id',
111 'name',
112 'label',
113 'barcode',
114 'objtype_name',
115 'objtype_id',
116 'asset_no',
117 'rack_id',
118 'Rack_name'
119 ) as $cname)
e673ee24
DO
120 $ret[$row['id']][$cname] = $row[$cname];
121 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
122 }
123 $result->closeCursor();
124 return $ret;
125}
126
932cf41f 127function getRacksForRow ($row_id = 0, $tagfilter = array())
e673ee24 128{
e673ee24 129 $query =
1c81a02c 130 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
2d7698a2 131 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
e673ee24 132 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
932cf41f 133 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
e673ee24
DO
134 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
135 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
932cf41f
DO
136 getWhereClause ($tagfilter) .
137 " order by row_name, Rack.id";
e425f895 138 $result = useSelectBlade ($query);
e673ee24 139 $ret = array();
1c81a02c
DO
140 $clist = array
141 (
142 'id',
143 'name',
144 'height',
145 'comment',
146 'row_id',
147 'left_is_front',
148 'bottom_is_unit1',
149 'row_name'
150 );
e673ee24 151 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1c81a02c 152 foreach ($clist as $cname)
e673ee24
DO
153 $ret[$row['id']][$cname] = $row[$cname];
154 $result->closeCursor();
6a3a37b2 155 usort ($ret, 'sortRacks');
e673ee24
DO
156 $ret = restoreRackIDs ($ret);
157 return $ret;
158}
159
160// This is a popular helper for getting information about
161// a particular rack and its rackspace at once.
162function getRackData ($rack_id = 0, $silent = FALSE)
163{
164 if ($rack_id == 0)
165 {
166 if ($silent == FALSE)
f41b492f 167 showError ('Invalid rack_id', __FUNCTION__);
e673ee24
DO
168 return NULL;
169 }
e673ee24 170 $query =
1c81a02c 171 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
2d7698a2 172 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
e673ee24
DO
173 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
174 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
89fa639f
DO
175 $result = useSelectBlade ($query);
176 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
e673ee24
DO
177 {
178 if ($silent == FALSE)
f41b492f 179 showError ('Query #1 succeded, but returned no data', __FUNCTION__);
e673ee24
DO
180 return NULL;
181 }
182
183 // load metadata
1c81a02c
DO
184 $clist = array
185 (
186 'id',
187 'name',
188 'height',
189 'comment',
190 'row_id',
191 'left_is_front',
192 'bottom_is_unit1',
193 'row_name'
194 );
195 foreach ($clist as $cname)
196 $rack[$cname] = $row[$cname];
89fa639f
DO
197 $result->closeCursor();
198 unset ($result);
e673ee24
DO
199
200 // start with default rackspace
201 for ($i = $rack['height']; $i > 0; $i--)
202 for ($locidx = 0; $locidx < 3; $locidx++)
203 $rack[$i][$locidx]['state'] = 'F';
204
205 // load difference
206 $query =
207 "select unit_no, atom, state, object_id " .
208 "from RackSpace where rack_id = ${rack_id} and " .
209 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
89fa639f 210 $result = useSelectBlade ($query);
e673ee24 211 global $loclist;
89fa639f 212 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
213 {
214 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
215 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
216 }
89fa639f 217 $result->closeCursor();
e673ee24
DO
218 return $rack;
219}
220
221// This is a popular helper.
222function getObjectInfo ($object_id = 0)
223{
224 if ($object_id == 0)
225 {
f41b492f 226 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
227 return;
228 }
e673ee24
DO
229 $query =
230 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
231 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
232 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
e425f895 233 $result = useSelectBlade ($query);
e673ee24
DO
234 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
235 {
f41b492f 236 showError ('Query succeded, but returned no data', __FUNCTION__);
e673ee24
DO
237 $ret = NULL;
238 }
239 else
240 {
241 $ret['id'] = $row['id'];
242 $ret['name'] = $row['name'];
243 $ret['label'] = $row['label'];
244 $ret['barcode'] = $row['barcode'];
245 $ret['objtype_name'] = $row['objtype_name'];
246 $ret['objtype_id'] = $row['objtype_id'];
247 $ret['has_problems'] = $row['has_problems'];
248 $ret['asset_no'] = $row['asset_no'];
249 $ret['dname'] = displayedName ($ret);
250 $ret['comment'] = $row['comment'];
251 }
252 $result->closeCursor();
253 return $ret;
254}
255
256function getPortTypes ()
257{
fe6e3bd7 258 return readChapter ('PortType');
e673ee24
DO
259}
260
261function getObjectPortsAndLinks ($object_id = 0)
262{
263 if ($object_id == 0)
264 {
f41b492f 265 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
266 return;
267 }
e673ee24
DO
268 $query =
269 "select Port.id as Port_id, ".
270 "Port.name as Port_name, ".
271 "Port.label as Port_label, ".
272 "Port.l2address as Port_l2address, ".
273 "Port.type as Port_type, ".
274 "Port.reservation_comment as Port_reservation_comment, " .
275 "dict_value as PortType_name, ".
276 "RemotePort.id as RemotePort_id, ".
277 "RemotePort.name as RemotePort_name, ".
278 "RemotePort.object_id as RemotePort_object_id, ".
279 "RackObject.name as RackObject_name ".
280 "from (".
281 "(".
282 "(".
283 "Port inner join Dictionary on Port.type = dict_key natural join Chapter".
284 ") ".
285 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
286 ") ".
287 "left join Port as RemotePort on Link.portb=RemotePort.id or Link.porta=RemotePort.id ".
288 ") ".
289 "left join RackObject on RemotePort.object_id=RackObject.id ".
290 "where chapter_name = 'PortType' and Port.object_id=${object_id} ".
291 "and (Port.id != RemotePort.id or RemotePort.id is null) ".
292 "order by Port_name";
e425f895
DO
293 $result = useSelectBlade ($query);
294 $ret=array();
295 $count=0;
296 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 297 {
e425f895
DO
298 $ret[$count]['id'] = $row['Port_id'];
299 $ret[$count]['name'] = $row['Port_name'];
300 $ret[$count]['l2address'] = l2addressFromDatabase ($row['Port_l2address']);
301 $ret[$count]['label'] = $row['Port_label'];
302 $ret[$count]['type_id'] = $row['Port_type'];
303 $ret[$count]['type'] = $row['PortType_name'];
304 $ret[$count]['reservation_comment'] = $row['Port_reservation_comment'];
305 $ret[$count]['remote_id'] = $row['RemotePort_id'];
306 $ret[$count]['remote_name'] = htmlentities ($row['RemotePort_name'], ENT_QUOTES);
307 $ret[$count]['remote_object_id'] = $row['RemotePort_object_id'];
308 $ret[$count]['remote_object_name'] = $row['RackObject_name'];
309 // Save on displayedName() calls.
310 if (empty ($row['RackObject_name']) and !empty ($row['RemotePort_object_id']))
e673ee24 311 {
e425f895
DO
312 $oi = getObjectInfo ($row['RemotePort_object_id']);
313 $ret[$count]['remote_object_name'] = displayedName ($oi);
e673ee24 314 }
e425f895 315 $count++;
e673ee24
DO
316 }
317 $result->closeCursor();
318 return $ret;
319}
320
406b54bd 321function commitAddRack ($name, $height, $row_id, $comment, $taglist)
e673ee24 322{
406b54bd
DO
323 $result = useInsertBlade
324 (
325 'Rack',
326 array
327 (
328 'row_id' => $row_id,
329 'name' => "'${name}'",
330 'height' => $height,
331 'comment' => "'${comment}'"
332 )
333 );
334 if ($result == NULL)
e673ee24 335 {
406b54bd 336 showError ('useInsertBlade() failed', __FUNCTION__);
e673ee24
DO
337 return FALSE;
338 }
406b54bd
DO
339
340 if (($result = useSelectBlade ('select last_insert_id()')) == NULL)
e673ee24 341 {
406b54bd 342 showError ('Query #2 failed', __FUNCTION__);
e673ee24
DO
343 return FALSE;
344 }
345 // we always have a row
406b54bd 346 $row = $result->fetch (PDO::FETCH_NUM);
e673ee24 347 $last_insert_id = $row[0];
406b54bd 348 $result->closeCursor();
f60bb422 349 $errcount = 0;
406b54bd
DO
350 foreach ($taglist as $tag_id)
351 if (useInsertBlade
352 (
353 'TagStorage',
354 array
355 (
356 'target_realm' => "'rack'",
357 'target_id' => $last_insert_id,
358 'tag_id' => $tag_id
359 )
360 ) == FALSE)
361 $errcount++;
362 if ($errcount)
363 showError ("Experienced ${errcount} errors adding tags for the rack");
e673ee24
DO
364 return recordHistory ('Rack', "id = ${last_insert_id}");
365}
366
f60bb422 367function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
e673ee24
DO
368{
369 global $dbxlink;
f60bb422
DO
370 // Maintain UNIQUE INDEX for common names and asset tags by
371 // filtering out empty strings (not NULLs).
372 $result1 = useInsertBlade
373 (
374 'RackObject',
375 array
376 (
377 'name' => empty ($new_name) ? 'NULL' : "'${new_name}'",
378 'label' => "'${new_label}'",
379 'barcode' => empty ($new_barcode) ? 'NULL' : "'${new_barcode}'",
380 'objtype_id' => $new_type_id,
381 'asset_no' => empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'"
382 )
383 );
e673ee24
DO
384 if ($result1 == NULL)
385 {
f60bb422 386 showError ("SQL query #1 failed", __FUNCTION__);
e673ee24
DO
387 return FALSE;
388 }
f60bb422 389 $result2 = useSelectBlade ('select last_insert_id()');
e673ee24
DO
390 if ($result2 == NULL)
391 {
392 $errorInfo = $dbxlink->errorInfo();
f41b492f 393 showError ("SQL query '${query}' failed: ${errorInfo[2]}", __FUNCTION__);
e673ee24
DO
394 die;
395 }
396 // we always have a row
397 $row = $result2->fetch (PDO::FETCH_NUM);
398 $last_insert_id = $row[0];
399 $result2->closeCursor();
ad0e4754
DO
400 // Do AutoPorts magic
401 executeAutoPorts ($last_insert_id, $new_type_id);
f60bb422
DO
402 // Now tags...
403 $errcount = 0;
404 foreach ($taglist as $tag_id)
405 if (useInsertBlade
406 (
407 'TagStorage',
408 array
409 (
410 'target_realm' => "'object'",
411 'target_id' => $last_insert_id,
412 'tag_id' => $tag_id
413 )
414 ) == FALSE)
415 $errcount++;
416 if ($errcount)
417 showError ("Experienced ${errcount} errors adding tags for the object");
e673ee24
DO
418 return recordHistory ('RackObject', "id = ${last_insert_id}");
419}
420
421function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
422{
423 if ($object_id == 0 || $new_type_id == 0)
424 {
f41b492f 425 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
426 return FALSE;
427 }
428 global $dbxlink;
429 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
430 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
431 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
432 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
433 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
434 "where id='${object_id}' limit 1";
435 $result = $dbxlink->query ($query);
436 if ($result == NULL)
437 {
f41b492f 438 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
439 return FALSE;
440 }
e673ee24
DO
441 $result->closeCursor();
442 return recordHistory ('RackObject', "id = ${object_id}");
443}
444
445function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
446{
447 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
448 {
f41b492f 449 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
450 return FALSE;
451 }
452 global $dbxlink;
453 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
454 "where id='${rack_id}' limit 1";
455 $result1 = $dbxlink->query ($query);
456 if ($result1->rowCount() != 1)
457 {
f41b492f 458 showError ('Error updating rack information', __FUNCTION__);
e673ee24
DO
459 return FALSE;
460 }
461 return recordHistory ('Rack', "id = ${rack_id}");
462}
463
464// This function accepts rack data returned by getRackData(), validates and applies changes
465// supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
466// correspond to current rack ID.
467// 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
468// If 4th arg is present, object_id fields will be updated accordingly to the new state.
469// The function returns the modified rack upon success.
470function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
471{
472 global $loclist, $dbxlink;
473 $rack_id = $rackData['id'];
474 $rack_name = $rackData['name'];
475 $rackchanged = FALSE;
476 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
477 {
478 for ($locidx = 0; $locidx < 3; $locidx++)
479 {
480 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
481 continue;
482 // detect a change
483 $state = $rackData[$unit_no][$locidx]['state'];
484 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
485 $newstate = $checked_state;
486 else
487 $newstate = $unchecked_state;
488 if ($state == $newstate)
489 continue;
490 $rackchanged = TRUE;
491 // and validate
492 $atom = $loclist[$locidx];
493 // The only changes allowed are those introduced by checkbox grid.
494 if
495 (
496 !($state == $checked_state && $newstate == $unchecked_state) &&
497 !($state == $unchecked_state && $newstate == $checked_state)
498 )
499 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
500 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
501 // anyway and then looking for probable need of INSERT.
502 $query =
503 "delete from RackSpace where rack_id = ${rack_id} and " .
504 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
505 $r = $dbxlink->query ($query);
506 if ($r == NULL)
4d2e93f2 507 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
e673ee24
DO
508 if ($newstate != 'F')
509 {
510 $query =
511 "insert into RackSpace(rack_id, unit_no, atom, state) " .
512 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
513 $r = $dbxlink->query ($query);
514 if ($r == NULL)
4d2e93f2 515 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
e673ee24
DO
516 }
517 if ($newstate == 'T' and $object_id != 0)
518 {
519 // At this point we already have a record in RackSpace.
520 $query =
521 "update RackSpace set object_id=${object_id} " .
522 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
523 $r = $dbxlink->query ($query);
524 if ($r->rowCount() == 1)
525 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
526 else
527 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
528 }
529 }
530 }
531 if ($rackchanged)
c7fe33be
DO
532 {
533 resetThumbCache ($rack_id);
e673ee24 534 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
c7fe33be 535 }
e673ee24
DO
536 else
537 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
538}
539
540// This function builds a list of rack-unit-atom records, which are assigned to
541// the requested object.
542function getMoleculeForObject ($object_id = 0)
543{
544 if ($object_id == 0)
545 {
f41b492f 546 showError ("object_id == 0", __FUNCTION__);
e673ee24
DO
547 return NULL;
548 }
e673ee24
DO
549 $query =
550 "select rack_id, unit_no, atom from RackSpace " .
551 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
e425f895 552 $result = useSelectBlade ($query);
e673ee24
DO
553 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
554 $result->closeCursor();
555 return $ret;
556}
557
558// This function builds a list of rack-unit-atom records for requested molecule.
559function getMolecule ($mid = 0)
560{
561 if ($mid == 0)
562 {
f41b492f 563 showError ("mid == 0", __FUNCTION__);
e673ee24
DO
564 return NULL;
565 }
e673ee24
DO
566 $query =
567 "select rack_id, unit_no, atom from Atom " .
568 "where molecule_id=${mid}";
e425f895 569 $result = useSelectBlade ($query);
e673ee24
DO
570 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
571 $result->closeCursor();
572 return $ret;
573}
574
575// This function creates a new record in Molecule and number of linked
576// R-U-A records in Atom.
577function createMolecule ($molData)
578{
579 global $dbxlink;
580 $query = "insert into Molecule values()";
581 $result1 = $dbxlink->query ($query);
582 if ($result1->rowCount() != 1)
583 {
f41b492f 584 showError ('Error inserting into Molecule', __FUNCTION__);
e673ee24
DO
585 return NULL;
586 }
587 $query = 'select last_insert_id()';
588 $result2 = $dbxlink->query ($query);
589 if ($result2 == NULL)
590 {
f41b492f 591 showError ('Cannot get last ID.', __FUNCTION__);
e673ee24
DO
592 return NULL;
593 }
594 $row = $result2->fetch (PDO::FETCH_NUM);
595 $molecule_id = $row[0];
596 $result2->closeCursor();
64b95774 597 foreach ($molData as $rua)
e673ee24
DO
598 {
599 $rack_id = $rua['rack_id'];
600 $unit_no = $rua['unit_no'];
601 $atom = $rua['atom'];
602 $query =
603 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
604 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
605 $result3 = $dbxlink->query ($query);
606 if ($result3 == NULL or $result3->rowCount() != 1)
607 {
f41b492f 608 showError ('Error inserting into Atom', __FUNCTION__);
e673ee24
DO
609 return NULL;
610 }
611 }
612 return $molecule_id;
613}
614
615// History logger. This function assumes certain table naming convention and
616// column design:
617// 1. History table name equals to dictionary table name plus 'History'.
618// 2. History table must have the same row set (w/o keys) plus one row named
619// 'ctime' of type 'timestamp'.
620function recordHistory ($tableName, $whereClause)
621{
622 global $dbxlink, $remote_username;
623 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
624 $result = $dbxlink->query ($query);
625 if ($result == NULL or $result->rowCount() != 1)
626 {
863b199a 627 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
e673ee24
DO
628 return FALSE;
629 }
630 return TRUE;
631}
632
633function getRackspaceHistory ()
634{
e673ee24
DO
635 $query =
636 "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 " .
637 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
638 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
639 "where chapter_name = 'RackObjectType' order by ctime desc";
e425f895 640 $result = useSelectBlade ($query);
e673ee24
DO
641 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
642 $result->closeCursor();
643 return $ret;
644}
645
646// This function is used in renderRackspaceHistory()
647function getOperationMolecules ($op_id = 0)
648{
649 if ($op_id <= 0)
650 {
f41b492f 651 showError ("Missing argument", __FUNCTION__);
e673ee24
DO
652 return;
653 }
e673ee24 654 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
e425f895 655 $result = useSelectBlade ($query);
e673ee24
DO
656 // We expect one row.
657 $row = $result->fetch (PDO::FETCH_ASSOC);
658 if ($row == NULL)
659 {
f41b492f 660 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
e673ee24
DO
661 return;
662 }
663 $omid = $row['old_molecule_id'];
664 $nmid = $row['new_molecule_id'];
665 $result->closeCursor();
666 return array ($omid, $nmid);
667}
668
c7fe33be 669function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
e673ee24
DO
670{
671 if ($object_id <= 0)
672 {
f41b492f 673 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
674 return;
675 }
676 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
e425f895 677 $result = useSelectBlade ($query);
e673ee24
DO
678 $rows = $result->fetchAll (PDO::FETCH_NUM);
679 $result->closeCursor();
680 $ret = array();
681 foreach ($rows as $row)
682 {
b422aee6
DO
683 if (!$fetch_rackdata)
684 {
685 $ret[$row[0]] = $row[0];
686 continue;
687 }
e673ee24
DO
688 $rackData = getRackData ($row[0]);
689 if ($rackData == NULL)
690 {
f41b492f 691 showError ('getRackData() failed', __FUNCTION__);
e673ee24
DO
692 return NULL;
693 }
694 $ret[$row[0]] = $rackData;
695 }
696 $result->closeCursor();
697 return $ret;
698}
699
7cc02fc1 700function getObjectGroupInfo ()
e673ee24
DO
701{
702 $query =
703 'select dict_key as id, dict_value as name, count(id) as count from ' .
704 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
705 'where chapter_name = "RackObjectType" ' .
7cc02fc1 706 'group by dict_key order by dict_value';
e425f895 707 $result = useSelectBlade ($query);
e673ee24 708 $ret = array();
105cea6e 709 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
e673ee24 710 $clist = array ('id', 'name', 'count');
105cea6e 711 $total = 0;
e673ee24 712 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7cc02fc1 713 if ($row['count'] > 0)
105cea6e
DO
714 {
715 $total += $row['count'];
64b95774 716 foreach ($clist as $cname)
7cc02fc1 717 $ret[$row['id']][$cname] = $row[$cname];
105cea6e 718 }
e673ee24 719 $result->closeCursor();
105cea6e 720 $ret[0]['count'] = $total;
7cc02fc1 721 return $ret;
e673ee24
DO
722}
723
724// This function returns objects, which have no rackspace assigned to them.
725// Additionally it keeps rack_id parameter, so we can silently pre-select
726// the rack required.
727function getUnmountedObjects ()
728{
e673ee24
DO
729 $query =
730 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
731 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
732 'left join RackSpace on id = object_id '.
068ffc0c 733 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
e425f895 734 $result = useSelectBlade ($query);
e673ee24
DO
735 $ret = array();
736 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
737 while ($row = $result->fetch (PDO::FETCH_ASSOC))
738 {
64b95774 739 foreach ($clist as $cname)
e673ee24
DO
740 $ret[$row['id']][$cname] = $row[$cname];
741 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
742 }
743 $result->closeCursor();
744 return $ret;
745}
746
747function getProblematicObjects ()
748{
e673ee24
DO
749 $query =
750 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
751 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
752 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
e425f895 753 $result = useSelectBlade ($query);
e673ee24
DO
754 $ret = array();
755 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
756 while ($row = $result->fetch (PDO::FETCH_ASSOC))
757 {
64b95774 758 foreach ($clist as $cname)
e673ee24
DO
759 $ret[$row['id']][$cname] = $row[$cname];
760 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
761 }
762 $result->closeCursor();
763 return $ret;
764}
765
766function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
767{
768 if ($object_id <= 0)
769 {
f41b492f 770 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
771 return;
772 }
773 $port_l2address = l2addressForDatabase ($port_l2address);
774 $result = useInsertBlade
775 (
776 'Port',
777 array
778 (
779 'name' => "'${port_name}'",
780 'object_id' => "'${object_id}'",
781 'label' => "'${port_label}'",
782 'type' => "'${port_type_id}'",
783 'l2address' => "${port_l2address}"
784 )
785 );
786 if ($result)
787 return '';
788 else
789 return 'SQL query failed';
790}
791
792function commitUpdatePort ($port_id, $port_name, $port_label, $port_l2address, $port_reservation_comment)
793{
794 global $dbxlink;
795 $port_l2address = l2addressForDatabase ($port_l2address);
796 $query =
797 "update Port set name='$port_name', label='$port_label', " .
798 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
799 "where id='$port_id'";
800 $result = $dbxlink->exec ($query);
801 if ($result == 1)
802 return '';
803 $errorInfo = $dbxlink->errorInfo();
804 // We could update nothing.
805 if ($errorInfo[0] == '00000')
806 return '';
807 return $errorInfo[2];
808}
809
810function delObjectPort ($port_id)
811{
812 if (unlinkPort ($port_id) != '')
4d2e93f2 813 return __FUNCTION__ . ': unlinkPort() failed';
e673ee24 814 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
4d2e93f2 815 return __FUNCTION__ . ': useDeleteBlade() failed';
e673ee24
DO
816 return '';
817}
818
819function getObjectAddressesAndNames ()
820{
e673ee24
DO
821 $query =
822 "select object_id as object_id, ".
823 "RackObject.name as object_name, ".
824 "IPBonds.name as name, ".
825 "INET_NTOA(ip) as ip ".
826 "from IPBonds join RackObject on id=object_id ";
e425f895 827 $result = useSelectBlade ($query);
e673ee24
DO
828 $ret = array();
829 $count=0;
830 while ($row = $result->fetch (PDO::FETCH_ASSOC))
831 {
832 $ret[$count]['object_id']=$row['object_id'];
833 $ret[$count]['object_name']=$row['object_name'];
834 $ret[$count]['name']=$row['name'];
835 $ret[$count]['ip']=$row['ip'];
836 $count++;
837 }
838 $result->closeCursor();
839 return $ret;
840}
841
842
843function getEmptyPortsOfType ($type_id)
844{
e673ee24
DO
845 $query =
846 "select distinct Port.id as Port_id, ".
847 "Port.object_id as Port_object_id, ".
848 "RackObject.name as Object_name, ".
849 "Port.name as Port_name, ".
850 "Port.type as Port_type_id, ".
851 "dict_value as Port_type_name ".
852 "from ( ".
853 " ( ".
854 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
855 " ) ".
856 " join RackObject on Port.object_id = RackObject.id ".
857 ") ".
858 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
859 "inner join PortCompat on Port.type = PortCompat.type2 ".
860 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
861 "and Port.reservation_comment is null order by Object_name, Port_name";
e425f895 862 $result = useSelectBlade ($query);
e673ee24
DO
863 $ret = array();
864 $count=0;
865 while ($row = $result->fetch (PDO::FETCH_ASSOC))
866 {
867 $ret[$count]['Port_id']=$row['Port_id'];
868 $ret[$count]['Port_object_id']=$row['Port_object_id'];
869 $ret[$count]['Object_name']=$row['Object_name'];
870 $ret[$count]['Port_name']=$row['Port_name'];
871 $ret[$count]['Port_type_id']=$row['Port_type_id'];
872 $ret[$count]['Port_type_name']=$row['Port_type_name'];
873 $count++;
874 }
875 $result->closeCursor();
876 return $ret;
877}
878
879function linkPorts ($porta, $portb)
880{
881 if ($porta == $portb)
882 return "Ports can't be the same";
883 if ($porta > $portb)
884 {
885 $tmp = $porta;
886 $porta = $portb;
887 $portb = $tmp;
888 }
889 global $dbxlink;
890 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
891 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
892 // FIXME: who cares about the return value?
893 $result = $dbxlink->exec ($query1);
894 $result = $dbxlink->exec ($query2);
895 return '';
896
897}
898
899function unlinkPort ($port)
900{
901 global $dbxlink;
902 $query =
903 "delete from Link where porta='$port' or portb='$port'";
904 $result = $dbxlink->exec ($query);
905 return '';
906
907}
908
4b2bf583
DO
909// FIXME: after falling back to using existing getObjectInfo we don't
910// need that large query. Shrink it some later.
e673ee24
DO
911function getObjectAddresses ($object_id = 0)
912{
913 if ($object_id == 0)
914 {
f41b492f 915 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
916 return;
917 }
e673ee24
DO
918 $query =
919 "select ".
920 "IPAddress.name as IPAddress_name, ".
921 "IPAddress.reserved as IPAddress_reserved, ".
922 "IPBonds.name as IPBonds_name, ".
923 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
924 "IPBonds.type as IPBonds_type, ".
925 "RemoteBonds.name as RemoteBonds_name, ".
926 "RemoteBonds.type as RemoteBonds_type, ".
927 "RemoteBonds.object_id as RemoteBonds_object_id, ".
928 "RemoteObject.name as RemoteObject_name from IPBonds " .
929 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
930 "and IPBonds.object_id!=RemoteBonds.object_id " .
931 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
932 "left join RackObject as RemoteObject on RemoteBonds.object_id=RemoteObject.id ".
933 "where ".
934 "IPBonds.object_id = ${object_id} ".
935 "order by IPBonds.ip, RemoteObject.name";
e425f895
DO
936 $result = useSelectBlade ($query);
937 $ret=array();
938 $count=0;
939 $refcount=0;
940 $prev_ip = 0;
941 // We are going to call getObjectInfo() for some rows,
942 // hence the connector must be unloaded from the
943 // current data.
944 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
945 $result->closeCursor();
946 foreach ($rows as $row)
e673ee24 947 {
e425f895 948 if ($prev_ip != $row['IPBonds_ip'])
e673ee24 949 {
e425f895
DO
950 $count++;
951 $refcount=0;
952 $prev_ip = $row['IPBonds_ip'];
953 $ret[$count]['address_name'] = $row['IPAddress_name'];
954 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
955 $ret[$count]['ip'] = $row['IPBonds_ip'];
956 $ret[$count]['name'] = $row['IPBonds_name'];
957 $ret[$count]['type'] = $row['IPBonds_type'];
958 $ret[$count]['references'] = array();
959 }
e673ee24 960
e425f895
DO
961 if ($row['RemoteBonds_type'])
962 {
963 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
964 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
965 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
966 if (empty ($row['RemoteBonds_object_id']))
967 $ret[$count]['references'][$refcount]['object_name'] = $row['RemoteObject_name'];
968 else
e673ee24 969 {
e425f895
DO
970 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
971 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
e673ee24 972 }
e425f895 973 $refcount++;
e673ee24
DO
974 }
975 }
e673ee24
DO
976 return $ret;
977}
978
3b6ca088 979function getAddressspaceList ($tagfilter = array())
e673ee24 980{
489a7502 981 $whereclause = getWhereClause ($tagfilter);
e673ee24 982 $query =
0b4c0f17 983 "select distinct ".
e673ee24
DO
984 "id as IPRanges_id, ".
985 "INET_NTOA(ip) as IPRanges_ip, ".
986 "mask as IPRanges_mask, ".
987 "name as IPRanges_name ".
74ccacff 988 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
489a7502 989 "where true ${whereclause} " .
74ccacff 990 " order by ip";
e425f895
DO
991 $result = useSelectBlade ($query);
992 $ret=array();
993 $count=0;
994 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 995 {
e425f895
DO
996 $ret[$count]['id'] = $row['IPRanges_id'];
997 $ret[$count]['ip'] = $row['IPRanges_ip'];
998 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
999 $ret[$count]['name'] = $row['IPRanges_name'];
1000 $ret[$count]['mask'] = $row['IPRanges_mask'];
1001 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
1002 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
1003 $count++;
e673ee24
DO
1004 }
1005 $result->closeCursor();
1006 return $ret;
1007
1008}
1009
1010function getRangeByIp ($ip = '', $id = 0)
1011{
e673ee24
DO
1012 if ($id == 0)
1013 $query =
1014 "select ".
1015 "id, INET_NTOA(ip) as ip, mask, name ".
1016 "from IPRanges ";
1017 else
1018 $query =
1019 "select ".
1020 "id, INET_NTOA(ip) as ip, mask, name ".
1021 "from IPRanges where id='$id'";
1022
e425f895
DO
1023 $result = useSelectBlade ($query);
1024 $ret=array();
1025 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 1026 {
e425f895
DO
1027 $binmask=binMaskFromDec($row['mask']);
1028 if ((ip2long($ip) & $binmask) == ip2long($row['ip']))
e673ee24 1029 {
e425f895
DO
1030 $ret['id'] = $row['id'];
1031 $ret['ip'] = $row['ip'];
1032 $ret['ip_bin'] = ip2long($row['ip']);
1033 $ret['name'] = $row['name'];
1034 $ret['mask'] = $row['mask'];
1035 $result->closeCursor();
1036 return $ret;
e673ee24
DO
1037 }
1038 }
1039 $result->closeCursor();
1040 return NULL;
1041}
1042
1043function updateRange ($id=0, $name='')
1044{
1045 global $dbxlink;
1046 $query =
1047 "update IPRanges set name='$name' where id='$id'";
1048 $result = $dbxlink->exec ($query);
1049 return '';
1050
1051}
1052
1053// This function is actually used not only to update, but also to create records,
1054// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1055// (MySQL 4.0 workaround).
1056function updateAddress ($ip=0, $name='', $reserved='no')
1057{
1058 // DELETE may safely fail.
1059 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1060 // INSERT may appear not necessary.
1061 if ($name == '' and $reserved == 'no')
1062 return '';
1063 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1064 return '';
1065 else
1066 return 'useInsertBlade() failed in updateAddress()';
1067}
1068
399214af 1069// FIXME: This function doesn't wipe relevant records from IPAddress table.
e673ee24
DO
1070function commitDeleteRange ($id = 0)
1071{
1072 if ($id <= 0)
4d2e93f2 1073 return __FUNCTION__ . ': Invalid range ID';
aedf18af
DO
1074 if (!useDeleteBlade ('IPRanges', 'id', $id, FALSE))
1075 return __FUNCTION__ . ': SQL query #1 failed';
1076 if (!deleteTagsForEntity ('ipv4net', $id))
1077 return __FUNCTION__ . ': SQL query #2 failed';
1078 return '';
e673ee24
DO
1079}
1080
1081function updateBond ($ip='', $object_id=0, $name='', $type='')
1082{
1083 global $dbxlink;
1084
1085 $query =
1086 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1087 $result = $dbxlink->exec ($query);
1088 return '';
1089}
1090
1091function unbindIpFromObject ($ip='', $object_id=0)
1092{
1093 global $dbxlink;
1094
1095 $query =
1096 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1097 $result = $dbxlink->exec ($query);
1098 return '';
1099}
1100
1101// This function returns either all or one user account. Array key is user name.
1102function getUserAccounts ()
1103{
e673ee24
DO
1104 $query =
1105 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
4e9ea83c 1106 'from UserAccount order by user_name';
e425f895 1107 $result = useSelectBlade ($query);
e673ee24
DO
1108 $ret = array();
1109 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1110 while ($row = $result->fetch (PDO::FETCH_ASSOC))
64b95774 1111 foreach ($clist as $cname)
e673ee24
DO
1112 $ret[$row['user_name']][$cname] = $row[$cname];
1113 $result->closeCursor();
1114 return $ret;
1115}
1116
1117// This function returns permission array for all user accounts. Array key is user name.
1118function getUserPermissions ()
1119{
e673ee24
DO
1120 $query =
1121 "select UserPermission.user_id, user_name, page, tab, access from " .
1122 "UserPermission natural left join UserAccount where (user_name is not null) or " .
7bf342fd 1123 "(user_name is null and UserPermission.user_id = 0) order by user_name, page, tab";
e425f895 1124 $result = useSelectBlade ($query);
e673ee24
DO
1125 $ret = array();
1126 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1127 {
1128 if ($row['user_id'] == 0)
1129 $row['user_name'] = '%';
1130 $ret[$row['user_name']][$row['page']][$row['tab']] = $row['access'];
1131 }
1132 $result->closeCursor();
1133 return $ret;
1134}
1135
1136function searchByl2address ($l2addr)
1137{
e673ee24
DO
1138 $l2addr = l2addressForDatabase ($l2addr);
1139 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1140 "where l2address = ${l2addr}";
e425f895 1141 $result = useSelectBlade ($query);
e673ee24
DO
1142 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1143 $result->closeCursor();
1144 if (count ($rows) == 0) // No results.
1145 return NULL;
1146 if (count ($rows) == 1) // Target found.
1147 return $rows[0];
f41b492f 1148 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
e673ee24
DO
1149 return NULL;
1150}
1151
ea5fc465
DO
1152function getIPv4PrefixSearchResult ($terms)
1153{
1154 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1155 $or = '';
1156 foreach (explode (' ', $terms) as $term)
1157 {
1158 $query .= $or . "name like '%${term}%'";
1159 $or = ' or ';
1160 }
1161 $result = useSelectBlade ($query);
1162 $ret = array();
1163 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1164 $ret[] = $row;
1165 return $ret;
1166}
1167
1168function getIPv4AddressSearchResult ($terms)
1169{
1170 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1171 $or = '';
1172 foreach (explode (' ', $terms) as $term)
1173 {
1174 $query .= $or . "name like '%${term}%'";
1175 $or = ' or ';
1176 }
1177 $result = useSelectBlade ($query);
1178 $ret = array();
1179 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1180 $ret[] = $row;
1181 return $ret;
1182}
1183
05411ccd
DO
1184function getIPv4RSPoolSearchResult ($terms)
1185{
1186 $query = "select id as pool_id, name from IPRSPool where ";
1187 $or = '';
1188 foreach (explode (' ', $terms) as $term)
1189 {
1190 $query .= $or . "name like '%${term}%'";
1191 $or = ' or ';
1192 }
1193 $result = useSelectBlade ($query);
1194 $ret = array();
1195 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1196 $ret[] = $row;
1197 return $ret;
1198}
1199
1200function getIPv4VServiceSearchResult ($terms)
1201{
1202 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1203 $or = '';
1204 foreach (explode (' ', $terms) as $term)
1205 {
1206 $query .= $or . "name like '%${term}%'";
1207 $or = ' or ';
1208 }
1209 $result = useSelectBlade ($query);
1210 $ret = array();
1211 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1212 $ret[] = $row;
1213 return $ret;
1214}
1215
e673ee24
DO
1216// This function returns either port ID or NULL for specified arguments.
1217function getPortID ($object_id, $port_name)
1218{
e673ee24 1219 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
e425f895 1220 $result = useSelectBlade ($query);
e673ee24
DO
1221 $rows = $result->fetchAll (PDO::FETCH_NUM);
1222 if (count ($rows) != 1)
1223 return NULL;
1224 $ret = $rows[0][0];
1225 $result->closeCursor();
1226 return $ret;
1227}
1228
1229function commitCreateUserAccount ($username, $realname, $password)
1230{
1231 return useInsertBlade
1232 (
1233 'UserAccount',
1234 array
1235 (
1236 'user_name' => "'${username}'",
1237 'user_realname' => "'${realname}'",
1238 'user_password_hash' => "'${password}'"
1239 )
1240 );
1241}
1242
1243function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1244{
1245 global $dbxlink;
1246 $query =
1247 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1248 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1249 $result = $dbxlink->query ($query);
1250 if ($result == NULL)
1251 {
f41b492f 1252 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1253 die;
1254 }
1255 return TRUE;
1256}
1257
1258function commitEnableUserAccount ($id, $new_enabled_value)
1259{
1260 global $dbxlink;
1261 $query =
1262 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1263 "where user_id = ${id} limit 1";
1264 $result = $dbxlink->query ($query);
1265 if ($result == NULL)
1266 {
f41b492f 1267 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1268 die;
1269 }
1270 return TRUE;
1271}
1272
1273function commitGrantPermission ($userid, $page, $tab, $value)
1274{
1275 return useInsertBlade
1276 (
1277 'UserPermission',
1278 array
1279 (
1280 'user_id' => $userid,
1281 'page' => "'${page}'",
1282 'tab' => "'${tab}'",
1283 'access' => "'${value}'"
1284 )
1285 );
1286}
1287
1288function commitRevokePermission ($userid, $page, $tab)
1289{
1290 global $dbxlink;
1291 $query =
1292 "delete from UserPermission where user_id = '${userid}' and page = '${page}' " .
1293 "and tab = '$tab' limit 1";
1294 $result = $dbxlink->query ($query);
1295 if ($result == NULL)
1296 {
f41b492f 1297 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1298 die;
1299 }
1300 return TRUE;
1301}
1302
1303// This function returns an array of all port type pairs from PortCompat table.
1304function getPortCompat ()
1305{
e673ee24
DO
1306 $query =
1307 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1308 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1309 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1310 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1311 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1312 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
e425f895 1313 $result = useSelectBlade ($query);
e673ee24
DO
1314 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1315 $result->closeCursor();
1316 return $ret;
1317}
1318
1319function removePortCompat ($type1 = 0, $type2 = 0)
1320{
1321 global $dbxlink;
1322 if ($type1 == 0 or $type2 == 0)
1323 {
f41b492f 1324 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1325 die;
1326 }
1327 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1328 $result = $dbxlink->query ($query);
1329 if ($result == NULL)
1330 {
f41b492f 1331 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1332 die;
1333 }
1334 return TRUE;
1335}
1336
1337function addPortCompat ($type1 = 0, $type2 = 0)
1338{
1339 if ($type1 <= 0 or $type2 <= 0)
1340 {
f41b492f 1341 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1342 die;
1343 }
1344 return useInsertBlade
1345 (
1346 'PortCompat',
1347 array ('type1' => $type1, 'type2' => $type2)
1348 );
1349}
1350
1351// This function returns the dictionary as an array of trees, each tree
1352// representing a single chapter. Each element has 'id', 'name', 'sticky'
1353// and 'word' keys with the latter holding all the words within the chapter.
2dd59b15 1354function getDict ($parse_links = FALSE)
e673ee24 1355{
6bb8e41d 1356 $query1 =
e673ee24
DO
1357 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1358 "Chapter natural left join Dictionary order by chapter_name, dict_value";
89fa639f 1359 $result = useSelectBlade ($query1);
e673ee24 1360 $dict = array();
89fa639f 1361 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
1362 {
1363 $chapter_no = $row['chapter_no'];
1364 if (!isset ($dict[$chapter_no]))
1365 {
1366 $dict[$chapter_no]['no'] = $chapter_no;
1367 $dict[$chapter_no]['name'] = $row['chapter_name'];
1368 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1369 $dict[$chapter_no]['word'] = array();
1370 }
1371 if ($row['dict_key'] != NULL)
6bb8e41d 1372 {
2dd59b15
DO
1373 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1374 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1375 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1376 }
e673ee24 1377 }
89fa639f
DO
1378 $result->closeCursor();
1379 unset ($result);
6bb8e41d
DO
1380// Find the list of all assigned values of dictionary-addressed attributes, each with
1381// chapter/word keyed reference counters. Use the structure to adjust reference counters
1382// of the returned disctionary words.
1383 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1384 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1385 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1386 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1387 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1388 "order by a.attr_id, am.chapter_no, uint_value";
89fa639f 1389 $result = useSelectBlade ($query2);
6bb8e41d 1390 $refcnt = array();
89fa639f 1391 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1392 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1393 $result->closeCursor();
e673ee24
DO
1394 return $dict;
1395}
1396
da95280e
DO
1397function getDictStats ()
1398{
82f7e2e8 1399 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
da95280e 1400 $query =
5aa28abb
DO
1401 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1402 "Chapter natural left join Dictionary group by Chapter.chapter_no";
89fa639f 1403 $result = useSelectBlade ($query);
da95280e 1404 $tc = $tw = $uc = $uw = 0;
89fa639f 1405 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1406 {
1407 $tc++;
1408 $tw += $row['wc'];;
1409 if (in_array ($row['chapter_no'], $stock_chapters))
1410 continue;
1411 $uc++;
1412 $uw += $row['wc'];;
1413 }
89fa639f
DO
1414 $result->closeCursor();
1415 unset ($result);
08b4cb24
DO
1416 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1417 "AttributeValue as av on ro.id = av.object_id group by ro.id";
89fa639f 1418 $result = useSelectBlade ($query);
08b4cb24 1419 $to = $ta = $so = 0;
89fa639f 1420 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1421 {
1422 $to++;
1423 if ($row['attrc'] != 0)
1424 {
1425 $so++;
1426 $ta += $row['attrc'];
1427 }
1428 }
89fa639f 1429 $result->closeCursor();
da95280e
DO
1430 $ret = array();
1431 $ret['Total chapters in dictionary'] = $tc;
1432 $ret['Total words in dictionary'] = $tw;
1433 $ret['User chapters'] = $uc;
1434 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1435 $ret['Total objects'] = $to;
1436 $ret['Objects with stickers'] = $so;
1437 $ret['Total stickers attached'] = $ta;
da95280e
DO
1438 return $ret;
1439}
1440
9ec5fdf1
DO
1441function getIPv4Stats()
1442{
9ec5fdf1
DO
1443 $ret = array();
1444 $subject = array();
1445 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1446 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1447 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1448 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1449 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1450 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1451 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1452 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1453
1454 foreach ($subject as $item)
1455 {
e425f895 1456 $result = useSelectBlade ($item['q']);
9ec5fdf1
DO
1457 $row = $result->fetch (PDO::FETCH_NUM);
1458 $ret[$item['txt']] = $row[0];
1459 $result->closeCursor();
1460 unset ($result);
1461 }
1462 return $ret;
1463}
1464
1465function getRackspaceStats()
1466{
9ec5fdf1
DO
1467 $ret = array();
1468 $subject = array();
1469 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1470 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1471 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1472 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1473
1474 foreach ($subject as $item)
1475 {
e425f895 1476 $result = useSelectBlade ($item['q']);
9ec5fdf1 1477 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1478 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1479 $result->closeCursor();
1480 unset ($result);
1481 }
1482 return $ret;
1483}
1484
5bbbeaa2
DO
1485function getTagStats ()
1486{
1487 $ret = array();
1488 $query = "select tag, count(tag_id) as refcnt from " .
1489 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1490 "group by tag_id order by refcnt desc";
1491 $result = useSelectBlade ($query);
1492 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1493 $ret[$row['tag']] = $row['refcnt'];
1494 $result->closeCursor();
1495 return $ret;
1496}
1497
e673ee24
DO
1498function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1499{
1500 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1501 {
f41b492f 1502 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1503 die;
1504 }
1505 global $dbxlink;
1506 $query =
1507 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1508 "and dict_key=${dict_key} limit 1";
1509 $result = $dbxlink->query ($query);
1510 if ($result == NULL)
1511 {
f41b492f 1512 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1513 die;
1514 }
1515 return TRUE;
1516}
1517
1518function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1519{
1520 if ($chapter_no <= 0 or empty ($dict_value))
1521 {
f41b492f 1522 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1523 die;
1524 }
1525 return useInsertBlade
1526 (
1527 'Dictionary',
1528 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1529 );
1530}
1531
1532function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1533{
1534 if ($chapter_no <= 0 or $dict_key <= 0)
1535 {
f41b492f 1536 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1537 die;
1538 }
1539 global $dbxlink;
1540 $query =
1541 "delete from Dictionary where chapter_no=${chapter_no} " .
1542 "and dict_key=${dict_key} limit 1";
1543 $result = $dbxlink->query ($query);
1544 if ($result == NULL)
1545 {
f41b492f 1546 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1547 die;
1548 }
1549 return TRUE;
1550}
1551
1552function commitAddChapter ($chapter_name = '')
1553{
1554 if (empty ($chapter_name))
1555 {
f41b492f 1556 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1557 die;
1558 }
1559 return useInsertBlade
1560 (
1561 'Chapter',
1562 array ('chapter_name' => "'${chapter_name}'")
1563 );
1564}
1565
1566function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1567{
1568 if ($chapter_no <= 0 or empty ($chapter_name))
1569 {
f41b492f 1570 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1571 die;
1572 }
1573 global $dbxlink;
1574 $query =
1575 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1576 "and sticky = 'no' limit 1";
1577 $result = $dbxlink->query ($query);
1578 if ($result == NULL)
1579 {
f41b492f 1580 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1581 die;
1582 }
1583 return TRUE;
1584}
1585
1586function commitDeleteChapter ($chapter_no = 0)
1587{
1588 if ($chapter_no <= 0)
1589 {
f41b492f 1590 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1591 die;
1592 }
1593 global $dbxlink;
1594 $query =
1595 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1596 $result = $dbxlink->query ($query);
1597 if ($result == NULL)
1598 {
f41b492f 1599 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1600 die;
1601 }
1602 return TRUE;
1603}
1604
4c330a14
DO
1605// This is a dictionary accessor. We perform link rendering, so the user sees
1606// nice <select> drop-downs.
e673ee24
DO
1607function readChapter ($chapter_name = '')
1608{
1609 if (empty ($chapter_name))
1610 {
f41b492f 1611 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1612 return NULL;
1613 }
e673ee24
DO
1614 $query =
1615 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1616 "where chapter_name = '${chapter_name}'";
e425f895 1617 $result = useSelectBlade ($query);
e673ee24
DO
1618 $chapter = array();
1619 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1620 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1621 $result->closeCursor();
4aa8609b
DO
1622 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1623 asort ($chapter);
e673ee24
DO
1624 return $chapter;
1625}
1626
1627function getAttrMap ()
1628{
e673ee24
DO
1629 $query =
1630 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1631 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1632 "Attribute as a natural left join AttributeMap as am " .
1633 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1634 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1635 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1636 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1637 "order by attr_name";
e425f895 1638 $result = useSelectBlade ($query);
e673ee24
DO
1639 $ret = array();
1640 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1641 {
1642 $attr_id = $row['attr_id'];
1643 if (!isset ($ret[$attr_id]))
1644 {
1645 $ret[$attr_id]['id'] = $attr_id;
1646 $ret[$attr_id]['type'] = $row['attr_type'];
1647 $ret[$attr_id]['name'] = $row['attr_name'];
1648 $ret[$attr_id]['application'] = array();
1649 }
1650 if ($row['objtype_id'] == '')
1651 continue;
1652 $application['objtype_id'] = $row['objtype_id'];
1653 $application['objtype_name'] = $row['objtype_name'];
1654 if ($row['attr_type'] == 'dict')
1655 {
1656 $application['chapter_no'] = $row['chapter_no'];
1657 $application['chapter_name'] = $row['chapter_name'];
1658 }
1659 $ret[$attr_id]['application'][] = $application;
1660 }
1661 $result->closeCursor();
1662 return $ret;
1663}
1664
1665function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1666{
1667 if ($attr_id <= 0 or empty ($attr_name))
1668 {
f41b492f 1669 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1670 die;
1671 }
1672 global $dbxlink;
1673 $query =
1674 "update Attribute set attr_name = '${attr_name}' " .
1675 "where attr_id = ${attr_id} limit 1";
1676 $result = $dbxlink->query ($query);
1677 if ($result == NULL)
1678 {
f41b492f 1679 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
1680 die;
1681 }
1682 return TRUE;
1683}
1684
1685function commitAddAttribute ($attr_name = '', $attr_type = '')
1686{
1687 if (empty ($attr_name))
1688 {
f41b492f 1689 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1690 die;
1691 }
1692 switch ($attr_type)
1693 {
1694 case 'uint':
1695 case 'float':
1696 case 'string':
1697 case 'dict':
1698 break;
1699 default:
f41b492f 1700 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1701 die;
1702 }
1703 return useInsertBlade
1704 (
1705 'Attribute',
1706 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1707 );
1708}
1709
1710function commitDeleteAttribute ($attr_id = 0)
1711{
1712 if ($attr_id <= 0)
1713 {
f41b492f 1714 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1715 die;
1716 }
aedf18af 1717 return useDeleteBlade ('Attribute', 'attr_id', $attr_id, FALSE);
e673ee24
DO
1718}
1719
1720// FIXME: don't store garbage in chapter_no for non-dictionary types.
1721function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1722{
1723 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1724 {
f41b492f 1725 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1726 die;
1727 }
1728 return useInsertBlade
1729 (
1730 'AttributeMap',
1731 array
1732 (
1733 'attr_id' => $attr_id,
1734 'objtype_id' => $objtype_id,
1735 'chapter_no' => $chapter_no
1736 )
1737 );
1738}
1739
1740function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1741{
1742 if ($attr_id <= 0 or $objtype_id <= 0)
1743 {
f41b492f 1744 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1745 die;
1746 }
1747 global $dbxlink;
1748 $query =
1749 "delete from AttributeMap where attr_id=${attr_id} " .
1750 "and objtype_id=${objtype_id} limit 1";
1751 $result = $dbxlink->query ($query);
1752 if ($result == NULL)
1753 {
f41b492f 1754 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1755 die;
1756 }
1757 return TRUE;
1758}
1759
1760// This function returns all optional attributes for requested object
1761// as an array of records. NULL is returned on error and empty array
1762// is returned, if there are no attributes found.
24cbe8af 1763function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
1764{
1765 if ($object_id <= 0)
1766 {
f41b492f 1767 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
1768 return NULL;
1769 }
e673ee24
DO
1770 $ret = array();
1771 $query =
1772 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1773 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1774 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1775 "inner join Attribute as A using (attr_id) " .
1776 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1777 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1778 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1a576609 1779 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
e425f895 1780 $result = useSelectBlade ($query);
e673ee24
DO
1781 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1782 {
1783 $record = array();
1784 $record['id'] = $row['attr_id'];
1785 $record['name'] = $row['attr_name'];
1786 $record['type'] = $row['attr_type'];
1787 switch ($row['attr_type'])
1788 {
1789 case 'uint':
1790 case 'float':
1791 case 'string':
24cbe8af
DO
1792 $record['value'] = $row[$row['attr_type'] . '_value'];
1793 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1794 break;
e673ee24 1795 case 'dict':
24cbe8af
DO
1796 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1797 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
1798 $record['chapter_name'] = $row['chapter_name'];
1799 $record['key'] = $row['uint_value'];
1800 break;
1801 default:
1802 $record['value'] = NULL;
1803 break;
1804 }
1805 $ret[$row['attr_id']] = $record;
1806 }
1807 $result->closeCursor();
1808 return $ret;
1809}
1810
1811function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1812{
1813 if ($object_id <= 0 or $attr_id <= 0)
1814 {
f41b492f 1815 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1816 die;
1817 }
1818 global $dbxlink;
1819 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1820 $result = $dbxlink->query ($query);
1821 if ($result == NULL)
1822 {
f41b492f 1823 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1824 die;
1825 }
1826 return TRUE;
1827}
1828
1829// FIXME: don't share common code with use commitResetAttrValue()
1830function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1831{
1832 if ($object_id <= 0 or $attr_id <= 0)
1833 {
f41b492f 1834 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1835 die;
1836 }
1837 if (empty ($value))
1838 return commitResetAttrValue ($object_id, $attr_id);
1839 global $dbxlink;
1840 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1841 $result = $dbxlink->query ($query1);
1842 if ($result == NULL)
1843 {
f41b492f 1844 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
1845 die;
1846 }
1847 $row = $result->fetch (PDO::FETCH_NUM);
1848 if ($row == NULL)
1849 {
f41b492f 1850 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
1851 die;
1852 }
1853 $attr_type = $row[0];
1854 $result->closeCursor();
1855 switch ($attr_type)
1856 {
1857 case 'uint':
1858 case 'float':
1859 case 'string':
1860 $column = $attr_type . '_value';
1861 break;
1862 case 'dict':
1863 $column = 'uint_value';
1864 break;
1865 default:
f41b492f 1866 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
1867 die;
1868 }
1869 $query2 =
1870 "delete from AttributeValue where " .
1871 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1872 $result = $dbxlink->query ($query2);
1873 if ($result == NULL)
1874 {
f41b492f 1875 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
1876 die;
1877 }
1878 // We know $value isn't empty here.
1879 $query3 =
1880 "insert into AttributeValue set ${column} = '${value}', " .
1881 "object_id = ${object_id}, attr_id = ${attr_id} ";
1882 $result = $dbxlink->query ($query3);
1883 if ($result == NULL)
1884 {
f41b492f 1885 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
1886 die;
1887 }
1888 return TRUE;
1889}
1890
1891function commitUseupPort ($port_id = 0)
1892{
1893 if ($port_id <= 0)
1894 {
f41b492f 1895 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
1896 die;
1897 }
1898 global $dbxlink;
1899 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
1900 $result = $dbxlink->exec ($query);
1901 if ($result == NULL)
1902 {
f41b492f 1903 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
1904 die;
1905 }
1906 return TRUE;
1907
1908}
1909
1910// This is a swiss-knife blade to insert a record into a table.
1911// The first argument is table name.
1912// The second argument is an array of "name" => "value" pairs.
1913// The function returns either TRUE or FALSE (we expect one row
1914// to be inserted).
1915function useInsertBlade ($tablename, $values)
1916{
1917 global $dbxlink;
1918 $namelist = $valuelist = '';
1919 foreach ($values as $name => $value)
1920 {
1921 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
1922 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
1923 }
1924 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
1925 $result = $dbxlink->exec ($query);
1926 if ($result != 1)
1927 return FALSE;
1928 return TRUE;
1929}
1930
1931// This swiss-knife blade deletes one record from the specified table
1932// using the specified key name and value.
fe7044ad 1933function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
e673ee24
DO
1934{
1935 global $dbxlink;
1936 if ($quotekey == TRUE)
fe7044ad
DO
1937 $keyvalue = "'${keyvalue}'";
1938 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
1939 if (!$deleteall)
1940 $query .= ' limit 1';
e673ee24
DO
1941 $result = $dbxlink->exec ($query);
1942 if ($result === NULL)
1943 return FALSE;
aedf18af 1944 elseif (!$deleteall && $result != 1)
e673ee24
DO
1945 return FALSE;
1946 else
1947 return TRUE;
1948}
1949
5967b83d
DO
1950function useSelectBlade ($query, $caller = 'N/A')
1951{
1952 global $dbxlink;
1953 $result = $dbxlink->query ($query);
1954 if ($result == NULL)
1955 {
1956 $ei = $dbxlink->errorInfo();
1957 showError ("SQL query '${query}' failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
1958 return NULL;
1959 }
1960 return $result;
1961}
1962
9c0b0016
DO
1963function loadConfigCache ()
1964{
4fe32e78 1965 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
e425f895 1966 $result = useSelectBlade ($query);
9c0b0016
DO
1967 $cache = array();
1968 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1969 $cache[$row['varname']] = $row;
1970 $result->closeCursor();
1971 return $cache;
1972}
1973
1974// setConfigVar() is expected to perform all necessary filtering
1975function storeConfigVar ($varname = NULL, $varvalue = NULL)
1976{
c461c579 1977 global $dbxlink;
bb6b9880 1978 if (empty ($varname) || $varvalue === NULL)
9c0b0016 1979 {
f41b492f 1980 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
1981 return FALSE;
1982 }
1983 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
1984 $result = $dbxlink->query ($query);
1985 if ($result == NULL)
1986 {
f41b492f 1987 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
1988 return FALSE;
1989 }
1990 $rc = $result->rowCount();
1991 $result->closeCursor();
f7ee57a1 1992 if ($rc == 0 or $rc == 1)
9c0b0016 1993 return TRUE;
f41b492f 1994 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
1995 return FALSE;
1996}
1997
fbbb74fb
DO
1998// Database version detector. Should behave corretly on any
1999// working dataset a user might have.
2000function getDatabaseVersion ()
2001{
2002 global $dbxlink;
2003 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2004 $result = $dbxlink->query ($query);
2005 if ($result == NULL)
2006 {
2007 $errorInfo = $dbxlink->errorInfo();
2008 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2009 return '0.14.4';
4d2e93f2 2010 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2011 }
2012 $rows = $result->fetchAll (PDO::FETCH_NUM);
2013 if (count ($rows) != 1 || empty ($rows[0][0]))
2014 {
2015 $result->closeCursor();
4d2e93f2 2016 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2017 }
2018 $ret = $rows[0][0];
2019 $result->closeCursor();
2020 return $ret;
2021}
2022
da04825a
DO
2023// Return an array of virtual services. For each of them list real server pools
2024// with their load balancers and other stats.
62a1dcb5
DO
2025function getSLBSummary ()
2026{
6fec9f39
DO
2027 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2028 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2029 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
3e56d972 2030 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
6fec9f39
DO
2031 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2032 'group by vs.id, object_id order by vs.vip, object_id';
e425f895 2033 $result = useSelectBlade ($query);
c3bdc503
DO
2034 $ret = array();
2035 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2036 {
4cadac8f 2037 $vsid = $row['vsid'];
da04825a 2038 $object_id = $row['object_id'];
4cadac8f
DO
2039 if (!isset ($ret[$vsid]))
2040 {
2041 $ret[$vsid] = array();
13bffb29 2042 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2043 $ret[$vsid][$cname] = $row[$cname];
da04825a 2044 $ret[$vsid]['lblist'] = array();
4cadac8f 2045 }
6fec9f39
DO
2046 // There's only one assigned RS pool possible for each LB-VS combination.
2047 $ret[$vsid]['lblist'][$row['object_id']] = array
2048 (
2049 'id' => $row['rspool_id'],
2050 'size' => $row['rscount'],
2051 'name' => $row['pool_name']
2052 );
c3bdc503 2053 }
060ba26e 2054 $result->closeCursor();
c3bdc503 2055 return $ret;
62a1dcb5
DO
2056}
2057
da04825a
DO
2058// Get the detailed composition of a particular virtual service, namely the list
2059// of all pools, each shown with the list of objects servicing it. VS/RS configs
2060// will be returned as well.
060ba26e
DO
2061function getVServiceInfo ($vsid = 0)
2062{
2b4eee17
DO
2063 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2064 "from IPVirtualService where id = ${vsid}";
89fa639f 2065 $result = useSelectBlade ($query1);
060ba26e 2066 $vsinfo = array ();
89fa639f 2067 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
2068 if (!$row)
2069 return NULL;
2070 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2071 $vsinfo[$cname] = $row[$cname];
2072 $vsinfo['rspool'] = array();
89fa639f
DO
2073 $result->closeCursor();
2074 unset ($result);
2b4eee17
DO
2075 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2076 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2077 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2078 "where vs_id = ${vsid} order by pool.name, object_id";
89fa639f
DO
2079 $result = useSelectBlade ($query2);
2080 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 2081 {
2b4eee17 2082 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 2083 {
2b4eee17
DO
2084 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2085 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2086 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2087 $vsinfo['rspool'][$row['id']]['lblist'] = array();
060ba26e 2088 }
2b4eee17
DO
2089 if ($row['object_id'] == NULL)
2090 continue;
2091 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2092 (
2093 'vsconfig' => $row['lb_vsconfig'],
2094 'rsconfig' => $row['lb_rsconfig']
2095 );
060ba26e 2096 }
89fa639f 2097 $result->closeCursor();
060ba26e
DO
2098 return $vsinfo;
2099}
2100
71b8bda1
DO
2101// Collect and return the following info about the given real server pool:
2102// basic information
2103// parent virtual service information
c1ca768c 2104// load balancers list (each with a list of VSes)
71b8bda1
DO
2105// real servers list
2106
2107function getRSPoolInfo ($id = 0)
2108{
c1ca768c 2109 $query1 = "select id, name, vsconfig, rsconfig from " .
481a7f8b 2110 "IPRSPool where id = ${id}";
89fa639f 2111 $result = useSelectBlade ($query1);
71b8bda1 2112 $ret = array();
89fa639f 2113 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2114 if (!$row)
2115 return NULL;
70c24883 2116 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2117 $ret[$c] = $row[$c];
89fa639f
DO
2118 $result->closeCursor();
2119 unset ($result);
71b8bda1
DO
2120 $ret['lblist'] = array();
2121 $ret['rslist'] = array();
1519d6fa
DO
2122 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2123 "where rspool_id = ${id} order by object_id, vs_id";
89fa639f
DO
2124 $result = useSelectBlade ($query2);
2125 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2126 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2127 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2128 $result->closeCursor();
2129 unset ($result);
1f7d18fa 2130 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
676a8268 2131 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
89fa639f
DO
2132 $result = useSelectBlade ($query3);
2133 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2134 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2135 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2136 $result->closeCursor();
71b8bda1
DO
2137 return $ret;
2138}
2139
7e7a8387 2140function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127
DO
2141{
2142 if ($pool_id <= 0 or $rsport <= 0)
2143 {
2144 showError ('Invalid arguments', __FUNCTION__);
2145 die;
2146 }
ca461127
DO
2147 return useInsertBlade
2148 (
2149 'IPRealServer',
2150 array
2151 (
2152 'rsip' => "inet_aton('${rsip}')",
2153 'rsport' => $rsport,
2154 'rspool_id' => $pool_id,
bcbeadb4 2155 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2156 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2157 )
2158 );
2159}
2160
d6517a21
DO
2161function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig)
2162{
2163 if (empty ($vip) or $vport <= 0 or empty ($proto))
2164 {
2165 showError ('Invalid arguments', __FUNCTION__);
2166 die;
2167 }
2168 return useInsertBlade
2169 (
2170 'IPVirtualService',
2171 array
2172 (
2173 'vip' => "inet_aton('${vip}')",
2174 'vport' => $vport,
2175 'proto' => "'${proto}'",
2176 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2177 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2178 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2179 )
2180 );
2181}
2182
c1ca768c 2183function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2184{
c1ca768c 2185 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2186 {
2187 showError ('Invalid arguments', __FUNCTION__);
2188 die;
2189 }
2190 return useInsertBlade
2191 (
2192 'IPLoadBalancer',
2193 array
2194 (
2195 'object_id' => $object_id,
2196 'rspool_id' => $pool_id,
c1ca768c 2197 'vs_id' => $vs_id,
3241551e
DO
2198 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2199 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2200 )
ca461127
DO
2201 );
2202}
2203
fb1c4a54
DO
2204function commitDeleteRS ($id = 0)
2205{
2206 if ($id <= 0)
2207 return FALSE;
aedf18af 2208 return useDeleteBlade ('IPRealServer', 'id', $id, FALSE);
fb1c4a54
DO
2209}
2210
d6517a21
DO
2211function commitDeleteVS ($id = 0)
2212{
2213 if ($id <= 0)
2214 return FALSE;
aedf18af 2215 return useDeleteBlade ('IPVirtualService', 'id', $id, FALSE) && deleteTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2216}
2217
c1ca768c 2218function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2219{
2220 global $dbxlink;
c4d85fd1 2221 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2222 return FALSE;
c1ca768c
DO
2223 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2224 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2225 $result = $dbxlink->exec ($query);
2226 if ($result === NULL)
2227 return FALSE;
2228 elseif ($result != 1)
2229 return FALSE;
2230 else
2231 return TRUE;
2232}
2233
fb1c4a54
DO
2234function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2235{
2236 if ($rsid <= 0 or $rsport <= 0)
2237 {
2238 showError ('Invalid args', __FUNCTION__);
2239 die;
2240 }
2241 if (long2ip (ip2long ($rsip)) !== $rsip)
2242 {
2243 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2244 die;
2245 }
2246 global $dbxlink;
2247 $query =
2248 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2249 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2250 " where id = ${rsid} limit 1";
2251 $result = $dbxlink->query ($query);
2252 if ($result == NULL)
2253 {
2254 showError ("SQL query '${query}' failed", __FUNCTION__);
2255 die;
2256 }
2257 return TRUE;
2258}
2259
c1ca768c 2260function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2261{
c1ca768c 2262 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2263 {
2264 showError ('Invalid args', __FUNCTION__);
2265 die;
2266 }
2267 global $dbxlink;
2268 $query =
2269 "update IPLoadBalancer set vsconfig = " .
2270 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2271 ', rsconfig = ' .
2272 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2273 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2274 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2275 $result = $dbxlink->exec ($query);
2276 if ($result === NULL)
2277 return FALSE;
3241551e
DO
2278 else
2279 return TRUE;
2280}
2281
d6517a21
DO
2282function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2283{
2284 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2285 {
2286 showError ('Invalid args', __FUNCTION__);
2287 die;
2288 }
2289 global $dbxlink;
2290 $query = "update IPVirtualService set " .
2291 "vip = inet_aton('${vip}'), " .
2292 "vport = ${vport}, " .
2293 "proto = '${proto}', " .
2294 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2295 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2296 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2297 " where id = ${vsid} limit 1";
d6517a21
DO
2298 $result = $dbxlink->exec ($query);
2299 if ($result === NULL)
2300 return FALSE;
d6517a21
DO
2301 else
2302 return TRUE;
2303}
2304
e57dca7f 2305// Return the list of virtual services, indexed by vs_id.
70c24883 2306// Each record will be shown with its basic info plus RS pools counter.
996b02ba 2307function getVSList ($tagfilter = array())
e57dca7f 2308{
489a7502 2309 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2310 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2311 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
996b02ba 2312 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
83d3dde9 2313 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
e425f895 2314 $result = useSelectBlade ($query);
4b0932b6 2315 $ret = array ();
e57dca7f 2316 while ($row = $result->fetch (PDO::FETCH_ASSOC))
d6517a21 2317 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
4b0932b6 2318 $ret[$row['id']][$cname] = $row[$cname];
e57dca7f 2319 $result->closeCursor();
4b0932b6 2320 return $ret;
e57dca7f
DO
2321}
2322
9a81d416 2323// Return the list of RS pool, indexed by pool id.
2e4170aa 2324function getRSPoolList ($tagfilter = array())
9a81d416 2325{
489a7502 2326 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2327 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2328 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2e4170aa 2329 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
83d3dde9 2330 "where true ${whereclause} group by pool.id order by pool.id, name";
e425f895 2331 $result = useSelectBlade ($query);
4b0932b6 2332 $ret = array ();
9a81d416 2333 while ($row = $result->fetch (PDO::FETCH_ASSOC))
70c24883 2334 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
4b0932b6 2335 $ret[$row['id']][$cname] = $row[$cname];
9a81d416 2336 $result->closeCursor();
4b0932b6 2337 return $ret;
9a81d416
DO
2338}
2339
5a1680d2
DO
2340function loadThumbCache ($rack_id = 0)
2341{
5a1680d2
DO
2342 $ret = NULL;
2343 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
e425f895 2344 $result = useSelectBlade ($query);
5a1680d2
DO
2345 $row = $result->fetch (PDO::FETCH_ASSOC);
2346 if ($row)
2347 $ret = base64_decode ($row['thumb_data']);
2348 $result->closeCursor();
2349 return $ret;
2350}
2351
2352function saveThumbCache ($rack_id = 0, $cache = NULL)
2353{
2354 global $dbxlink;
2355 if ($rack_id == 0 or $cache == NULL)
2356 {
2357 showError ('Invalid arguments', __FUNCTION__);
2358 return;
2359 }
2360 $data = base64_encode ($cache);
2361 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2362 $result = $dbxlink->exec ($query);
2363}
9a81d416 2364
c7fe33be
DO
2365function resetThumbCache ($rack_id = 0)
2366{
2367 global $dbxlink;
2368 if ($rack_id == 0)
2369 {
2370 showError ('Invalid argument', __FUNCTION__);
2371 return;
2372 }
2373 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2374 $result = $dbxlink->exec ($query);
2375}
2376
748805bf
DO
2377// Return the list of attached RS pools for the given object. As long as we have
2378// the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2379// by vs_id, because there will be only one RS pool listed for each VS of the
2380// current object.
78e7b769
DO
2381function getRSPoolsForObject ($object_id = 0)
2382{
2383 if ($object_id <= 0)
2384 {
2385 showError ('Invalid object_id', __FUNCTION__);
2386 return NULL;
2387 }
748805bf 2388 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2389 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
748805bf
DO
2390 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2391 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2392 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2393 "where lb.object_id = ${object_id} " .
2394 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
e425f895 2395 $result = useSelectBlade ($query);
748805bf 2396 $ret = array ();
78e7b769 2397 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2398 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2399 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2400 $result->closeCursor();
748805bf 2401 return $ret;
78e7b769
DO
2402}
2403
70c24883 2404function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '')
5ad76f01 2405{
5ad76f01
DO
2406 return useInsertBlade
2407 (
2408 'IPRSPool',
2409 array
2410 (
5ad76f01
DO
2411 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2412 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2413 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2414 )
2415 );
2416}
2417
2418function commitDeleteRSPool ($pool_id = 0)
2419{
2420 global $dbxlink;
2421 if ($pool_id <= 0)
2422 return FALSE;
aedf18af 2423 return useDeleteBlade ('IPRSPool', 'id', $pool_id, FALSE) && deleteTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2424}
2425
2426function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2427{
2428 if ($pool_id <= 0)
2429 {
2430 showError ('Invalid arg', __FUNCTION__);
2431 die;
2432 }
2433 global $dbxlink;
2434 $query = "update IPRSPool set " .
2435 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2436 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2437 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2438 " where id = ${pool_id} limit 1";
2439 $result = $dbxlink->exec ($query);
2440 if ($result === NULL)
2441 return FALSE;
2442 elseif ($result != 1)
2443 return FALSE;
2444 else
2445 return TRUE;
2446}
2447
8253d9f0
DO
2448function getRSList ()
2449{
1f7d18fa 2450 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
8253d9f0 2451 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
e425f895 2452 $result = useSelectBlade ($query);
4b0932b6 2453 $ret = array ();
8253d9f0 2454 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2455 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2456 $ret[$row['id']][$cname] = $row[$cname];
2457 $result->closeCursor();
2458 return $ret;
2459}
2460
2461// Return the list of all currently configured load balancers with their pool count.
2462function getLBList ()
2463{
4b0932b6
DO
2464 $query = "select object_id, count(rspool_id) as poolcount " .
2465 "from IPLoadBalancer group by object_id order by object_id";
e425f895 2466 $result = useSelectBlade ($query);
4b0932b6
DO
2467 $ret = array ();
2468 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2469 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2470 $result->closeCursor();
4b0932b6 2471 return $ret;
8253d9f0
DO
2472}
2473
9e677cbd
DO
2474// For the given object return: it vsconfig/rsconfig; the list of RS pools
2475// attached (each with vsconfig/rsconfig in turn), each with the list of
2476// virtual services terminating the pool. Each pool also lists all real
2477// servers with rsconfig.
2478function buildLBConfig ($object_id)
2479{
2480 if ($object_id <= 0)
2481 {
2482 showError ('Invalid arg', __FUNCTION__);
2483 return NULL;
2484 }
9e677cbd 2485 $ret = array();
d91f08f3
DO
2486 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2487 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2488 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2489 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3
DO
2490 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2491 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2492 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
9e677cbd 2493 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2494 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2495 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
e425f895 2496 $result = useSelectBlade ($query);
9e677cbd
DO
2497 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2498 {
d91f08f3
DO
2499 $vs_id = $row['vs_id'];
2500 if (!isset ($ret[$vs_id]))
2501 {
2502 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)
2503 $ret[$vs_id][$c] = $row[$c];
2504 $ret[$vs_id]['rslist'] = array();
2505 }
2506 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2507 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2508 }
2509 $result->closeCursor();
2510 return $ret;
2511}
1f7d18fa
DO
2512
2513function commitSetInService ($rs_id = 0, $inservice = '')
2514{
2515 if ($rs_id <= 0 or empty ($inservice))
2516 {
2517 showError ('Invalid args', __FUNCTION__);
2518 return NULL;
2519 }
2520 global $dbxlink;
2521 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2522 $result = $dbxlink->exec ($query);
2523 if ($result === NULL)
2524 return FALSE;
2525 elseif ($result != 1)
2526 return FALSE;
2527 else
2528 return TRUE;
2529}
2530
ad0e4754
DO
2531function executeAutoPorts ($object_id = 0, $type_id = 0)
2532{
2533 if ($object_id == 0 or $type_id == 0)
2534 {
2535 showError ('Invalid arguments', __FUNCTION__);
2536 die;
2537 }
f3f0161f 2538 $ret = TRUE;
118e4c38 2539 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2540 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2541 return $ret;
ad0e4754
DO
2542}
2543
a6e8d544
DO
2544// Return only implicitly listed tags, the rest of the trail will be
2545// generated/deducted later at higher levels.
f9bc186f 2546function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2547{
f9bc186f
DO
2548 if ($entity_realm == '' or $entity_id <= 0)
2549 {
2550 showError ('Invalid or missing arguments', __FUNCTION__);
2551 return NULL;
2552 }
a6e8d544 2553 $ret = array();
f9bc186f 2554 $result = useSelectBlade ("select tt.id, tag from TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id where target_realm = '${entity_realm}' and target_id = ${entity_id}");
5967b83d 2555 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2556 $ret[$row['id']] = $row;
a6e8d544
DO
2557 $result->closeCursor();
2558 return $ret;
5967b83d
DO
2559}
2560
f9bc186f
DO
2561function loadRackObjectTags ($id)
2562{
2563 return loadEntityTags ('object', $id);
2564}
2565
2566function loadIPv4PrefixTags ($id)
2567{
2568 return loadEntityTags ('ipv4net', $id);
2569}
2570
41bd8c87
DO
2571function loadRackTags ($id)
2572{
2573 return loadEntityTags ('rack', $id);
2574}
2575
d817ba03
DO
2576function loadIPv4VSTags ($id)
2577{
2578 return loadEntityTags ('ipv4vs', $id);
2579}
2580
2581function loadIPv4RSPoolTags ($id)
2582{
2583 return loadEntityTags ('ipv4rspool', $id);
2584}
2585
5967b83d
DO
2586function getTagList ()
2587{
20c901a7 2588 $ret = array();
5b7bd02e
DO
2589 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2590 "from TagTree left join TagStorage on id = tag_id " .
2591 "group by id, target_realm order by tag";
2592 $result = useSelectBlade ($query);
5967b83d 2593 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2594 {
7cc02fc1 2595 if (!isset ($ret[$row['id']]))
20c901a7 2596 $ret[$row['id']] = array
5b7bd02e
DO
2597 (
2598 'id' => $row['id'],
2599 'tag' => $row['tag'],
2600 'parent_id' => $row['parent_id'],
2601 'refcnt' => array()
2602 );
2603 if ($row['realm'])
20c901a7 2604 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2605 }
5967b83d 2606 $result->closeCursor();
20c901a7 2607 return $ret;
5967b83d
DO
2608}
2609
fe7044ad
DO
2610function commitCreateTag ($tagname = '', $parent_id = 0)
2611{
2612 if ($tagname == '' or $parent_id === 0)
2613 return "Invalid args to " . __FUNCTION__;
2614 $result = useInsertBlade
2615 (
2616 'TagTree',
2617 array
2618 (
2619 'tag' => "'${tagname}'",
2620 'parent_id' => $parent_id
2621 )
2622 );
2623 if ($result)
2624 return '';
2625 else
2626 return "SQL query failed in " . __FUNCTION__;
2627}
2628
2629function commitDestroyTag ($tagid = 0)
2630{
2631 if ($tagid == 0)
2632 return 'Invalid arg to ' . __FUNCTION__;
2633 if (useDeleteBlade ('TagTree', 'id', $tagid, FALSE))
2634 return '';
2635 else
2636 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2637}
f9bc186f 2638
49fb1027 2639function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2640{
49fb1027
DO
2641 if ($parent_id == 0)
2642 $parent_id = 'NULL';
f9bc186f 2643 global $dbxlink;
49fb1027
DO
2644 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2645 "where id = ${tag_id} limit 1";
f9bc186f
DO
2646 $result = $dbxlink->exec ($query);
2647 if ($result === NULL)
49fb1027
DO
2648 return 'SQL query failed in ' . __FUNCTION__;
2649 return '';
f9bc186f
DO
2650}
2651
aedf18af
DO
2652function deleteTagsForEntity ($entity_realm, $entity_id)
2653{
2654 global $dbxlink;
2655 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2656 $result = $dbxlink->exec ($query);
2657 if ($result === NULL)
2658 return FALSE;
2659 else
2660 return TRUE;
2661}
2662
e673ee24 2663?>