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