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