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