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