r1885 + implement tag filtering for IPv4 RS pools
[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
e673ee24
DO
1128// This function returns either port ID or NULL for specified arguments.
1129function getPortID ($object_id, $port_name)
1130{
e673ee24 1131 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
e425f895 1132 $result = useSelectBlade ($query);
e673ee24
DO
1133 $rows = $result->fetchAll (PDO::FETCH_NUM);
1134 if (count ($rows) != 1)
1135 return NULL;
1136 $ret = $rows[0][0];
1137 $result->closeCursor();
1138 return $ret;
1139}
1140
1141function commitCreateUserAccount ($username, $realname, $password)
1142{
1143 return useInsertBlade
1144 (
1145 'UserAccount',
1146 array
1147 (
1148 'user_name' => "'${username}'",
1149 'user_realname' => "'${realname}'",
1150 'user_password_hash' => "'${password}'"
1151 )
1152 );
1153}
1154
1155function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1156{
1157 global $dbxlink;
1158 $query =
1159 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1160 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1161 $result = $dbxlink->query ($query);
1162 if ($result == NULL)
1163 {
f41b492f 1164 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1165 die;
1166 }
1167 return TRUE;
1168}
1169
1170function commitEnableUserAccount ($id, $new_enabled_value)
1171{
1172 global $dbxlink;
1173 $query =
1174 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1175 "where user_id = ${id} limit 1";
1176 $result = $dbxlink->query ($query);
1177 if ($result == NULL)
1178 {
f41b492f 1179 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1180 die;
1181 }
1182 return TRUE;
1183}
1184
1185function commitGrantPermission ($userid, $page, $tab, $value)
1186{
1187 return useInsertBlade
1188 (
1189 'UserPermission',
1190 array
1191 (
1192 'user_id' => $userid,
1193 'page' => "'${page}'",
1194 'tab' => "'${tab}'",
1195 'access' => "'${value}'"
1196 )
1197 );
1198}
1199
1200function commitRevokePermission ($userid, $page, $tab)
1201{
1202 global $dbxlink;
1203 $query =
1204 "delete from UserPermission where user_id = '${userid}' and page = '${page}' " .
1205 "and tab = '$tab' limit 1";
1206 $result = $dbxlink->query ($query);
1207 if ($result == NULL)
1208 {
f41b492f 1209 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1210 die;
1211 }
1212 return TRUE;
1213}
1214
1215// This function returns an array of all port type pairs from PortCompat table.
1216function getPortCompat ()
1217{
e673ee24
DO
1218 $query =
1219 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1220 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1221 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1222 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1223 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1224 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
e425f895 1225 $result = useSelectBlade ($query);
e673ee24
DO
1226 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1227 $result->closeCursor();
1228 return $ret;
1229}
1230
1231function removePortCompat ($type1 = 0, $type2 = 0)
1232{
1233 global $dbxlink;
1234 if ($type1 == 0 or $type2 == 0)
1235 {
f41b492f 1236 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1237 die;
1238 }
1239 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1240 $result = $dbxlink->query ($query);
1241 if ($result == NULL)
1242 {
f41b492f 1243 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1244 die;
1245 }
1246 return TRUE;
1247}
1248
1249function addPortCompat ($type1 = 0, $type2 = 0)
1250{
1251 if ($type1 <= 0 or $type2 <= 0)
1252 {
f41b492f 1253 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1254 die;
1255 }
1256 return useInsertBlade
1257 (
1258 'PortCompat',
1259 array ('type1' => $type1, 'type2' => $type2)
1260 );
1261}
1262
1263// This function returns the dictionary as an array of trees, each tree
1264// representing a single chapter. Each element has 'id', 'name', 'sticky'
1265// and 'word' keys with the latter holding all the words within the chapter.
2dd59b15 1266function getDict ($parse_links = FALSE)
e673ee24 1267{
6bb8e41d 1268 $query1 =
e673ee24
DO
1269 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1270 "Chapter natural left join Dictionary order by chapter_name, dict_value";
89fa639f 1271 $result = useSelectBlade ($query1);
e673ee24 1272 $dict = array();
89fa639f 1273 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
1274 {
1275 $chapter_no = $row['chapter_no'];
1276 if (!isset ($dict[$chapter_no]))
1277 {
1278 $dict[$chapter_no]['no'] = $chapter_no;
1279 $dict[$chapter_no]['name'] = $row['chapter_name'];
1280 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1281 $dict[$chapter_no]['word'] = array();
1282 }
1283 if ($row['dict_key'] != NULL)
6bb8e41d 1284 {
2dd59b15
DO
1285 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1286 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1287 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1288 }
e673ee24 1289 }
89fa639f
DO
1290 $result->closeCursor();
1291 unset ($result);
6bb8e41d
DO
1292// Find the list of all assigned values of dictionary-addressed attributes, each with
1293// chapter/word keyed reference counters. Use the structure to adjust reference counters
1294// of the returned disctionary words.
1295 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1296 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1297 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1298 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1299 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1300 "order by a.attr_id, am.chapter_no, uint_value";
89fa639f 1301 $result = useSelectBlade ($query2);
6bb8e41d 1302 $refcnt = array();
89fa639f 1303 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1304 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1305 $result->closeCursor();
e673ee24
DO
1306 return $dict;
1307}
1308
da95280e
DO
1309function getDictStats ()
1310{
82f7e2e8 1311 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
da95280e 1312 $query =
5aa28abb
DO
1313 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1314 "Chapter natural left join Dictionary group by Chapter.chapter_no";
89fa639f 1315 $result = useSelectBlade ($query);
da95280e 1316 $tc = $tw = $uc = $uw = 0;
89fa639f 1317 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1318 {
1319 $tc++;
1320 $tw += $row['wc'];;
1321 if (in_array ($row['chapter_no'], $stock_chapters))
1322 continue;
1323 $uc++;
1324 $uw += $row['wc'];;
1325 }
89fa639f
DO
1326 $result->closeCursor();
1327 unset ($result);
08b4cb24
DO
1328 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1329 "AttributeValue as av on ro.id = av.object_id group by ro.id";
89fa639f 1330 $result = useSelectBlade ($query);
08b4cb24 1331 $to = $ta = $so = 0;
89fa639f 1332 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1333 {
1334 $to++;
1335 if ($row['attrc'] != 0)
1336 {
1337 $so++;
1338 $ta += $row['attrc'];
1339 }
1340 }
89fa639f 1341 $result->closeCursor();
da95280e
DO
1342 $ret = array();
1343 $ret['Total chapters in dictionary'] = $tc;
1344 $ret['Total words in dictionary'] = $tw;
1345 $ret['User chapters'] = $uc;
1346 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1347 $ret['Total objects'] = $to;
1348 $ret['Objects with stickers'] = $so;
1349 $ret['Total stickers attached'] = $ta;
da95280e
DO
1350 return $ret;
1351}
1352
9ec5fdf1
DO
1353function getIPv4Stats()
1354{
9ec5fdf1
DO
1355 $ret = array();
1356 $subject = array();
1357 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1358 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1359 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1360 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1361 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1362 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1363 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1364 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1365
1366 foreach ($subject as $item)
1367 {
e425f895 1368 $result = useSelectBlade ($item['q']);
9ec5fdf1
DO
1369 $row = $result->fetch (PDO::FETCH_NUM);
1370 $ret[$item['txt']] = $row[0];
1371 $result->closeCursor();
1372 unset ($result);
1373 }
1374 return $ret;
1375}
1376
1377function getRackspaceStats()
1378{
9ec5fdf1
DO
1379 $ret = array();
1380 $subject = array();
1381 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1382 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1383 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1384 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1385
1386 foreach ($subject as $item)
1387 {
e425f895 1388 $result = useSelectBlade ($item['q']);
9ec5fdf1 1389 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1390 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1391 $result->closeCursor();
1392 unset ($result);
1393 }
1394 return $ret;
1395}
1396
e673ee24
DO
1397function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1398{
1399 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1400 {
f41b492f 1401 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1402 die;
1403 }
1404 global $dbxlink;
1405 $query =
1406 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1407 "and dict_key=${dict_key} limit 1";
1408 $result = $dbxlink->query ($query);
1409 if ($result == NULL)
1410 {
f41b492f 1411 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1412 die;
1413 }
1414 return TRUE;
1415}
1416
1417function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1418{
1419 if ($chapter_no <= 0 or empty ($dict_value))
1420 {
f41b492f 1421 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1422 die;
1423 }
1424 return useInsertBlade
1425 (
1426 'Dictionary',
1427 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1428 );
1429}
1430
1431function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1432{
1433 if ($chapter_no <= 0 or $dict_key <= 0)
1434 {
f41b492f 1435 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1436 die;
1437 }
1438 global $dbxlink;
1439 $query =
1440 "delete from Dictionary where chapter_no=${chapter_no} " .
1441 "and dict_key=${dict_key} limit 1";
1442 $result = $dbxlink->query ($query);
1443 if ($result == NULL)
1444 {
f41b492f 1445 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1446 die;
1447 }
1448 return TRUE;
1449}
1450
1451function commitAddChapter ($chapter_name = '')
1452{
1453 if (empty ($chapter_name))
1454 {
f41b492f 1455 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1456 die;
1457 }
1458 return useInsertBlade
1459 (
1460 'Chapter',
1461 array ('chapter_name' => "'${chapter_name}'")
1462 );
1463}
1464
1465function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1466{
1467 if ($chapter_no <= 0 or empty ($chapter_name))
1468 {
f41b492f 1469 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1470 die;
1471 }
1472 global $dbxlink;
1473 $query =
1474 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1475 "and sticky = 'no' limit 1";
1476 $result = $dbxlink->query ($query);
1477 if ($result == NULL)
1478 {
f41b492f 1479 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1480 die;
1481 }
1482 return TRUE;
1483}
1484
1485function commitDeleteChapter ($chapter_no = 0)
1486{
1487 if ($chapter_no <= 0)
1488 {
f41b492f 1489 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1490 die;
1491 }
1492 global $dbxlink;
1493 $query =
1494 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1495 $result = $dbxlink->query ($query);
1496 if ($result == NULL)
1497 {
f41b492f 1498 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1499 die;
1500 }
1501 return TRUE;
1502}
1503
4c330a14
DO
1504// This is a dictionary accessor. We perform link rendering, so the user sees
1505// nice <select> drop-downs.
e673ee24
DO
1506function readChapter ($chapter_name = '')
1507{
1508 if (empty ($chapter_name))
1509 {
f41b492f 1510 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1511 return NULL;
1512 }
e673ee24
DO
1513 $query =
1514 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1515 "where chapter_name = '${chapter_name}'";
e425f895 1516 $result = useSelectBlade ($query);
e673ee24
DO
1517 $chapter = array();
1518 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1519 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1520 $result->closeCursor();
4aa8609b
DO
1521 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1522 asort ($chapter);
e673ee24
DO
1523 return $chapter;
1524}
1525
1526function getAttrMap ()
1527{
e673ee24
DO
1528 $query =
1529 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1530 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1531 "Attribute as a natural left join AttributeMap as am " .
1532 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1533 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1534 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1535 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1536 "order by attr_name";
e425f895 1537 $result = useSelectBlade ($query);
e673ee24
DO
1538 $ret = array();
1539 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1540 {
1541 $attr_id = $row['attr_id'];
1542 if (!isset ($ret[$attr_id]))
1543 {
1544 $ret[$attr_id]['id'] = $attr_id;
1545 $ret[$attr_id]['type'] = $row['attr_type'];
1546 $ret[$attr_id]['name'] = $row['attr_name'];
1547 $ret[$attr_id]['application'] = array();
1548 }
1549 if ($row['objtype_id'] == '')
1550 continue;
1551 $application['objtype_id'] = $row['objtype_id'];
1552 $application['objtype_name'] = $row['objtype_name'];
1553 if ($row['attr_type'] == 'dict')
1554 {
1555 $application['chapter_no'] = $row['chapter_no'];
1556 $application['chapter_name'] = $row['chapter_name'];
1557 }
1558 $ret[$attr_id]['application'][] = $application;
1559 }
1560 $result->closeCursor();
1561 return $ret;
1562}
1563
1564function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1565{
1566 if ($attr_id <= 0 or empty ($attr_name))
1567 {
f41b492f 1568 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1569 die;
1570 }
1571 global $dbxlink;
1572 $query =
1573 "update Attribute set attr_name = '${attr_name}' " .
1574 "where attr_id = ${attr_id} limit 1";
1575 $result = $dbxlink->query ($query);
1576 if ($result == NULL)
1577 {
f41b492f 1578 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
1579 die;
1580 }
1581 return TRUE;
1582}
1583
1584function commitAddAttribute ($attr_name = '', $attr_type = '')
1585{
1586 if (empty ($attr_name))
1587 {
f41b492f 1588 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1589 die;
1590 }
1591 switch ($attr_type)
1592 {
1593 case 'uint':
1594 case 'float':
1595 case 'string':
1596 case 'dict':
1597 break;
1598 default:
f41b492f 1599 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1600 die;
1601 }
1602 return useInsertBlade
1603 (
1604 'Attribute',
1605 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1606 );
1607}
1608
1609function commitDeleteAttribute ($attr_id = 0)
1610{
1611 if ($attr_id <= 0)
1612 {
f41b492f 1613 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1614 die;
1615 }
1616 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
1617}
1618
1619// FIXME: don't store garbage in chapter_no for non-dictionary types.
1620function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1621{
1622 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1623 {
f41b492f 1624 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1625 die;
1626 }
1627 return useInsertBlade
1628 (
1629 'AttributeMap',
1630 array
1631 (
1632 'attr_id' => $attr_id,
1633 'objtype_id' => $objtype_id,
1634 'chapter_no' => $chapter_no
1635 )
1636 );
1637}
1638
1639function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1640{
1641 if ($attr_id <= 0 or $objtype_id <= 0)
1642 {
f41b492f 1643 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1644 die;
1645 }
1646 global $dbxlink;
1647 $query =
1648 "delete from AttributeMap where attr_id=${attr_id} " .
1649 "and objtype_id=${objtype_id} limit 1";
1650 $result = $dbxlink->query ($query);
1651 if ($result == NULL)
1652 {
f41b492f 1653 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1654 die;
1655 }
1656 return TRUE;
1657}
1658
1659// This function returns all optional attributes for requested object
1660// as an array of records. NULL is returned on error and empty array
1661// is returned, if there are no attributes found.
24cbe8af 1662function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
1663{
1664 if ($object_id <= 0)
1665 {
f41b492f 1666 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
1667 return NULL;
1668 }
e673ee24
DO
1669 $ret = array();
1670 $query =
1671 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1672 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1673 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1674 "inner join Attribute as A using (attr_id) " .
1675 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1676 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1677 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1a576609 1678 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
e425f895 1679 $result = useSelectBlade ($query);
e673ee24
DO
1680 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1681 {
1682 $record = array();
1683 $record['id'] = $row['attr_id'];
1684 $record['name'] = $row['attr_name'];
1685 $record['type'] = $row['attr_type'];
1686 switch ($row['attr_type'])
1687 {
1688 case 'uint':
1689 case 'float':
1690 case 'string':
24cbe8af
DO
1691 $record['value'] = $row[$row['attr_type'] . '_value'];
1692 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1693 break;
e673ee24 1694 case 'dict':
24cbe8af
DO
1695 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1696 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
1697 $record['chapter_name'] = $row['chapter_name'];
1698 $record['key'] = $row['uint_value'];
1699 break;
1700 default:
1701 $record['value'] = NULL;
1702 break;
1703 }
1704 $ret[$row['attr_id']] = $record;
1705 }
1706 $result->closeCursor();
1707 return $ret;
1708}
1709
1710function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1711{
1712 if ($object_id <= 0 or $attr_id <= 0)
1713 {
f41b492f 1714 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1715 die;
1716 }
1717 global $dbxlink;
1718 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1719 $result = $dbxlink->query ($query);
1720 if ($result == NULL)
1721 {
f41b492f 1722 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1723 die;
1724 }
1725 return TRUE;
1726}
1727
1728// FIXME: don't share common code with use commitResetAttrValue()
1729function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1730{
1731 if ($object_id <= 0 or $attr_id <= 0)
1732 {
f41b492f 1733 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1734 die;
1735 }
1736 if (empty ($value))
1737 return commitResetAttrValue ($object_id, $attr_id);
1738 global $dbxlink;
1739 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1740 $result = $dbxlink->query ($query1);
1741 if ($result == NULL)
1742 {
f41b492f 1743 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
1744 die;
1745 }
1746 $row = $result->fetch (PDO::FETCH_NUM);
1747 if ($row == NULL)
1748 {
f41b492f 1749 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
1750 die;
1751 }
1752 $attr_type = $row[0];
1753 $result->closeCursor();
1754 switch ($attr_type)
1755 {
1756 case 'uint':
1757 case 'float':
1758 case 'string':
1759 $column = $attr_type . '_value';
1760 break;
1761 case 'dict':
1762 $column = 'uint_value';
1763 break;
1764 default:
f41b492f 1765 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
1766 die;
1767 }
1768 $query2 =
1769 "delete from AttributeValue where " .
1770 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1771 $result = $dbxlink->query ($query2);
1772 if ($result == NULL)
1773 {
f41b492f 1774 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
1775 die;
1776 }
1777 // We know $value isn't empty here.
1778 $query3 =
1779 "insert into AttributeValue set ${column} = '${value}', " .
1780 "object_id = ${object_id}, attr_id = ${attr_id} ";
1781 $result = $dbxlink->query ($query3);
1782 if ($result == NULL)
1783 {
f41b492f 1784 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
1785 die;
1786 }
1787 return TRUE;
1788}
1789
1790function commitUseupPort ($port_id = 0)
1791{
1792 if ($port_id <= 0)
1793 {
f41b492f 1794 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
1795 die;
1796 }
1797 global $dbxlink;
1798 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
1799 $result = $dbxlink->exec ($query);
1800 if ($result == NULL)
1801 {
f41b492f 1802 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
1803 die;
1804 }
1805 return TRUE;
1806
1807}
1808
1809// This is a swiss-knife blade to insert a record into a table.
1810// The first argument is table name.
1811// The second argument is an array of "name" => "value" pairs.
1812// The function returns either TRUE or FALSE (we expect one row
1813// to be inserted).
1814function useInsertBlade ($tablename, $values)
1815{
1816 global $dbxlink;
1817 $namelist = $valuelist = '';
1818 foreach ($values as $name => $value)
1819 {
1820 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
1821 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
1822 }
1823 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
1824 $result = $dbxlink->exec ($query);
1825 if ($result != 1)
1826 return FALSE;
1827 return TRUE;
1828}
1829
1830// This swiss-knife blade deletes one record from the specified table
1831// using the specified key name and value.
fe7044ad 1832function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
e673ee24
DO
1833{
1834 global $dbxlink;
1835 if ($quotekey == TRUE)
fe7044ad
DO
1836 $keyvalue = "'${keyvalue}'";
1837 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
1838 if (!$deleteall)
1839 $query .= ' limit 1';
e673ee24
DO
1840 $result = $dbxlink->exec ($query);
1841 if ($result === NULL)
1842 return FALSE;
1843 elseif ($result != 1)
1844 return FALSE;
1845 else
1846 return TRUE;
1847}
1848
5967b83d
DO
1849function useSelectBlade ($query, $caller = 'N/A')
1850{
1851 global $dbxlink;
1852 $result = $dbxlink->query ($query);
1853 if ($result == NULL)
1854 {
1855 $ei = $dbxlink->errorInfo();
1856 showError ("SQL query '${query}' failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
1857 return NULL;
1858 }
1859 return $result;
1860}
1861
9c0b0016
DO
1862function loadConfigCache ()
1863{
4fe32e78 1864 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
e425f895 1865 $result = useSelectBlade ($query);
9c0b0016
DO
1866 $cache = array();
1867 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1868 $cache[$row['varname']] = $row;
1869 $result->closeCursor();
1870 return $cache;
1871}
1872
1873// setConfigVar() is expected to perform all necessary filtering
1874function storeConfigVar ($varname = NULL, $varvalue = NULL)
1875{
c461c579 1876 global $dbxlink;
bb6b9880 1877 if (empty ($varname) || $varvalue === NULL)
9c0b0016 1878 {
f41b492f 1879 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
1880 return FALSE;
1881 }
1882 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
1883 $result = $dbxlink->query ($query);
1884 if ($result == NULL)
1885 {
f41b492f 1886 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
1887 return FALSE;
1888 }
1889 $rc = $result->rowCount();
1890 $result->closeCursor();
f7ee57a1 1891 if ($rc == 0 or $rc == 1)
9c0b0016 1892 return TRUE;
f41b492f 1893 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
1894 return FALSE;
1895}
1896
fbbb74fb
DO
1897// Database version detector. Should behave corretly on any
1898// working dataset a user might have.
1899function getDatabaseVersion ()
1900{
1901 global $dbxlink;
1902 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
1903 $result = $dbxlink->query ($query);
1904 if ($result == NULL)
1905 {
1906 $errorInfo = $dbxlink->errorInfo();
1907 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
1908 return '0.14.4';
4d2e93f2 1909 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
1910 }
1911 $rows = $result->fetchAll (PDO::FETCH_NUM);
1912 if (count ($rows) != 1 || empty ($rows[0][0]))
1913 {
1914 $result->closeCursor();
4d2e93f2 1915 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
1916 }
1917 $ret = $rows[0][0];
1918 $result->closeCursor();
1919 return $ret;
1920}
1921
da04825a
DO
1922// Return an array of virtual services. For each of them list real server pools
1923// with their load balancers and other stats.
62a1dcb5
DO
1924function getSLBSummary ()
1925{
6fec9f39
DO
1926 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
1927 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
1928 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
3e56d972 1929 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
6fec9f39
DO
1930 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
1931 'group by vs.id, object_id order by vs.vip, object_id';
e425f895 1932 $result = useSelectBlade ($query);
c3bdc503
DO
1933 $ret = array();
1934 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1935 {
4cadac8f 1936 $vsid = $row['vsid'];
da04825a 1937 $object_id = $row['object_id'];
4cadac8f
DO
1938 if (!isset ($ret[$vsid]))
1939 {
1940 $ret[$vsid] = array();
13bffb29 1941 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 1942 $ret[$vsid][$cname] = $row[$cname];
da04825a 1943 $ret[$vsid]['lblist'] = array();
4cadac8f 1944 }
6fec9f39
DO
1945 // There's only one assigned RS pool possible for each LB-VS combination.
1946 $ret[$vsid]['lblist'][$row['object_id']] = array
1947 (
1948 'id' => $row['rspool_id'],
1949 'size' => $row['rscount'],
1950 'name' => $row['pool_name']
1951 );
c3bdc503 1952 }
060ba26e 1953 $result->closeCursor();
c3bdc503 1954 return $ret;
62a1dcb5
DO
1955}
1956
da04825a
DO
1957// Get the detailed composition of a particular virtual service, namely the list
1958// of all pools, each shown with the list of objects servicing it. VS/RS configs
1959// will be returned as well.
060ba26e
DO
1960function getVServiceInfo ($vsid = 0)
1961{
2b4eee17
DO
1962 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
1963 "from IPVirtualService where id = ${vsid}";
89fa639f 1964 $result = useSelectBlade ($query1);
060ba26e 1965 $vsinfo = array ();
89fa639f 1966 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
1967 if (!$row)
1968 return NULL;
1969 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
1970 $vsinfo[$cname] = $row[$cname];
1971 $vsinfo['rspool'] = array();
89fa639f
DO
1972 $result->closeCursor();
1973 unset ($result);
2b4eee17
DO
1974 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
1975 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
1976 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
1977 "where vs_id = ${vsid} order by pool.name, object_id";
89fa639f
DO
1978 $result = useSelectBlade ($query2);
1979 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 1980 {
2b4eee17 1981 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 1982 {
2b4eee17
DO
1983 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
1984 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
1985 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
1986 $vsinfo['rspool'][$row['id']]['lblist'] = array();
060ba26e 1987 }
2b4eee17
DO
1988 if ($row['object_id'] == NULL)
1989 continue;
1990 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
1991 (
1992 'vsconfig' => $row['lb_vsconfig'],
1993 'rsconfig' => $row['lb_rsconfig']
1994 );
060ba26e 1995 }
89fa639f 1996 $result->closeCursor();
060ba26e
DO
1997 return $vsinfo;
1998}
1999
71b8bda1
DO
2000// Collect and return the following info about the given real server pool:
2001// basic information
2002// parent virtual service information
c1ca768c 2003// load balancers list (each with a list of VSes)
71b8bda1
DO
2004// real servers list
2005
2006function getRSPoolInfo ($id = 0)
2007{
c1ca768c 2008 $query1 = "select id, name, vsconfig, rsconfig from " .
481a7f8b 2009 "IPRSPool where id = ${id}";
89fa639f 2010 $result = useSelectBlade ($query1);
71b8bda1 2011 $ret = array();
89fa639f 2012 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2013 if (!$row)
2014 return NULL;
70c24883 2015 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2016 $ret[$c] = $row[$c];
89fa639f
DO
2017 $result->closeCursor();
2018 unset ($result);
71b8bda1
DO
2019 $ret['lblist'] = array();
2020 $ret['rslist'] = array();
1519d6fa
DO
2021 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2022 "where rspool_id = ${id} order by object_id, vs_id";
89fa639f
DO
2023 $result = useSelectBlade ($query2);
2024 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2025 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2026 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2027 $result->closeCursor();
2028 unset ($result);
1f7d18fa 2029 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
676a8268 2030 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
89fa639f
DO
2031 $result = useSelectBlade ($query3);
2032 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2033 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2034 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2035 $result->closeCursor();
71b8bda1
DO
2036 return $ret;
2037}
2038
7e7a8387 2039function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127
DO
2040{
2041 if ($pool_id <= 0 or $rsport <= 0)
2042 {
2043 showError ('Invalid arguments', __FUNCTION__);
2044 die;
2045 }
ca461127
DO
2046 return useInsertBlade
2047 (
2048 'IPRealServer',
2049 array
2050 (
2051 'rsip' => "inet_aton('${rsip}')",
2052 'rsport' => $rsport,
2053 'rspool_id' => $pool_id,
bcbeadb4 2054 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2055 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2056 )
2057 );
2058}
2059
d6517a21
DO
2060function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig)
2061{
2062 if (empty ($vip) or $vport <= 0 or empty ($proto))
2063 {
2064 showError ('Invalid arguments', __FUNCTION__);
2065 die;
2066 }
2067 return useInsertBlade
2068 (
2069 'IPVirtualService',
2070 array
2071 (
2072 'vip' => "inet_aton('${vip}')",
2073 'vport' => $vport,
2074 'proto' => "'${proto}'",
2075 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2076 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2077 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2078 )
2079 );
2080}
2081
c1ca768c 2082function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2083{
c1ca768c 2084 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2085 {
2086 showError ('Invalid arguments', __FUNCTION__);
2087 die;
2088 }
2089 return useInsertBlade
2090 (
2091 'IPLoadBalancer',
2092 array
2093 (
2094 'object_id' => $object_id,
2095 'rspool_id' => $pool_id,
c1ca768c 2096 'vs_id' => $vs_id,
3241551e
DO
2097 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2098 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2099 )
ca461127
DO
2100 );
2101}
2102
fb1c4a54
DO
2103function commitDeleteRS ($id = 0)
2104{
2105 if ($id <= 0)
2106 return FALSE;
2107 return useDeleteBlade ('IPRealServer', 'id', $id);
2108}
2109
d6517a21
DO
2110function commitDeleteVS ($id = 0)
2111{
2112 if ($id <= 0)
2113 return FALSE;
2114 return useDeleteBlade ('IPVirtualService', 'id', $id);
2115}
2116
c1ca768c 2117function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2118{
2119 global $dbxlink;
c4d85fd1 2120 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2121 return FALSE;
c1ca768c
DO
2122 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2123 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2124 $result = $dbxlink->exec ($query);
2125 if ($result === NULL)
2126 return FALSE;
2127 elseif ($result != 1)
2128 return FALSE;
2129 else
2130 return TRUE;
2131}
2132
fb1c4a54
DO
2133function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2134{
2135 if ($rsid <= 0 or $rsport <= 0)
2136 {
2137 showError ('Invalid args', __FUNCTION__);
2138 die;
2139 }
2140 if (long2ip (ip2long ($rsip)) !== $rsip)
2141 {
2142 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2143 die;
2144 }
2145 global $dbxlink;
2146 $query =
2147 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2148 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2149 " where id = ${rsid} limit 1";
2150 $result = $dbxlink->query ($query);
2151 if ($result == NULL)
2152 {
2153 showError ("SQL query '${query}' failed", __FUNCTION__);
2154 die;
2155 }
2156 return TRUE;
2157}
2158
c1ca768c 2159function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2160{
c1ca768c 2161 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2162 {
2163 showError ('Invalid args', __FUNCTION__);
2164 die;
2165 }
2166 global $dbxlink;
2167 $query =
2168 "update IPLoadBalancer set vsconfig = " .
2169 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2170 ', rsconfig = ' .
2171 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2172 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2173 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2174 $result = $dbxlink->exec ($query);
2175 if ($result === NULL)
2176 return FALSE;
3241551e
DO
2177 else
2178 return TRUE;
2179}
2180
d6517a21
DO
2181function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2182{
2183 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2184 {
2185 showError ('Invalid args', __FUNCTION__);
2186 die;
2187 }
2188 global $dbxlink;
2189 $query = "update IPVirtualService set " .
2190 "vip = inet_aton('${vip}'), " .
2191 "vport = ${vport}, " .
2192 "proto = '${proto}', " .
2193 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2194 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2195 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2196 " where id = ${vsid} limit 1";
d6517a21
DO
2197 $result = $dbxlink->exec ($query);
2198 if ($result === NULL)
2199 return FALSE;
d6517a21
DO
2200 else
2201 return TRUE;
2202}
2203
e57dca7f 2204// Return the list of virtual services, indexed by vs_id.
70c24883 2205// Each record will be shown with its basic info plus RS pools counter.
996b02ba 2206function getVSList ($tagfilter = array())
e57dca7f 2207{
996b02ba
DO
2208 if (!count ($tagfilter))
2209 $whereclause = '';
2210 else
2211 {
2212 $whereclause = 'where ';
2213 $orclause = '';
2214 foreach ($tagfilter as $tag_id)
2215 {
2216 $whereclause .= $orclause . 'tag_id = ' . $tag_id;
2217 $orclause = ' or ';
2218 }
2219 }
70c24883
DO
2220 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2221 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
996b02ba
DO
2222 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
2223 "${whereclause} group by vs.id order by vs.vip, proto, vport";
e425f895 2224 $result = useSelectBlade ($query);
4b0932b6 2225 $ret = array ();
e57dca7f 2226 while ($row = $result->fetch (PDO::FETCH_ASSOC))
d6517a21 2227 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
4b0932b6 2228 $ret[$row['id']][$cname] = $row[$cname];
e57dca7f 2229 $result->closeCursor();
4b0932b6 2230 return $ret;
e57dca7f
DO
2231}
2232
9a81d416 2233// Return the list of RS pool, indexed by pool id.
2e4170aa 2234function getRSPoolList ($tagfilter = array())
9a81d416 2235{
2e4170aa
DO
2236 if (!count ($tagfilter))
2237 $whereclause = '';
2238 else
2239 {
2240 $whereclause = 'where ';
2241 $orclause = '';
2242 foreach ($tagfilter as $tag_id)
2243 {
2244 $whereclause .= $orclause . 'tag_id = ' . $tag_id;
2245 $orclause = ' or ';
2246 }
2247 }
70c24883
DO
2248 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2249 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2e4170aa
DO
2250 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
2251 "${whereclause} group by pool.id order by pool.id, name";
e425f895 2252 $result = useSelectBlade ($query);
4b0932b6 2253 $ret = array ();
9a81d416 2254 while ($row = $result->fetch (PDO::FETCH_ASSOC))
70c24883 2255 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
4b0932b6 2256 $ret[$row['id']][$cname] = $row[$cname];
9a81d416 2257 $result->closeCursor();
4b0932b6 2258 return $ret;
9a81d416
DO
2259}
2260
5a1680d2
DO
2261function loadThumbCache ($rack_id = 0)
2262{
5a1680d2
DO
2263 $ret = NULL;
2264 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
e425f895 2265 $result = useSelectBlade ($query);
5a1680d2
DO
2266 $row = $result->fetch (PDO::FETCH_ASSOC);
2267 if ($row)
2268 $ret = base64_decode ($row['thumb_data']);
2269 $result->closeCursor();
2270 return $ret;
2271}
2272
2273function saveThumbCache ($rack_id = 0, $cache = NULL)
2274{
2275 global $dbxlink;
2276 if ($rack_id == 0 or $cache == NULL)
2277 {
2278 showError ('Invalid arguments', __FUNCTION__);
2279 return;
2280 }
2281 $data = base64_encode ($cache);
2282 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2283 $result = $dbxlink->exec ($query);
2284}
9a81d416 2285
c7fe33be
DO
2286function resetThumbCache ($rack_id = 0)
2287{
2288 global $dbxlink;
2289 if ($rack_id == 0)
2290 {
2291 showError ('Invalid argument', __FUNCTION__);
2292 return;
2293 }
2294 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2295 $result = $dbxlink->exec ($query);
2296}
2297
748805bf
DO
2298// Return the list of attached RS pools for the given object. As long as we have
2299// the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2300// by vs_id, because there will be only one RS pool listed for each VS of the
2301// current object.
78e7b769
DO
2302function getRSPoolsForObject ($object_id = 0)
2303{
2304 if ($object_id <= 0)
2305 {
2306 showError ('Invalid object_id', __FUNCTION__);
2307 return NULL;
2308 }
748805bf 2309 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2310 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
748805bf
DO
2311 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2312 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2313 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2314 "where lb.object_id = ${object_id} " .
2315 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
e425f895 2316 $result = useSelectBlade ($query);
748805bf 2317 $ret = array ();
78e7b769 2318 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2319 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2320 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2321 $result->closeCursor();
748805bf 2322 return $ret;
78e7b769
DO
2323}
2324
70c24883 2325function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '')
5ad76f01 2326{
5ad76f01
DO
2327 return useInsertBlade
2328 (
2329 'IPRSPool',
2330 array
2331 (
5ad76f01
DO
2332 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2333 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2334 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2335 )
2336 );
2337}
2338
2339function commitDeleteRSPool ($pool_id = 0)
2340{
2341 global $dbxlink;
2342 if ($pool_id <= 0)
2343 return FALSE;
2344 $query = "delete from IPRSPool where id = ${pool_id} limit 1";
2345 $result = $dbxlink->exec ($query);
2346 if ($result === NULL)
2347 return FALSE;
2348 elseif ($result != 1)
2349 return FALSE;
2350 else
2351 return TRUE;
2352}
2353
2354function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2355{
2356 if ($pool_id <= 0)
2357 {
2358 showError ('Invalid arg', __FUNCTION__);
2359 die;
2360 }
2361 global $dbxlink;
2362 $query = "update IPRSPool set " .
2363 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2364 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2365 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2366 " where id = ${pool_id} limit 1";
2367 $result = $dbxlink->exec ($query);
2368 if ($result === NULL)
2369 return FALSE;
2370 elseif ($result != 1)
2371 return FALSE;
2372 else
2373 return TRUE;
2374}
2375
8253d9f0
DO
2376function getRSList ()
2377{
1f7d18fa 2378 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
8253d9f0 2379 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
e425f895 2380 $result = useSelectBlade ($query);
4b0932b6 2381 $ret = array ();
8253d9f0 2382 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2383 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2384 $ret[$row['id']][$cname] = $row[$cname];
2385 $result->closeCursor();
2386 return $ret;
2387}
2388
2389// Return the list of all currently configured load balancers with their pool count.
2390function getLBList ()
2391{
4b0932b6
DO
2392 $query = "select object_id, count(rspool_id) as poolcount " .
2393 "from IPLoadBalancer group by object_id order by object_id";
e425f895 2394 $result = useSelectBlade ($query);
4b0932b6
DO
2395 $ret = array ();
2396 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2397 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2398 $result->closeCursor();
4b0932b6 2399 return $ret;
8253d9f0
DO
2400}
2401
9e677cbd
DO
2402// For the given object return: it vsconfig/rsconfig; the list of RS pools
2403// attached (each with vsconfig/rsconfig in turn), each with the list of
2404// virtual services terminating the pool. Each pool also lists all real
2405// servers with rsconfig.
2406function buildLBConfig ($object_id)
2407{
2408 if ($object_id <= 0)
2409 {
2410 showError ('Invalid arg', __FUNCTION__);
2411 return NULL;
2412 }
9e677cbd 2413 $ret = array();
d91f08f3
DO
2414 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2415 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2416 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2417 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3
DO
2418 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2419 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2420 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
9e677cbd 2421 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2422 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2423 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
e425f895 2424 $result = useSelectBlade ($query);
9e677cbd
DO
2425 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2426 {
d91f08f3
DO
2427 $vs_id = $row['vs_id'];
2428 if (!isset ($ret[$vs_id]))
2429 {
2430 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)
2431 $ret[$vs_id][$c] = $row[$c];
2432 $ret[$vs_id]['rslist'] = array();
2433 }
2434 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2435 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2436 }
2437 $result->closeCursor();
2438 return $ret;
2439}
1f7d18fa
DO
2440
2441function commitSetInService ($rs_id = 0, $inservice = '')
2442{
2443 if ($rs_id <= 0 or empty ($inservice))
2444 {
2445 showError ('Invalid args', __FUNCTION__);
2446 return NULL;
2447 }
2448 global $dbxlink;
2449 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2450 $result = $dbxlink->exec ($query);
2451 if ($result === NULL)
2452 return FALSE;
2453 elseif ($result != 1)
2454 return FALSE;
2455 else
2456 return TRUE;
2457}
2458
ad0e4754
DO
2459function executeAutoPorts ($object_id = 0, $type_id = 0)
2460{
2461 if ($object_id == 0 or $type_id == 0)
2462 {
2463 showError ('Invalid arguments', __FUNCTION__);
2464 die;
2465 }
f3f0161f 2466 $ret = TRUE;
118e4c38 2467 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2468 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2469 return $ret;
ad0e4754
DO
2470}
2471
a6e8d544
DO
2472// Return only implicitly listed tags, the rest of the trail will be
2473// generated/deducted later at higher levels.
f9bc186f 2474function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2475{
f9bc186f
DO
2476 if ($entity_realm == '' or $entity_id <= 0)
2477 {
2478 showError ('Invalid or missing arguments', __FUNCTION__);
2479 return NULL;
2480 }
a6e8d544 2481 $ret = array();
f9bc186f 2482 $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 2483 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2484 $ret[$row['id']] = $row;
a6e8d544
DO
2485 $result->closeCursor();
2486 return $ret;
5967b83d
DO
2487}
2488
f9bc186f
DO
2489function loadRackObjectTags ($id)
2490{
2491 return loadEntityTags ('object', $id);
2492}
2493
2494function loadIPv4PrefixTags ($id)
2495{
2496 return loadEntityTags ('ipv4net', $id);
2497}
2498
41bd8c87
DO
2499function loadRackTags ($id)
2500{
2501 return loadEntityTags ('rack', $id);
2502}
2503
d817ba03
DO
2504function loadIPv4VSTags ($id)
2505{
2506 return loadEntityTags ('ipv4vs', $id);
2507}
2508
2509function loadIPv4RSPoolTags ($id)
2510{
2511 return loadEntityTags ('ipv4rspool', $id);
2512}
2513
5967b83d
DO
2514function getTagList ()
2515{
20c901a7 2516 $ret = array();
5b7bd02e
DO
2517 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2518 "from TagTree left join TagStorage on id = tag_id " .
2519 "group by id, target_realm order by tag";
2520 $result = useSelectBlade ($query);
5967b83d 2521 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2522 {
7cc02fc1 2523 if (!isset ($ret[$row['id']]))
20c901a7 2524 $ret[$row['id']] = array
5b7bd02e
DO
2525 (
2526 'id' => $row['id'],
2527 'tag' => $row['tag'],
2528 'parent_id' => $row['parent_id'],
2529 'refcnt' => array()
2530 );
2531 if ($row['realm'])
20c901a7 2532 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2533 }
5967b83d 2534 $result->closeCursor();
20c901a7 2535 return $ret;
5967b83d
DO
2536}
2537
fe7044ad
DO
2538function commitCreateTag ($tagname = '', $parent_id = 0)
2539{
2540 if ($tagname == '' or $parent_id === 0)
2541 return "Invalid args to " . __FUNCTION__;
2542 $result = useInsertBlade
2543 (
2544 'TagTree',
2545 array
2546 (
2547 'tag' => "'${tagname}'",
2548 'parent_id' => $parent_id
2549 )
2550 );
2551 if ($result)
2552 return '';
2553 else
2554 return "SQL query failed in " . __FUNCTION__;
2555}
2556
2557function commitDestroyTag ($tagid = 0)
2558{
2559 if ($tagid == 0)
2560 return 'Invalid arg to ' . __FUNCTION__;
2561 if (useDeleteBlade ('TagTree', 'id', $tagid, FALSE))
2562 return '';
2563 else
2564 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2565}
f9bc186f
DO
2566
2567function wipeTags ($realm, $id)
2568{
2569 global $dbxlink;
2034d968 2570 $query = "delete from TagStorage where target_realm = '${realm}' and target_id = ${id}";
f9bc186f
DO
2571 $result = $dbxlink->exec ($query);
2572 if ($result === NULL)
2573 return FALSE;
2574 return TRUE;
2575}
2576
e673ee24 2577?>