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