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