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