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