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