r1989 + mergeSearchResults(): sort search results on SQL server side
[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";
065eeb52 29 $result = useSelectBlade ($query, __FUNCTION__);
489a7502 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";
065eeb52 48 $result = useSelectBlade ($query, __FUNCTION__);
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";
065eeb52 97 $result = useSelectBlade ($query, __FUNCTION__);
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";
065eeb52 130 $result = useSelectBlade ($query, __FUNCTION__);
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";
065eeb52 167 $result = useSelectBlade ($query, __FUNCTION__);
89fa639f 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";
065eeb52 202 $result = useSelectBlade ($query, __FUNCTION__);
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";
065eeb52 286 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
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 332
065eeb52 333 if (($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)) == 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 }
065eeb52 373 $result2 = useSelectBlade ('select last_insert_id()', __FUNCTION__);
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";
065eeb52 527 $result = useSelectBlade ($query, __FUNCTION__);
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}";
065eeb52 544 $result = useSelectBlade ($query, __FUNCTION__);
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";
065eeb52 615 $result = useSelectBlade ($query, __FUNCTION__);
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}";
065eeb52 630 $result = useSelectBlade ($query, __FUNCTION__);
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";
065eeb52 652 $result = useSelectBlade ($query, __FUNCTION__);
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';
065eeb52 682 $result = useSelectBlade ($query, __FUNCTION__);
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';
065eeb52 709 $result = useSelectBlade ($query, __FUNCTION__);
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';
065eeb52 728 $result = useSelectBlade ($query, __FUNCTION__);
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 ";
065eeb52 802 $result = useSelectBlade ($query, __FUNCTION__);
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";
065eeb52 836 $result = useSelectBlade ($query, __FUNCTION__);
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 '';
e673ee24
DO
870}
871
872function unlinkPort ($port)
873{
874 global $dbxlink;
875 $query =
876 "delete from Link where porta='$port' or portb='$port'";
877 $result = $dbxlink->exec ($query);
878 return '';
e673ee24
DO
879}
880
4b2bf583
DO
881// FIXME: after falling back to using existing getObjectInfo we don't
882// need that large query. Shrink it some later.
e673ee24
DO
883function getObjectAddresses ($object_id = 0)
884{
885 if ($object_id == 0)
886 {
f41b492f 887 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
888 return;
889 }
e673ee24
DO
890 $query =
891 "select ".
892 "IPAddress.name as IPAddress_name, ".
893 "IPAddress.reserved as IPAddress_reserved, ".
894 "IPBonds.name as IPBonds_name, ".
895 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
896 "IPBonds.type as IPBonds_type, ".
897 "RemoteBonds.name as RemoteBonds_name, ".
898 "RemoteBonds.type as RemoteBonds_type, ".
899 "RemoteBonds.object_id as RemoteBonds_object_id, ".
900 "RemoteObject.name as RemoteObject_name from IPBonds " .
901 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
902 "and IPBonds.object_id!=RemoteBonds.object_id " .
903 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
904 "left join RackObject as RemoteObject on RemoteBonds.object_id=RemoteObject.id ".
905 "where ".
906 "IPBonds.object_id = ${object_id} ".
907 "order by IPBonds.ip, RemoteObject.name";
065eeb52 908 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
909 $ret=array();
910 $count=0;
911 $refcount=0;
912 $prev_ip = 0;
913 // We are going to call getObjectInfo() for some rows,
914 // hence the connector must be unloaded from the
915 // current data.
916 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
917 $result->closeCursor();
918 foreach ($rows as $row)
e673ee24 919 {
e425f895 920 if ($prev_ip != $row['IPBonds_ip'])
e673ee24 921 {
e425f895
DO
922 $count++;
923 $refcount=0;
924 $prev_ip = $row['IPBonds_ip'];
925 $ret[$count]['address_name'] = $row['IPAddress_name'];
926 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
927 $ret[$count]['ip'] = $row['IPBonds_ip'];
928 $ret[$count]['name'] = $row['IPBonds_name'];
929 $ret[$count]['type'] = $row['IPBonds_type'];
930 $ret[$count]['references'] = array();
931 }
e673ee24 932
e425f895
DO
933 if ($row['RemoteBonds_type'])
934 {
935 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
936 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
937 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
938 if (empty ($row['RemoteBonds_object_id']))
939 $ret[$count]['references'][$refcount]['object_name'] = $row['RemoteObject_name'];
940 else
e673ee24 941 {
e425f895
DO
942 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
943 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
e673ee24 944 }
e425f895 945 $refcount++;
e673ee24
DO
946 }
947 }
e673ee24
DO
948 return $ret;
949}
950
3b6ca088 951function getAddressspaceList ($tagfilter = array())
e673ee24 952{
489a7502 953 $whereclause = getWhereClause ($tagfilter);
e673ee24 954 $query =
0b4c0f17 955 "select distinct ".
e673ee24
DO
956 "id as IPRanges_id, ".
957 "INET_NTOA(ip) as IPRanges_ip, ".
958 "mask as IPRanges_mask, ".
959 "name as IPRanges_name ".
74ccacff 960 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
489a7502 961 "where true ${whereclause} " .
74ccacff 962 " order by ip";
065eeb52 963 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
964 $ret=array();
965 $count=0;
966 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 967 {
e425f895
DO
968 $ret[$count]['id'] = $row['IPRanges_id'];
969 $ret[$count]['ip'] = $row['IPRanges_ip'];
970 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
971 $ret[$count]['name'] = $row['IPRanges_name'];
972 $ret[$count]['mask'] = $row['IPRanges_mask'];
973 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
974 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
975 $count++;
e673ee24
DO
976 }
977 $result->closeCursor();
978 return $ret;
979
980}
981
982function getRangeByIp ($ip = '', $id = 0)
983{
e673ee24
DO
984 if ($id == 0)
985 $query =
986 "select ".
987 "id, INET_NTOA(ip) as ip, mask, name ".
988 "from IPRanges ";
989 else
990 $query =
991 "select ".
992 "id, INET_NTOA(ip) as ip, mask, name ".
993 "from IPRanges where id='$id'";
994
065eeb52 995 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
996 $ret=array();
997 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 998 {
e425f895
DO
999 $binmask=binMaskFromDec($row['mask']);
1000 if ((ip2long($ip) & $binmask) == ip2long($row['ip']))
e673ee24 1001 {
e425f895
DO
1002 $ret['id'] = $row['id'];
1003 $ret['ip'] = $row['ip'];
1004 $ret['ip_bin'] = ip2long($row['ip']);
1005 $ret['name'] = $row['name'];
1006 $ret['mask'] = $row['mask'];
1007 $result->closeCursor();
1008 return $ret;
e673ee24
DO
1009 }
1010 }
1011 $result->closeCursor();
1012 return NULL;
1013}
1014
1015function updateRange ($id=0, $name='')
1016{
1017 global $dbxlink;
1018 $query =
1019 "update IPRanges set name='$name' where id='$id'";
1020 $result = $dbxlink->exec ($query);
1021 return '';
e673ee24
DO
1022}
1023
1024// This function is actually used not only to update, but also to create records,
1025// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1026// (MySQL 4.0 workaround).
b4c1ef87 1027function updateAddress ($ip = 0, $name = '', $reserved = 'no')
e673ee24
DO
1028{
1029 // DELETE may safely fail.
1030 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1031 // INSERT may appear not necessary.
1032 if ($name == '' and $reserved == 'no')
1033 return '';
1034 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1035 return '';
1036 else
b4c1ef87 1037 return __FUNCTION__ . '(): useInsertBlade() failed';
e673ee24
DO
1038}
1039
e673ee24
DO
1040function updateBond ($ip='', $object_id=0, $name='', $type='')
1041{
1042 global $dbxlink;
1043
1044 $query =
1045 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1046 $result = $dbxlink->exec ($query);
1047 return '';
1048}
1049
1050function unbindIpFromObject ($ip='', $object_id=0)
1051{
1052 global $dbxlink;
1053
1054 $query =
1055 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1056 $result = $dbxlink->exec ($query);
1057 return '';
1058}
1059
1060// This function returns either all or one user account. Array key is user name.
ebae41b3 1061function getUserAccounts ($tagfilter = array())
e673ee24 1062{
ebae41b3 1063 $whereclause = getWhereClause ($tagfilter);
e673ee24
DO
1064 $query =
1065 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
ebae41b3
DO
1066 'from UserAccount left join TagStorage ' .
1067 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1068 "where true ${whereclause} " .
1069 'order by user_name';
065eeb52 1070 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1071 $ret = array();
1072 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1073 while ($row = $result->fetch (PDO::FETCH_ASSOC))
64b95774 1074 foreach ($clist as $cname)
e673ee24
DO
1075 $ret[$row['user_name']][$cname] = $row[$cname];
1076 $result->closeCursor();
1077 return $ret;
1078}
1079
e673ee24
DO
1080function searchByl2address ($l2addr)
1081{
e673ee24
DO
1082 $l2addr = l2addressForDatabase ($l2addr);
1083 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1084 "where l2address = ${l2addr}";
065eeb52 1085 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1086 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1087 $result->closeCursor();
1088 if (count ($rows) == 0) // No results.
1089 return NULL;
1090 if (count ($rows) == 1) // Target found.
1091 return $rows[0];
f41b492f 1092 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
e673ee24
DO
1093 return NULL;
1094}
1095
ea5fc465
DO
1096function getIPv4PrefixSearchResult ($terms)
1097{
1098 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1099 $or = '';
1100 foreach (explode (' ', $terms) as $term)
1101 {
1102 $query .= $or . "name like '%${term}%'";
1103 $or = ' or ';
1104 }
065eeb52 1105 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1106 $ret = array();
1107 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1108 $ret[] = $row;
1109 return $ret;
1110}
1111
1112function getIPv4AddressSearchResult ($terms)
1113{
1114 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1115 $or = '';
1116 foreach (explode (' ', $terms) as $term)
1117 {
1118 $query .= $or . "name like '%${term}%'";
1119 $or = ' or ';
1120 }
065eeb52 1121 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1122 $ret = array();
1123 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1124 $ret[] = $row;
1125 return $ret;
1126}
1127
05411ccd
DO
1128function getIPv4RSPoolSearchResult ($terms)
1129{
1130 $query = "select id as pool_id, name from IPRSPool where ";
1131 $or = '';
1132 foreach (explode (' ', $terms) as $term)
1133 {
1134 $query .= $or . "name like '%${term}%'";
1135 $or = ' or ';
1136 }
065eeb52 1137 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1138 $ret = array();
1139 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1140 $ret[] = $row;
1141 return $ret;
1142}
1143
1144function getIPv4VServiceSearchResult ($terms)
1145{
1146 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1147 $or = '';
1148 foreach (explode (' ', $terms) as $term)
1149 {
1150 $query .= $or . "name like '%${term}%'";
1151 $or = ' or ';
1152 }
065eeb52 1153 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1154 $ret = array();
1155 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1156 $ret[] = $row;
1157 return $ret;
1158}
1159
e673ee24
DO
1160// This function returns either port ID or NULL for specified arguments.
1161function getPortID ($object_id, $port_name)
1162{
e673ee24 1163 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
065eeb52 1164 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1165 $rows = $result->fetchAll (PDO::FETCH_NUM);
1166 if (count ($rows) != 1)
1167 return NULL;
1168 $ret = $rows[0][0];
1169 $result->closeCursor();
1170 return $ret;
1171}
1172
1173function commitCreateUserAccount ($username, $realname, $password)
1174{
1175 return useInsertBlade
1176 (
1177 'UserAccount',
1178 array
1179 (
1180 'user_name' => "'${username}'",
1181 'user_realname' => "'${realname}'",
1182 'user_password_hash' => "'${password}'"
1183 )
1184 );
1185}
1186
1187function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1188{
1189 global $dbxlink;
1190 $query =
1191 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1192 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1193 $result = $dbxlink->query ($query);
1194 if ($result == NULL)
1195 {
f41b492f 1196 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1197 die;
1198 }
1199 return TRUE;
1200}
1201
1202function commitEnableUserAccount ($id, $new_enabled_value)
1203{
1204 global $dbxlink;
1205 $query =
1206 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1207 "where user_id = ${id} limit 1";
1208 $result = $dbxlink->query ($query);
1209 if ($result == NULL)
1210 {
f41b492f 1211 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1212 die;
1213 }
1214 return TRUE;
1215}
1216
e673ee24
DO
1217// This function returns an array of all port type pairs from PortCompat table.
1218function getPortCompat ()
1219{
e673ee24
DO
1220 $query =
1221 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1222 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1223 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1224 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1225 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1226 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
065eeb52 1227 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1228 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1229 $result->closeCursor();
1230 return $ret;
1231}
1232
1233function removePortCompat ($type1 = 0, $type2 = 0)
1234{
1235 global $dbxlink;
1236 if ($type1 == 0 or $type2 == 0)
1237 {
f41b492f 1238 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1239 die;
1240 }
1241 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1242 $result = $dbxlink->query ($query);
1243 if ($result == NULL)
1244 {
f41b492f 1245 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1246 die;
1247 }
1248 return TRUE;
1249}
1250
1251function addPortCompat ($type1 = 0, $type2 = 0)
1252{
1253 if ($type1 <= 0 or $type2 <= 0)
1254 {
f41b492f 1255 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1256 die;
1257 }
1258 return useInsertBlade
1259 (
1260 'PortCompat',
1261 array ('type1' => $type1, 'type2' => $type2)
1262 );
1263}
1264
1265// This function returns the dictionary as an array of trees, each tree
1266// representing a single chapter. Each element has 'id', 'name', 'sticky'
1267// and 'word' keys with the latter holding all the words within the chapter.
2dd59b15 1268function getDict ($parse_links = FALSE)
e673ee24 1269{
6bb8e41d 1270 $query1 =
e673ee24
DO
1271 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1272 "Chapter natural left join Dictionary order by chapter_name, dict_value";
065eeb52 1273 $result = useSelectBlade ($query1, __FUNCTION__);
e673ee24 1274 $dict = array();
89fa639f 1275 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
1276 {
1277 $chapter_no = $row['chapter_no'];
1278 if (!isset ($dict[$chapter_no]))
1279 {
1280 $dict[$chapter_no]['no'] = $chapter_no;
1281 $dict[$chapter_no]['name'] = $row['chapter_name'];
1282 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1283 $dict[$chapter_no]['word'] = array();
1284 }
1285 if ($row['dict_key'] != NULL)
6bb8e41d 1286 {
2dd59b15
DO
1287 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1288 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1289 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1290 }
e673ee24 1291 }
89fa639f
DO
1292 $result->closeCursor();
1293 unset ($result);
6bb8e41d
DO
1294// Find the list of all assigned values of dictionary-addressed attributes, each with
1295// chapter/word keyed reference counters. Use the structure to adjust reference counters
1296// of the returned disctionary words.
1297 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1298 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1299 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1300 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1301 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1302 "order by a.attr_id, am.chapter_no, uint_value";
065eeb52 1303 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1304 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1305 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1306 $result->closeCursor();
e673ee24
DO
1307 return $dict;
1308}
1309
da95280e
DO
1310function getDictStats ()
1311{
82f7e2e8 1312 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
da95280e 1313 $query =
5aa28abb
DO
1314 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1315 "Chapter natural left join Dictionary group by Chapter.chapter_no";
065eeb52 1316 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1317 $tc = $tw = $uc = $uw = 0;
89fa639f 1318 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1319 {
1320 $tc++;
1321 $tw += $row['wc'];;
1322 if (in_array ($row['chapter_no'], $stock_chapters))
1323 continue;
1324 $uc++;
1325 $uw += $row['wc'];;
1326 }
89fa639f
DO
1327 $result->closeCursor();
1328 unset ($result);
08b4cb24
DO
1329 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1330 "AttributeValue as av on ro.id = av.object_id group by ro.id";
065eeb52 1331 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1332 $to = $ta = $so = 0;
89fa639f 1333 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1334 {
1335 $to++;
1336 if ($row['attrc'] != 0)
1337 {
1338 $so++;
1339 $ta += $row['attrc'];
1340 }
1341 }
89fa639f 1342 $result->closeCursor();
da95280e
DO
1343 $ret = array();
1344 $ret['Total chapters in dictionary'] = $tc;
1345 $ret['Total words in dictionary'] = $tw;
1346 $ret['User chapters'] = $uc;
1347 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1348 $ret['Total objects'] = $to;
1349 $ret['Objects with stickers'] = $so;
1350 $ret['Total stickers attached'] = $ta;
da95280e
DO
1351 return $ret;
1352}
1353
9ec5fdf1
DO
1354function getIPv4Stats()
1355{
9ec5fdf1
DO
1356 $ret = array();
1357 $subject = array();
1358 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1359 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1360 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1361 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1362 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1363 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1364 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1365 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1366
1367 foreach ($subject as $item)
1368 {
065eeb52 1369 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
1370 $row = $result->fetch (PDO::FETCH_NUM);
1371 $ret[$item['txt']] = $row[0];
1372 $result->closeCursor();
1373 unset ($result);
1374 }
1375 return $ret;
1376}
1377
1378function getRackspaceStats()
1379{
9ec5fdf1
DO
1380 $ret = array();
1381 $subject = array();
1382 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1383 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1384 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1385 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1386
1387 foreach ($subject as $item)
1388 {
065eeb52 1389 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1390 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1391 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1392 $result->closeCursor();
1393 unset ($result);
1394 }
1395 return $ret;
1396}
1397
5bbbeaa2
DO
1398function getTagStats ()
1399{
1400 $ret = array();
1401 $query = "select tag, count(tag_id) as refcnt from " .
1402 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1403 "group by tag_id order by refcnt desc";
065eeb52 1404 $result = useSelectBlade ($query, __FUNCTION__);
5bbbeaa2
DO
1405 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1406 $ret[$row['tag']] = $row['refcnt'];
1407 $result->closeCursor();
1408 return $ret;
1409}
1410
e673ee24
DO
1411function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1412{
1413 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1414 {
f41b492f 1415 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1416 die;
1417 }
1418 global $dbxlink;
1419 $query =
1420 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1421 "and dict_key=${dict_key} limit 1";
1422 $result = $dbxlink->query ($query);
1423 if ($result == NULL)
1424 {
f41b492f 1425 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1426 die;
1427 }
1428 return TRUE;
1429}
1430
1431function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1432{
1433 if ($chapter_no <= 0 or empty ($dict_value))
1434 {
f41b492f 1435 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1436 die;
1437 }
1438 return useInsertBlade
1439 (
1440 'Dictionary',
1441 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1442 );
1443}
1444
1445function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1446{
1447 if ($chapter_no <= 0 or $dict_key <= 0)
1448 {
f41b492f 1449 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1450 die;
1451 }
1452 global $dbxlink;
1453 $query =
1454 "delete from Dictionary where chapter_no=${chapter_no} " .
1455 "and dict_key=${dict_key} limit 1";
1456 $result = $dbxlink->query ($query);
1457 if ($result == NULL)
1458 {
f41b492f 1459 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1460 die;
1461 }
1462 return TRUE;
1463}
1464
1465function commitAddChapter ($chapter_name = '')
1466{
1467 if (empty ($chapter_name))
1468 {
f41b492f 1469 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1470 die;
1471 }
1472 return useInsertBlade
1473 (
1474 'Chapter',
1475 array ('chapter_name' => "'${chapter_name}'")
1476 );
1477}
1478
1479function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1480{
1481 if ($chapter_no <= 0 or empty ($chapter_name))
1482 {
f41b492f 1483 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1484 die;
1485 }
1486 global $dbxlink;
1487 $query =
1488 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1489 "and sticky = 'no' limit 1";
1490 $result = $dbxlink->query ($query);
1491 if ($result == NULL)
1492 {
f41b492f 1493 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1494 die;
1495 }
1496 return TRUE;
1497}
1498
1499function commitDeleteChapter ($chapter_no = 0)
1500{
1501 if ($chapter_no <= 0)
1502 {
f41b492f 1503 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1504 die;
1505 }
1506 global $dbxlink;
1507 $query =
1508 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1509 $result = $dbxlink->query ($query);
1510 if ($result == NULL)
1511 {
f41b492f 1512 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1513 die;
1514 }
1515 return TRUE;
1516}
1517
4c330a14
DO
1518// This is a dictionary accessor. We perform link rendering, so the user sees
1519// nice <select> drop-downs.
e673ee24
DO
1520function readChapter ($chapter_name = '')
1521{
1522 if (empty ($chapter_name))
1523 {
f41b492f 1524 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1525 return NULL;
1526 }
e673ee24
DO
1527 $query =
1528 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1529 "where chapter_name = '${chapter_name}'";
065eeb52 1530 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1531 $chapter = array();
1532 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1533 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1534 $result->closeCursor();
4aa8609b
DO
1535 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1536 asort ($chapter);
e673ee24
DO
1537 return $chapter;
1538}
1539
1540function getAttrMap ()
1541{
e673ee24
DO
1542 $query =
1543 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1544 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1545 "Attribute as a natural left join AttributeMap as am " .
1546 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1547 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1548 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1549 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1550 "order by attr_name";
065eeb52 1551 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1552 $ret = array();
1553 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1554 {
1555 $attr_id = $row['attr_id'];
1556 if (!isset ($ret[$attr_id]))
1557 {
1558 $ret[$attr_id]['id'] = $attr_id;
1559 $ret[$attr_id]['type'] = $row['attr_type'];
1560 $ret[$attr_id]['name'] = $row['attr_name'];
1561 $ret[$attr_id]['application'] = array();
1562 }
1563 if ($row['objtype_id'] == '')
1564 continue;
1565 $application['objtype_id'] = $row['objtype_id'];
1566 $application['objtype_name'] = $row['objtype_name'];
1567 if ($row['attr_type'] == 'dict')
1568 {
1569 $application['chapter_no'] = $row['chapter_no'];
1570 $application['chapter_name'] = $row['chapter_name'];
1571 }
1572 $ret[$attr_id]['application'][] = $application;
1573 }
1574 $result->closeCursor();
1575 return $ret;
1576}
1577
1578function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1579{
1580 if ($attr_id <= 0 or empty ($attr_name))
1581 {
f41b492f 1582 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1583 die;
1584 }
1585 global $dbxlink;
1586 $query =
1587 "update Attribute set attr_name = '${attr_name}' " .
1588 "where attr_id = ${attr_id} limit 1";
1589 $result = $dbxlink->query ($query);
1590 if ($result == NULL)
1591 {
f41b492f 1592 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
1593 die;
1594 }
1595 return TRUE;
1596}
1597
1598function commitAddAttribute ($attr_name = '', $attr_type = '')
1599{
1600 if (empty ($attr_name))
1601 {
f41b492f 1602 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1603 die;
1604 }
1605 switch ($attr_type)
1606 {
1607 case 'uint':
1608 case 'float':
1609 case 'string':
1610 case 'dict':
1611 break;
1612 default:
f41b492f 1613 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1614 die;
1615 }
1616 return useInsertBlade
1617 (
1618 'Attribute',
1619 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1620 );
1621}
1622
1623function commitDeleteAttribute ($attr_id = 0)
1624{
1625 if ($attr_id <= 0)
1626 {
f41b492f 1627 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1628 die;
1629 }
aedf18af 1630 return useDeleteBlade ('Attribute', 'attr_id', $attr_id, FALSE);
e673ee24
DO
1631}
1632
1633// FIXME: don't store garbage in chapter_no for non-dictionary types.
1634function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1635{
1636 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1637 {
f41b492f 1638 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1639 die;
1640 }
1641 return useInsertBlade
1642 (
1643 'AttributeMap',
1644 array
1645 (
1646 'attr_id' => $attr_id,
1647 'objtype_id' => $objtype_id,
1648 'chapter_no' => $chapter_no
1649 )
1650 );
1651}
1652
1653function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1654{
1655 if ($attr_id <= 0 or $objtype_id <= 0)
1656 {
f41b492f 1657 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1658 die;
1659 }
1660 global $dbxlink;
1661 $query =
1662 "delete from AttributeMap where attr_id=${attr_id} " .
1663 "and objtype_id=${objtype_id} limit 1";
1664 $result = $dbxlink->query ($query);
1665 if ($result == NULL)
1666 {
f41b492f 1667 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1668 die;
1669 }
1670 return TRUE;
1671}
1672
1673// This function returns all optional attributes for requested object
1674// as an array of records. NULL is returned on error and empty array
1675// is returned, if there are no attributes found.
24cbe8af 1676function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
1677{
1678 if ($object_id <= 0)
1679 {
f41b492f 1680 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
1681 return NULL;
1682 }
e673ee24
DO
1683 $ret = array();
1684 $query =
1685 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1686 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1687 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1688 "inner join Attribute as A using (attr_id) " .
1689 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1690 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1691 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1a576609 1692 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
065eeb52 1693 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1694 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1695 {
1696 $record = array();
1697 $record['id'] = $row['attr_id'];
1698 $record['name'] = $row['attr_name'];
1699 $record['type'] = $row['attr_type'];
1700 switch ($row['attr_type'])
1701 {
1702 case 'uint':
1703 case 'float':
1704 case 'string':
24cbe8af
DO
1705 $record['value'] = $row[$row['attr_type'] . '_value'];
1706 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1707 break;
e673ee24 1708 case 'dict':
24cbe8af
DO
1709 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1710 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
1711 $record['chapter_name'] = $row['chapter_name'];
1712 $record['key'] = $row['uint_value'];
1713 break;
1714 default:
1715 $record['value'] = NULL;
1716 break;
1717 }
1718 $ret[$row['attr_id']] = $record;
1719 }
1720 $result->closeCursor();
1721 return $ret;
1722}
1723
1724function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1725{
1726 if ($object_id <= 0 or $attr_id <= 0)
1727 {
f41b492f 1728 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1729 die;
1730 }
1731 global $dbxlink;
1732 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1733 $result = $dbxlink->query ($query);
1734 if ($result == NULL)
1735 {
f41b492f 1736 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1737 die;
1738 }
1739 return TRUE;
1740}
1741
1742// FIXME: don't share common code with use commitResetAttrValue()
1743function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1744{
1745 if ($object_id <= 0 or $attr_id <= 0)
1746 {
f41b492f 1747 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1748 die;
1749 }
1750 if (empty ($value))
1751 return commitResetAttrValue ($object_id, $attr_id);
1752 global $dbxlink;
1753 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1754 $result = $dbxlink->query ($query1);
1755 if ($result == NULL)
1756 {
f41b492f 1757 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
1758 die;
1759 }
1760 $row = $result->fetch (PDO::FETCH_NUM);
1761 if ($row == NULL)
1762 {
f41b492f 1763 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
1764 die;
1765 }
1766 $attr_type = $row[0];
1767 $result->closeCursor();
1768 switch ($attr_type)
1769 {
1770 case 'uint':
1771 case 'float':
1772 case 'string':
1773 $column = $attr_type . '_value';
1774 break;
1775 case 'dict':
1776 $column = 'uint_value';
1777 break;
1778 default:
f41b492f 1779 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
1780 die;
1781 }
1782 $query2 =
1783 "delete from AttributeValue where " .
1784 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1785 $result = $dbxlink->query ($query2);
1786 if ($result == NULL)
1787 {
f41b492f 1788 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
1789 die;
1790 }
1791 // We know $value isn't empty here.
1792 $query3 =
1793 "insert into AttributeValue set ${column} = '${value}', " .
1794 "object_id = ${object_id}, attr_id = ${attr_id} ";
1795 $result = $dbxlink->query ($query3);
1796 if ($result == NULL)
1797 {
f41b492f 1798 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
1799 die;
1800 }
1801 return TRUE;
1802}
1803
1804function commitUseupPort ($port_id = 0)
1805{
1806 if ($port_id <= 0)
1807 {
f41b492f 1808 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
1809 die;
1810 }
1811 global $dbxlink;
1812 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
1813 $result = $dbxlink->exec ($query);
1814 if ($result == NULL)
1815 {
f41b492f 1816 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
1817 die;
1818 }
1819 return TRUE;
1820
1821}
1822
1823// This is a swiss-knife blade to insert a record into a table.
1824// The first argument is table name.
1825// The second argument is an array of "name" => "value" pairs.
1826// The function returns either TRUE or FALSE (we expect one row
1827// to be inserted).
1828function useInsertBlade ($tablename, $values)
1829{
1830 global $dbxlink;
1831 $namelist = $valuelist = '';
1832 foreach ($values as $name => $value)
1833 {
1834 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
1835 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
1836 }
1837 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
1838 $result = $dbxlink->exec ($query);
1839 if ($result != 1)
1840 return FALSE;
1841 return TRUE;
1842}
1843
1844// This swiss-knife blade deletes one record from the specified table
1845// using the specified key name and value.
fe7044ad 1846function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
e673ee24
DO
1847{
1848 global $dbxlink;
1849 if ($quotekey == TRUE)
fe7044ad
DO
1850 $keyvalue = "'${keyvalue}'";
1851 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
1852 if (!$deleteall)
1853 $query .= ' limit 1';
e673ee24
DO
1854 $result = $dbxlink->exec ($query);
1855 if ($result === NULL)
1856 return FALSE;
aedf18af 1857 elseif (!$deleteall && $result != 1)
e673ee24
DO
1858 return FALSE;
1859 else
1860 return TRUE;
1861}
1862
5967b83d
DO
1863function useSelectBlade ($query, $caller = 'N/A')
1864{
1865 global $dbxlink;
1866 $result = $dbxlink->query ($query);
1867 if ($result == NULL)
1868 {
1869 $ei = $dbxlink->errorInfo();
105a3bc8 1870 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
1871 return NULL;
1872 }
1873 return $result;
1874}
1875
9c0b0016
DO
1876function loadConfigCache ()
1877{
4fe32e78 1878 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 1879 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
1880 $cache = array();
1881 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1882 $cache[$row['varname']] = $row;
1883 $result->closeCursor();
1884 return $cache;
1885}
1886
1887// setConfigVar() is expected to perform all necessary filtering
1888function storeConfigVar ($varname = NULL, $varvalue = NULL)
1889{
c461c579 1890 global $dbxlink;
bb6b9880 1891 if (empty ($varname) || $varvalue === NULL)
9c0b0016 1892 {
f41b492f 1893 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
1894 return FALSE;
1895 }
1896 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
1897 $result = $dbxlink->query ($query);
1898 if ($result == NULL)
1899 {
f41b492f 1900 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
1901 return FALSE;
1902 }
1903 $rc = $result->rowCount();
1904 $result->closeCursor();
f7ee57a1 1905 if ($rc == 0 or $rc == 1)
9c0b0016 1906 return TRUE;
f41b492f 1907 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
1908 return FALSE;
1909}
1910
fbbb74fb
DO
1911// Database version detector. Should behave corretly on any
1912// working dataset a user might have.
1913function getDatabaseVersion ()
1914{
1915 global $dbxlink;
1916 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
1917 $result = $dbxlink->query ($query);
1918 if ($result == NULL)
1919 {
1920 $errorInfo = $dbxlink->errorInfo();
1921 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
1922 return '0.14.4';
4d2e93f2 1923 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
1924 }
1925 $rows = $result->fetchAll (PDO::FETCH_NUM);
1926 if (count ($rows) != 1 || empty ($rows[0][0]))
1927 {
1928 $result->closeCursor();
4d2e93f2 1929 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
1930 }
1931 $ret = $rows[0][0];
1932 $result->closeCursor();
1933 return $ret;
1934}
1935
da04825a
DO
1936// Return an array of virtual services. For each of them list real server pools
1937// with their load balancers and other stats.
62a1dcb5
DO
1938function getSLBSummary ()
1939{
6fec9f39
DO
1940 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
1941 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
1942 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
3e56d972 1943 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
6fec9f39
DO
1944 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
1945 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 1946 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
1947 $ret = array();
1948 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1949 {
4cadac8f 1950 $vsid = $row['vsid'];
da04825a 1951 $object_id = $row['object_id'];
4cadac8f
DO
1952 if (!isset ($ret[$vsid]))
1953 {
1954 $ret[$vsid] = array();
13bffb29 1955 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 1956 $ret[$vsid][$cname] = $row[$cname];
da04825a 1957 $ret[$vsid]['lblist'] = array();
4cadac8f 1958 }
6fec9f39
DO
1959 // There's only one assigned RS pool possible for each LB-VS combination.
1960 $ret[$vsid]['lblist'][$row['object_id']] = array
1961 (
1962 'id' => $row['rspool_id'],
1963 'size' => $row['rscount'],
1964 'name' => $row['pool_name']
1965 );
c3bdc503 1966 }
060ba26e 1967 $result->closeCursor();
c3bdc503 1968 return $ret;
62a1dcb5
DO
1969}
1970
da04825a
DO
1971// Get the detailed composition of a particular virtual service, namely the list
1972// of all pools, each shown with the list of objects servicing it. VS/RS configs
1973// will be returned as well.
060ba26e
DO
1974function getVServiceInfo ($vsid = 0)
1975{
2b4eee17
DO
1976 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
1977 "from IPVirtualService where id = ${vsid}";
065eeb52 1978 $result = useSelectBlade ($query1, __FUNCTION__);
060ba26e 1979 $vsinfo = array ();
89fa639f 1980 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
1981 if (!$row)
1982 return NULL;
1983 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
1984 $vsinfo[$cname] = $row[$cname];
1985 $vsinfo['rspool'] = array();
89fa639f
DO
1986 $result->closeCursor();
1987 unset ($result);
2b4eee17
DO
1988 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
1989 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
1990 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
1991 "where vs_id = ${vsid} order by pool.name, object_id";
065eeb52 1992 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1993 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 1994 {
2b4eee17 1995 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 1996 {
2b4eee17
DO
1997 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
1998 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
1999 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2000 $vsinfo['rspool'][$row['id']]['lblist'] = array();
060ba26e 2001 }
2b4eee17
DO
2002 if ($row['object_id'] == NULL)
2003 continue;
2004 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2005 (
2006 'vsconfig' => $row['lb_vsconfig'],
2007 'rsconfig' => $row['lb_rsconfig']
2008 );
060ba26e 2009 }
89fa639f 2010 $result->closeCursor();
060ba26e
DO
2011 return $vsinfo;
2012}
2013
71b8bda1
DO
2014// Collect and return the following info about the given real server pool:
2015// basic information
2016// parent virtual service information
c1ca768c 2017// load balancers list (each with a list of VSes)
71b8bda1
DO
2018// real servers list
2019
2020function getRSPoolInfo ($id = 0)
2021{
c1ca768c 2022 $query1 = "select id, name, vsconfig, rsconfig from " .
481a7f8b 2023 "IPRSPool where id = ${id}";
065eeb52 2024 $result = useSelectBlade ($query1, __FUNCTION__);
71b8bda1 2025 $ret = array();
89fa639f 2026 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2027 if (!$row)
2028 return NULL;
70c24883 2029 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2030 $ret[$c] = $row[$c];
89fa639f
DO
2031 $result->closeCursor();
2032 unset ($result);
71b8bda1
DO
2033 $ret['lblist'] = array();
2034 $ret['rslist'] = array();
1519d6fa
DO
2035 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2036 "where rspool_id = ${id} order by object_id, vs_id";
065eeb52 2037 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2038 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2039 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2040 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2041 $result->closeCursor();
2042 unset ($result);
1f7d18fa 2043 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
676a8268 2044 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
065eeb52 2045 $result = useSelectBlade ($query3, __FUNCTION__);
89fa639f 2046 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2047 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2048 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2049 $result->closeCursor();
71b8bda1
DO
2050 return $ret;
2051}
2052
7e7a8387 2053function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127
DO
2054{
2055 if ($pool_id <= 0 or $rsport <= 0)
2056 {
2057 showError ('Invalid arguments', __FUNCTION__);
2058 die;
2059 }
ca461127
DO
2060 return useInsertBlade
2061 (
2062 'IPRealServer',
2063 array
2064 (
2065 'rsip' => "inet_aton('${rsip}')",
2066 'rsport' => $rsport,
2067 'rspool_id' => $pool_id,
bcbeadb4 2068 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2069 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2070 )
2071 );
2072}
2073
d6517a21
DO
2074function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig)
2075{
2076 if (empty ($vip) or $vport <= 0 or empty ($proto))
2077 {
2078 showError ('Invalid arguments', __FUNCTION__);
2079 die;
2080 }
2081 return useInsertBlade
2082 (
2083 'IPVirtualService',
2084 array
2085 (
2086 'vip' => "inet_aton('${vip}')",
2087 'vport' => $vport,
2088 'proto' => "'${proto}'",
2089 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2090 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2091 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2092 )
2093 );
2094}
2095
c1ca768c 2096function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2097{
c1ca768c 2098 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2099 {
2100 showError ('Invalid arguments', __FUNCTION__);
2101 die;
2102 }
2103 return useInsertBlade
2104 (
2105 'IPLoadBalancer',
2106 array
2107 (
2108 'object_id' => $object_id,
2109 'rspool_id' => $pool_id,
c1ca768c 2110 'vs_id' => $vs_id,
3241551e
DO
2111 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2112 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2113 )
ca461127
DO
2114 );
2115}
2116
fb1c4a54
DO
2117function commitDeleteRS ($id = 0)
2118{
2119 if ($id <= 0)
2120 return FALSE;
aedf18af 2121 return useDeleteBlade ('IPRealServer', 'id', $id, FALSE);
fb1c4a54
DO
2122}
2123
d6517a21
DO
2124function commitDeleteVS ($id = 0)
2125{
2126 if ($id <= 0)
2127 return FALSE;
aedf18af 2128 return useDeleteBlade ('IPVirtualService', 'id', $id, FALSE) && deleteTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2129}
2130
c1ca768c 2131function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2132{
2133 global $dbxlink;
c4d85fd1 2134 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2135 return FALSE;
c1ca768c
DO
2136 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2137 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2138 $result = $dbxlink->exec ($query);
2139 if ($result === NULL)
2140 return FALSE;
2141 elseif ($result != 1)
2142 return FALSE;
2143 else
2144 return TRUE;
2145}
2146
fb1c4a54
DO
2147function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2148{
2149 if ($rsid <= 0 or $rsport <= 0)
2150 {
2151 showError ('Invalid args', __FUNCTION__);
2152 die;
2153 }
2154 if (long2ip (ip2long ($rsip)) !== $rsip)
2155 {
2156 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2157 die;
2158 }
2159 global $dbxlink;
2160 $query =
2161 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2162 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2163 " where id = ${rsid} limit 1";
2164 $result = $dbxlink->query ($query);
2165 if ($result == NULL)
2166 {
2167 showError ("SQL query '${query}' failed", __FUNCTION__);
2168 die;
2169 }
2170 return TRUE;
2171}
2172
c1ca768c 2173function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2174{
c1ca768c 2175 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2176 {
2177 showError ('Invalid args', __FUNCTION__);
2178 die;
2179 }
2180 global $dbxlink;
2181 $query =
2182 "update IPLoadBalancer set vsconfig = " .
2183 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2184 ', rsconfig = ' .
2185 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2186 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2187 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2188 $result = $dbxlink->exec ($query);
2189 if ($result === NULL)
2190 return FALSE;
3241551e
DO
2191 else
2192 return TRUE;
2193}
2194
d6517a21
DO
2195function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2196{
2197 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2198 {
2199 showError ('Invalid args', __FUNCTION__);
2200 die;
2201 }
2202 global $dbxlink;
2203 $query = "update IPVirtualService set " .
2204 "vip = inet_aton('${vip}'), " .
2205 "vport = ${vport}, " .
2206 "proto = '${proto}', " .
2207 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2208 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2209 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2210 " where id = ${vsid} limit 1";
d6517a21
DO
2211 $result = $dbxlink->exec ($query);
2212 if ($result === NULL)
2213 return FALSE;
d6517a21
DO
2214 else
2215 return TRUE;
2216}
2217
e57dca7f 2218// Return the list of virtual services, indexed by vs_id.
70c24883 2219// Each record will be shown with its basic info plus RS pools counter.
996b02ba 2220function getVSList ($tagfilter = array())
e57dca7f 2221{
489a7502 2222 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2223 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2224 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
996b02ba 2225 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
83d3dde9 2226 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
065eeb52 2227 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2228 $ret = array ();
e57dca7f 2229 while ($row = $result->fetch (PDO::FETCH_ASSOC))
d6517a21 2230 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
4b0932b6 2231 $ret[$row['id']][$cname] = $row[$cname];
e57dca7f 2232 $result->closeCursor();
4b0932b6 2233 return $ret;
e57dca7f
DO
2234}
2235
9a81d416 2236// Return the list of RS pool, indexed by pool id.
2e4170aa 2237function getRSPoolList ($tagfilter = array())
9a81d416 2238{
489a7502 2239 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2240 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2241 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2e4170aa 2242 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
83d3dde9 2243 "where true ${whereclause} group by pool.id order by pool.id, name";
065eeb52 2244 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2245 $ret = array ();
9a81d416 2246 while ($row = $result->fetch (PDO::FETCH_ASSOC))
70c24883 2247 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
4b0932b6 2248 $ret[$row['id']][$cname] = $row[$cname];
9a81d416 2249 $result->closeCursor();
4b0932b6 2250 return $ret;
9a81d416
DO
2251}
2252
5a1680d2
DO
2253function loadThumbCache ($rack_id = 0)
2254{
5a1680d2
DO
2255 $ret = NULL;
2256 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2257 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2258 $row = $result->fetch (PDO::FETCH_ASSOC);
2259 if ($row)
2260 $ret = base64_decode ($row['thumb_data']);
2261 $result->closeCursor();
2262 return $ret;
2263}
2264
2265function saveThumbCache ($rack_id = 0, $cache = NULL)
2266{
2267 global $dbxlink;
2268 if ($rack_id == 0 or $cache == NULL)
2269 {
2270 showError ('Invalid arguments', __FUNCTION__);
2271 return;
2272 }
2273 $data = base64_encode ($cache);
2274 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2275 $result = $dbxlink->exec ($query);
2276}
9a81d416 2277
c7fe33be
DO
2278function resetThumbCache ($rack_id = 0)
2279{
2280 global $dbxlink;
2281 if ($rack_id == 0)
2282 {
2283 showError ('Invalid argument', __FUNCTION__);
2284 return;
2285 }
2286 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2287 $result = $dbxlink->exec ($query);
2288}
2289
748805bf
DO
2290// Return the list of attached RS pools for the given object. As long as we have
2291// the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2292// by vs_id, because there will be only one RS pool listed for each VS of the
2293// current object.
78e7b769
DO
2294function getRSPoolsForObject ($object_id = 0)
2295{
2296 if ($object_id <= 0)
2297 {
2298 showError ('Invalid object_id', __FUNCTION__);
2299 return NULL;
2300 }
748805bf 2301 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2302 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
748805bf
DO
2303 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2304 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2305 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2306 "where lb.object_id = ${object_id} " .
2307 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2308 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2309 $ret = array ();
78e7b769 2310 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2311 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2312 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2313 $result->closeCursor();
748805bf 2314 return $ret;
78e7b769
DO
2315}
2316
70c24883 2317function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '')
5ad76f01 2318{
5ad76f01
DO
2319 return useInsertBlade
2320 (
2321 'IPRSPool',
2322 array
2323 (
5ad76f01
DO
2324 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2325 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2326 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2327 )
2328 );
2329}
2330
2331function commitDeleteRSPool ($pool_id = 0)
2332{
2333 global $dbxlink;
2334 if ($pool_id <= 0)
2335 return FALSE;
aedf18af 2336 return useDeleteBlade ('IPRSPool', 'id', $pool_id, FALSE) && deleteTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2337}
2338
2339function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2340{
2341 if ($pool_id <= 0)
2342 {
2343 showError ('Invalid arg', __FUNCTION__);
2344 die;
2345 }
2346 global $dbxlink;
2347 $query = "update IPRSPool set " .
2348 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2349 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2350 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2351 " where id = ${pool_id} limit 1";
2352 $result = $dbxlink->exec ($query);
2353 if ($result === NULL)
2354 return FALSE;
2355 elseif ($result != 1)
2356 return FALSE;
2357 else
2358 return TRUE;
2359}
2360
8253d9f0
DO
2361function getRSList ()
2362{
1f7d18fa 2363 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
8253d9f0 2364 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
065eeb52 2365 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2366 $ret = array ();
8253d9f0 2367 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2368 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2369 $ret[$row['id']][$cname] = $row[$cname];
2370 $result->closeCursor();
2371 return $ret;
2372}
2373
2374// Return the list of all currently configured load balancers with their pool count.
2375function getLBList ()
2376{
4b0932b6
DO
2377 $query = "select object_id, count(rspool_id) as poolcount " .
2378 "from IPLoadBalancer group by object_id order by object_id";
065eeb52 2379 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2380 $ret = array ();
2381 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2382 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2383 $result->closeCursor();
4b0932b6 2384 return $ret;
8253d9f0
DO
2385}
2386
9e677cbd
DO
2387// For the given object return: it vsconfig/rsconfig; the list of RS pools
2388// attached (each with vsconfig/rsconfig in turn), each with the list of
2389// virtual services terminating the pool. Each pool also lists all real
2390// servers with rsconfig.
2391function buildLBConfig ($object_id)
2392{
2393 if ($object_id <= 0)
2394 {
2395 showError ('Invalid arg', __FUNCTION__);
2396 return NULL;
2397 }
9e677cbd 2398 $ret = array();
d91f08f3
DO
2399 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2400 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2401 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2402 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3
DO
2403 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2404 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2405 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
9e677cbd 2406 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2407 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2408 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2409 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2410 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2411 {
d91f08f3
DO
2412 $vs_id = $row['vs_id'];
2413 if (!isset ($ret[$vs_id]))
2414 {
2415 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)
2416 $ret[$vs_id][$c] = $row[$c];
2417 $ret[$vs_id]['rslist'] = array();
2418 }
2419 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2420 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2421 }
2422 $result->closeCursor();
2423 return $ret;
2424}
1f7d18fa
DO
2425
2426function commitSetInService ($rs_id = 0, $inservice = '')
2427{
2428 if ($rs_id <= 0 or empty ($inservice))
2429 {
2430 showError ('Invalid args', __FUNCTION__);
2431 return NULL;
2432 }
2433 global $dbxlink;
2434 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2435 $result = $dbxlink->exec ($query);
2436 if ($result === NULL)
2437 return FALSE;
2438 elseif ($result != 1)
2439 return FALSE;
2440 else
2441 return TRUE;
2442}
2443
ad0e4754
DO
2444function executeAutoPorts ($object_id = 0, $type_id = 0)
2445{
2446 if ($object_id == 0 or $type_id == 0)
2447 {
2448 showError ('Invalid arguments', __FUNCTION__);
2449 die;
2450 }
f3f0161f 2451 $ret = TRUE;
118e4c38 2452 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2453 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2454 return $ret;
ad0e4754
DO
2455}
2456
a6e8d544
DO
2457// Return only implicitly listed tags, the rest of the trail will be
2458// generated/deducted later at higher levels.
f9bc186f 2459function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2460{
f9bc186f
DO
2461 if ($entity_realm == '' or $entity_id <= 0)
2462 {
2463 showError ('Invalid or missing arguments', __FUNCTION__);
2464 return NULL;
2465 }
a6e8d544 2466 $ret = array();
065eeb52 2467 $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}", __FUNCTION__);
5967b83d 2468 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2469 $ret[$row['id']] = $row;
a6e8d544
DO
2470 $result->closeCursor();
2471 return $ret;
5967b83d
DO
2472}
2473
f9bc186f
DO
2474function loadRackObjectTags ($id)
2475{
2476 return loadEntityTags ('object', $id);
2477}
2478
2479function loadIPv4PrefixTags ($id)
2480{
2481 return loadEntityTags ('ipv4net', $id);
2482}
2483
41bd8c87
DO
2484function loadRackTags ($id)
2485{
2486 return loadEntityTags ('rack', $id);
2487}
2488
d817ba03
DO
2489function loadIPv4VSTags ($id)
2490{
2491 return loadEntityTags ('ipv4vs', $id);
2492}
2493
2494function loadIPv4RSPoolTags ($id)
2495{
2496 return loadEntityTags ('ipv4rspool', $id);
2497}
2498
ebae41b3
DO
2499function loadUserTags ($user_id)
2500{
2501 return loadEntityTags ('user', $user_id);
2502}
2503
5967b83d
DO
2504function getTagList ()
2505{
20c901a7 2506 $ret = array();
5b7bd02e
DO
2507 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2508 "from TagTree left join TagStorage on id = tag_id " .
2509 "group by id, target_realm order by tag";
065eeb52 2510 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2511 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2512 {
7cc02fc1 2513 if (!isset ($ret[$row['id']]))
20c901a7 2514 $ret[$row['id']] = array
5b7bd02e
DO
2515 (
2516 'id' => $row['id'],
2517 'tag' => $row['tag'],
2518 'parent_id' => $row['parent_id'],
2519 'refcnt' => array()
2520 );
2521 if ($row['realm'])
20c901a7 2522 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2523 }
5967b83d 2524 $result->closeCursor();
20c901a7 2525 return $ret;
5967b83d
DO
2526}
2527
fe7044ad
DO
2528function commitCreateTag ($tagname = '', $parent_id = 0)
2529{
2530 if ($tagname == '' or $parent_id === 0)
2531 return "Invalid args to " . __FUNCTION__;
2532 $result = useInsertBlade
2533 (
2534 'TagTree',
2535 array
2536 (
2537 'tag' => "'${tagname}'",
2538 'parent_id' => $parent_id
2539 )
2540 );
2541 if ($result)
2542 return '';
2543 else
2544 return "SQL query failed in " . __FUNCTION__;
2545}
2546
2547function commitDestroyTag ($tagid = 0)
2548{
2549 if ($tagid == 0)
2550 return 'Invalid arg to ' . __FUNCTION__;
2551 if (useDeleteBlade ('TagTree', 'id', $tagid, FALSE))
2552 return '';
2553 else
2554 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2555}
f9bc186f 2556
49fb1027 2557function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2558{
49fb1027
DO
2559 if ($parent_id == 0)
2560 $parent_id = 'NULL';
f9bc186f 2561 global $dbxlink;
49fb1027
DO
2562 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2563 "where id = ${tag_id} limit 1";
f9bc186f
DO
2564 $result = $dbxlink->exec ($query);
2565 if ($result === NULL)
49fb1027
DO
2566 return 'SQL query failed in ' . __FUNCTION__;
2567 return '';
f9bc186f
DO
2568}
2569
aedf18af
DO
2570function deleteTagsForEntity ($entity_realm, $entity_id)
2571{
2572 global $dbxlink;
2573 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2574 $result = $dbxlink->exec ($query);
2575 if ($result === NULL)
2576 return FALSE;
2577 else
2578 return TRUE;
2579}
2580
eb6ea26f
DO
2581function addTagForEntity ($realm, $entity_id, $tag_id)
2582{
2583 return useInsertBlade
2584 (
2585 'TagStorage',
2586 array
2587 (
2588 'target_realm' => "'${realm}'",
2589 'target_id' => $entity_id,
2590 'tag_id' => $tag_id,
2591 )
2592 );
2593}
2594
42023f03
DO
2595function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2596{
2597 // $range is in x.x.x.x/x format, split into ip/mask vars
2598 $rangeArray = explode('/', $range);
2599 if (count ($rangeArray) != 2)
2600 return "Invalid IPv4 prefix '${range}'";
2601 $ip = $rangeArray[0];
2602 $mask = $rangeArray[1];
2603
2604 if (empty ($ip) or empty ($mask))
2605 return "Invalid IPv4 prefix '${range}'";
2606 $ipL = ip2long($ip);
2607 $maskL = ip2long($mask);
2608 if ($ipL == -1 || $ipL === FALSE)
2609 return 'Bad IPv4 address';
2610 if ($mask < 32 && $mask > 0)
2611 $maskL = $mask;
2612 else
2613 {
2614 $maskB = decbin($maskL);
2615 if (strlen($maskB)!=32)
2616 return 'Invalid netmask';
2617 $ones=0;
2618 $zeroes=FALSE;
2619 foreach( str_split ($maskB) as $digit)
2620 {
2621 if ($digit == '0')
2622 $zeroes = TRUE;
2623 if ($digit == '1')
2624 {
2625 $ones++;
2626 if ($zeroes == TRUE)
2627 return 'Invalid netmask';
2628 }
2629 }
2630 $maskL = $ones;
2631 }
2632 $binmask = binMaskFromDec($maskL);
2633 $ipL = $ipL & $binmask;
2634
2635 $query =
2636 "select ".
2637 "id, ip, mask, name ".
2638 "from IPRanges ";
2639
065eeb52 2640 $result = useSelectBlade ($query, __FUNCTION__);
42023f03
DO
2641
2642 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2643 {
2644 $otherip = $row['ip'];
2645 $othermask = binMaskFromDec($row['mask']);
2646 if (($otherip & $othermask) == ($ipL & $othermask))
2647 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2648 if (($otherip & $binmask) == ($ipL & $binmask))
2649 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2650 }
2651 $result->closeCursor();
2652 unset ($result);
2653 $result = useInsertBlade
2654 (
2655 'IPRanges',
2656 array
2657 (
2658 'ip' => sprintf ('%u', $ipL),
2659 'mask' => "'${maskL}'",
2660 'name' => "'${name}'"
2661 )
2662 );
2663
2664 if ($is_bcast and $maskL < 31)
2665 {
2666 $network_addr = long2ip ($ipL);
2667 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2668 updateAddress ($network_addr, 'network', 'yes');
2669 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2670 }
2671 if (!count ($taglist))
2672 return '';
065eeb52 2673 if (($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)) == NULL)
42023f03
DO
2674 return 'Query #3 failed in ' . __FUNCTION__;
2675 $row = $result->fetch (PDO::FETCH_NUM);
2676 $last_insert_id = $row[0];
2677 $result->closeCursor();
2678 unset ($result);
2679 $errcount = 0;
2680 foreach ($taglist as $tag_id)
2681 if (addTagForEntity ('ipv4net', $last_insert_id, $tag_id) == FALSE)
2682 $errcount++;
2683 if (!$errcount)
2684 return '';
2685 else
2686 return "Experienced ${errcount} errors adding tags for the IPv4 prefix";
2687}
2688
2689// FIXME: This function doesn't wipe relevant records from IPAddress table.
2690function destroyIPv4Prefix ($id = 0)
2691{
2692 if ($id <= 0)
2693 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
2694 if (!useDeleteBlade ('IPRanges', 'id', $id, FALSE))
2695 return __FUNCTION__ . ': SQL query #1 failed';
2696 if (!deleteTagsForEntity ('ipv4net', $id))
2697 return __FUNCTION__ . ': SQL query #2 failed';
2698 return '';
2699}
2700
ebae41b3
DO
2701function loadScript ($name)
2702{
2703 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
2704 $row = $result->fetch (PDO::FETCH_NUM);
2705 return $row[0];
2706}
2707
2708function saveScript ($name, $text)
2709{
2710 if (empty ($name))
2711 {
2712 showError ('Invalid argument');
2713 return FALSE;
2714 }
2715 return useDeleteBlade ('Script', 'script_name', $name, TRUE) && useInsertBlade
2716 (
2717 'Script',
2718 array
2719 (
2720 'script_name' => "'${name}'",
2721 'script_text' => "'${text}'"
2722 )
2723 );
2724}
2725
2726function saveUserPassword ($user_id, $newp)
bcd37231 2727{
ebae41b3
DO
2728 $newhash = hash (PASSWORD_HASH, $newp);
2729 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
bcd37231
DO
2730}
2731
e673ee24 2732?>