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