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