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