r2225 - use MAXSELSIZE, where it wasn't yet
[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{
b614498d 10 $ret = htmlspecialchars ($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
11c8e4be 19function getRackspace ($tagfilter = array(), $tfmode = 'any')
489a7502 20{
81736ac1 21 $whereclause = getWhereClause ($tagfilter);
489a7502 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.
81736ac1 64function getWhereClause ($tagfilter = array())
e673ee24 65{
105cea6e 66 $whereclause = '';
105cea6e 67 if (count ($tagfilter))
7cc02fc1 68 {
105cea6e 69 $whereclause .= ' and (';
11c8e4be 70 $conj = '';
7cc02fc1
DO
71 foreach ($tagfilter as $tag_id)
72 {
11c8e4be 73 $whereclause .= $conj . 'tag_id = ' . $tag_id;
81736ac1 74 $conj = ' or ';
7cc02fc1
DO
75 }
76 $whereclause .= ') ';
77 }
489a7502
DO
78 return $whereclause;
79}
80
e9132485
DO
81// Return a simple object list w/o related information.
82function getNarrowObjectList ($type_id = 0)
83{
84 $ret = array();
85 if (!$type_id)
86 {
87 showError ('Invalid argument', __FUNCTION__);
88 return $ret;
89 }
90 // object type id is known and constant, but it's Ok to have this standard overhead
91 $query =
92 "select RackObject.id as id, RackObject.name as name, dict_value as objtype_name, " .
93 "objtype_id from " .
94 "RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter " .
95 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
96 "and objtype_id = ${type_id} " .
97 "order by name";
98 $result = useSelectBlade ($query, __FUNCTION__);
99 while ($row = $result->fetch (PDO::FETCH_ASSOC))
100 {
101 foreach (array (
102 'id',
103 'name',
104 'objtype_name',
105 'objtype_id'
106 ) as $cname)
107 $ret[$row['id']][$cname] = $row[$cname];
108 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
109 }
110 return $ret;
111}
112
113// Return a filtered, detailed object list.
11c8e4be 114function getObjectList ($type_id = 0, $tagfilter = array(), $tfmode = 'any')
489a7502 115{
81736ac1 116 $whereclause = getWhereClause ($tagfilter);
489a7502
DO
117 if ($type_id != 0)
118 $whereclause .= " and objtype_id = '${type_id}' ";
e673ee24
DO
119 $query =
120 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
121 "RackObject.label as label, RackObject.barcode as barcode, " .
122 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name from " .
123 "((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
124 "left join RackSpace on RackObject.id = object_id) " .
125 "left join Rack on rack_id = Rack.id " .
7cc02fc1 126 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
105cea6e 127 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
7cc02fc1
DO
128 $whereclause .
129 "order by name";
065eeb52 130 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 131 $ret = array();
e673ee24
DO
132 while ($row = $result->fetch (PDO::FETCH_ASSOC))
133 {
2ac47ae4
DO
134 foreach (array (
135 'id',
136 'name',
137 'label',
138 'barcode',
139 'objtype_name',
140 'objtype_id',
141 'asset_no',
142 'rack_id',
143 'Rack_name'
144 ) as $cname)
e673ee24
DO
145 $ret[$row['id']][$cname] = $row[$cname];
146 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
147 }
148 $result->closeCursor();
149 return $ret;
150}
151
11c8e4be 152function getRacksForRow ($row_id = 0, $tagfilter = array(), $tfmode = 'any')
e673ee24 153{
e673ee24 154 $query =
1c81a02c 155 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
2d7698a2 156 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
e673ee24 157 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
932cf41f 158 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
e673ee24
DO
159 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
160 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
81736ac1 161 getWhereClause ($tagfilter) .
932cf41f 162 " order by row_name, Rack.id";
065eeb52 163 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 164 $ret = array();
1c81a02c
DO
165 $clist = array
166 (
167 'id',
168 'name',
169 'height',
170 'comment',
171 'row_id',
172 'left_is_front',
173 'bottom_is_unit1',
174 'row_name'
175 );
e673ee24 176 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1c81a02c 177 foreach ($clist as $cname)
e673ee24
DO
178 $ret[$row['id']][$cname] = $row[$cname];
179 $result->closeCursor();
6a3a37b2 180 usort ($ret, 'sortRacks');
e673ee24
DO
181 $ret = restoreRackIDs ($ret);
182 return $ret;
183}
184
185// This is a popular helper for getting information about
186// a particular rack and its rackspace at once.
187function getRackData ($rack_id = 0, $silent = FALSE)
188{
189 if ($rack_id == 0)
190 {
191 if ($silent == FALSE)
f41b492f 192 showError ('Invalid rack_id', __FUNCTION__);
e673ee24
DO
193 return NULL;
194 }
e673ee24 195 $query =
1c81a02c 196 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
2d7698a2 197 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
e673ee24
DO
198 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
199 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
065eeb52 200 $result = useSelectBlade ($query, __FUNCTION__);
89fa639f 201 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
e673ee24
DO
202 {
203 if ($silent == FALSE)
f41b492f 204 showError ('Query #1 succeded, but returned no data', __FUNCTION__);
e673ee24
DO
205 return NULL;
206 }
207
208 // load metadata
1c81a02c
DO
209 $clist = array
210 (
211 'id',
212 'name',
213 'height',
214 'comment',
215 'row_id',
216 'left_is_front',
217 'bottom_is_unit1',
218 'row_name'
219 );
220 foreach ($clist as $cname)
221 $rack[$cname] = $row[$cname];
89fa639f
DO
222 $result->closeCursor();
223 unset ($result);
e673ee24
DO
224
225 // start with default rackspace
226 for ($i = $rack['height']; $i > 0; $i--)
227 for ($locidx = 0; $locidx < 3; $locidx++)
228 $rack[$i][$locidx]['state'] = 'F';
229
230 // load difference
231 $query =
232 "select unit_no, atom, state, object_id " .
233 "from RackSpace where rack_id = ${rack_id} and " .
234 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
065eeb52 235 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 236 global $loclist;
89fa639f 237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
238 {
239 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
240 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
241 }
89fa639f 242 $result->closeCursor();
e673ee24
DO
243 return $rack;
244}
245
246// This is a popular helper.
247function getObjectInfo ($object_id = 0)
248{
249 if ($object_id == 0)
250 {
f41b492f 251 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
252 return;
253 }
e673ee24
DO
254 $query =
255 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
256 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
257 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
105a3bc8 258 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
259 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
260 {
105a3bc8 261 showError ('Query succeeded, but returned no data', __FUNCTION__);
e673ee24
DO
262 $ret = NULL;
263 }
264 else
265 {
266 $ret['id'] = $row['id'];
267 $ret['name'] = $row['name'];
268 $ret['label'] = $row['label'];
269 $ret['barcode'] = $row['barcode'];
270 $ret['objtype_name'] = $row['objtype_name'];
271 $ret['objtype_id'] = $row['objtype_id'];
272 $ret['has_problems'] = $row['has_problems'];
273 $ret['asset_no'] = $row['asset_no'];
274 $ret['dname'] = displayedName ($ret);
275 $ret['comment'] = $row['comment'];
276 }
277 $result->closeCursor();
105a3bc8 278 unset ($result);
e673ee24
DO
279 return $ret;
280}
281
282function getPortTypes ()
283{
fe6e3bd7 284 return readChapter ('PortType');
e673ee24
DO
285}
286
287function getObjectPortsAndLinks ($object_id = 0)
288{
289 if ($object_id == 0)
290 {
f41b492f 291 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
292 return;
293 }
e673ee24
DO
294 $query =
295 "select Port.id as Port_id, ".
296 "Port.name as Port_name, ".
297 "Port.label as Port_label, ".
298 "Port.l2address as Port_l2address, ".
299 "Port.type as Port_type, ".
300 "Port.reservation_comment as Port_reservation_comment, " .
301 "dict_value as PortType_name, ".
302 "RemotePort.id as RemotePort_id, ".
303 "RemotePort.name as RemotePort_name, ".
304 "RemotePort.object_id as RemotePort_object_id, ".
305 "RackObject.name as RackObject_name ".
306 "from (".
307 "(".
308 "(".
309 "Port inner join Dictionary on Port.type = dict_key natural join Chapter".
310 ") ".
311 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
312 ") ".
313 "left join Port as RemotePort on Link.portb=RemotePort.id or Link.porta=RemotePort.id ".
314 ") ".
315 "left join RackObject on RemotePort.object_id=RackObject.id ".
316 "where chapter_name = 'PortType' and Port.object_id=${object_id} ".
317 "and (Port.id != RemotePort.id or RemotePort.id is null) ".
318 "order by Port_name";
065eeb52 319 $result = useSelectBlade ($query, __FUNCTION__);
e425f895
DO
320 $ret=array();
321 $count=0;
322 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 323 {
e425f895
DO
324 $ret[$count]['id'] = $row['Port_id'];
325 $ret[$count]['name'] = $row['Port_name'];
326 $ret[$count]['l2address'] = l2addressFromDatabase ($row['Port_l2address']);
327 $ret[$count]['label'] = $row['Port_label'];
328 $ret[$count]['type_id'] = $row['Port_type'];
329 $ret[$count]['type'] = $row['PortType_name'];
330 $ret[$count]['reservation_comment'] = $row['Port_reservation_comment'];
331 $ret[$count]['remote_id'] = $row['RemotePort_id'];
332 $ret[$count]['remote_name'] = htmlentities ($row['RemotePort_name'], ENT_QUOTES);
333 $ret[$count]['remote_object_id'] = $row['RemotePort_object_id'];
334 $ret[$count]['remote_object_name'] = $row['RackObject_name'];
335 // Save on displayedName() calls.
336 if (empty ($row['RackObject_name']) and !empty ($row['RemotePort_object_id']))
e673ee24 337 {
e425f895
DO
338 $oi = getObjectInfo ($row['RemotePort_object_id']);
339 $ret[$count]['remote_object_name'] = displayedName ($oi);
e673ee24 340 }
e425f895 341 $count++;
e673ee24
DO
342 }
343 $result->closeCursor();
344 return $ret;
345}
346
f19c75d6 347function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
e673ee24 348{
f19c75d6
DO
349 if ($row_id <= 0 or $height <= 0 or empty ($name))
350 return FALSE;
406b54bd
DO
351 $result = useInsertBlade
352 (
353 'Rack',
354 array
355 (
356 'row_id' => $row_id,
357 'name' => "'${name}'",
358 'height' => $height,
359 'comment' => "'${comment}'"
360 )
361 );
362 if ($result == NULL)
e673ee24 363 {
406b54bd 364 showError ('useInsertBlade() failed', __FUNCTION__);
e673ee24
DO
365 return FALSE;
366 }
c63a8d6e 367 $last_insert_id = lastInsertID();
351c0966 368 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', "id = ${last_insert_id}");
e673ee24
DO
369}
370
f60bb422 371function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
e673ee24
DO
372{
373 global $dbxlink;
f60bb422
DO
374 // Maintain UNIQUE INDEX for common names and asset tags by
375 // filtering out empty strings (not NULLs).
376 $result1 = useInsertBlade
377 (
378 'RackObject',
379 array
380 (
381 'name' => empty ($new_name) ? 'NULL' : "'${new_name}'",
382 'label' => "'${new_label}'",
383 'barcode' => empty ($new_barcode) ? 'NULL' : "'${new_barcode}'",
384 'objtype_id' => $new_type_id,
385 'asset_no' => empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'"
386 )
387 );
e673ee24
DO
388 if ($result1 == NULL)
389 {
f60bb422 390 showError ("SQL query #1 failed", __FUNCTION__);
e673ee24
DO
391 return FALSE;
392 }
c63a8d6e 393 $last_insert_id = lastInsertID();
ad0e4754
DO
394 // Do AutoPorts magic
395 executeAutoPorts ($last_insert_id, $new_type_id);
f60bb422 396 // Now tags...
351c0966 397 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
c63a8d6e
DO
398 if ($error != '')
399 {
400 showError ("Error adding tags for the object: ${error}");
401 return FALSE;
402 }
e673ee24
DO
403 return recordHistory ('RackObject', "id = ${last_insert_id}");
404}
405
406function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
407{
408 if ($object_id == 0 || $new_type_id == 0)
409 {
f41b492f 410 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
411 return FALSE;
412 }
413 global $dbxlink;
414 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
415 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
416 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
417 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
418 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
419 "where id='${object_id}' limit 1";
420 $result = $dbxlink->query ($query);
421 if ($result == NULL)
422 {
f41b492f 423 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
424 return FALSE;
425 }
e673ee24
DO
426 $result->closeCursor();
427 return recordHistory ('RackObject', "id = ${object_id}");
428}
429
430function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
431{
432 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
433 {
f41b492f 434 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
435 return FALSE;
436 }
437 global $dbxlink;
438 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
439 "where id='${rack_id}' limit 1";
440 $result1 = $dbxlink->query ($query);
441 if ($result1->rowCount() != 1)
442 {
f41b492f 443 showError ('Error updating rack information', __FUNCTION__);
e673ee24
DO
444 return FALSE;
445 }
446 return recordHistory ('Rack', "id = ${rack_id}");
447}
448
449// This function accepts rack data returned by getRackData(), validates and applies changes
450// supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
451// correspond to current rack ID.
452// 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
453// If 4th arg is present, object_id fields will be updated accordingly to the new state.
454// The function returns the modified rack upon success.
455function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
456{
457 global $loclist, $dbxlink;
458 $rack_id = $rackData['id'];
459 $rack_name = $rackData['name'];
460 $rackchanged = FALSE;
461 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
462 {
463 for ($locidx = 0; $locidx < 3; $locidx++)
464 {
465 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
466 continue;
467 // detect a change
468 $state = $rackData[$unit_no][$locidx]['state'];
469 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
470 $newstate = $checked_state;
471 else
472 $newstate = $unchecked_state;
473 if ($state == $newstate)
474 continue;
475 $rackchanged = TRUE;
476 // and validate
477 $atom = $loclist[$locidx];
478 // The only changes allowed are those introduced by checkbox grid.
479 if
480 (
481 !($state == $checked_state && $newstate == $unchecked_state) &&
482 !($state == $unchecked_state && $newstate == $checked_state)
483 )
484 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
485 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
486 // anyway and then looking for probable need of INSERT.
487 $query =
488 "delete from RackSpace where rack_id = ${rack_id} and " .
489 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
490 $r = $dbxlink->query ($query);
491 if ($r == NULL)
4d2e93f2 492 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
e673ee24
DO
493 if ($newstate != 'F')
494 {
495 $query =
496 "insert into RackSpace(rack_id, unit_no, atom, state) " .
497 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
498 $r = $dbxlink->query ($query);
499 if ($r == NULL)
4d2e93f2 500 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
e673ee24
DO
501 }
502 if ($newstate == 'T' and $object_id != 0)
503 {
504 // At this point we already have a record in RackSpace.
505 $query =
506 "update RackSpace set object_id=${object_id} " .
507 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
508 $r = $dbxlink->query ($query);
509 if ($r->rowCount() == 1)
510 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
511 else
512 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
513 }
514 }
515 }
516 if ($rackchanged)
c7fe33be
DO
517 {
518 resetThumbCache ($rack_id);
e673ee24 519 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
c7fe33be 520 }
e673ee24
DO
521 else
522 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
523}
524
525// This function builds a list of rack-unit-atom records, which are assigned to
526// the requested object.
527function getMoleculeForObject ($object_id = 0)
528{
529 if ($object_id == 0)
530 {
f41b492f 531 showError ("object_id == 0", __FUNCTION__);
e673ee24
DO
532 return NULL;
533 }
e673ee24
DO
534 $query =
535 "select rack_id, unit_no, atom from RackSpace " .
536 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
065eeb52 537 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
538 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
539 $result->closeCursor();
540 return $ret;
541}
542
543// This function builds a list of rack-unit-atom records for requested molecule.
544function getMolecule ($mid = 0)
545{
546 if ($mid == 0)
547 {
f41b492f 548 showError ("mid == 0", __FUNCTION__);
e673ee24
DO
549 return NULL;
550 }
e673ee24
DO
551 $query =
552 "select rack_id, unit_no, atom from Atom " .
553 "where molecule_id=${mid}";
065eeb52 554 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
555 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
556 $result->closeCursor();
557 return $ret;
558}
559
c63a8d6e
DO
560// returns exactly what is's named after
561function lastInsertID ()
562{
563 if (NULL == ($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)))
564 {
565 showError ('SQL query failed!', __FUNCTION__);
566 die;
567 }
568 $row = $result->fetch (PDO::FETCH_NUM);
569 return $row[0];
570}
571
e673ee24
DO
572// This function creates a new record in Molecule and number of linked
573// R-U-A records in Atom.
574function createMolecule ($molData)
575{
576 global $dbxlink;
577 $query = "insert into Molecule values()";
578 $result1 = $dbxlink->query ($query);
579 if ($result1->rowCount() != 1)
580 {
f41b492f 581 showError ('Error inserting into Molecule', __FUNCTION__);
e673ee24
DO
582 return NULL;
583 }
c63a8d6e 584 $molecule_id = lastInsertID();
64b95774 585 foreach ($molData as $rua)
e673ee24
DO
586 {
587 $rack_id = $rua['rack_id'];
588 $unit_no = $rua['unit_no'];
589 $atom = $rua['atom'];
590 $query =
591 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
592 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
593 $result3 = $dbxlink->query ($query);
594 if ($result3 == NULL or $result3->rowCount() != 1)
595 {
f41b492f 596 showError ('Error inserting into Atom', __FUNCTION__);
e673ee24
DO
597 return NULL;
598 }
599 }
600 return $molecule_id;
601}
602
603// History logger. This function assumes certain table naming convention and
604// column design:
605// 1. History table name equals to dictionary table name plus 'History'.
606// 2. History table must have the same row set (w/o keys) plus one row named
607// 'ctime' of type 'timestamp'.
608function recordHistory ($tableName, $whereClause)
609{
610 global $dbxlink, $remote_username;
611 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
612 $result = $dbxlink->query ($query);
613 if ($result == NULL or $result->rowCount() != 1)
614 {
863b199a 615 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
e673ee24
DO
616 return FALSE;
617 }
618 return TRUE;
619}
620
621function getRackspaceHistory ()
622{
e673ee24
DO
623 $query =
624 "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 " .
625 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
626 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
627 "where chapter_name = 'RackObjectType' order by ctime desc";
065eeb52 628 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
629 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
630 $result->closeCursor();
631 return $ret;
632}
633
634// This function is used in renderRackspaceHistory()
635function getOperationMolecules ($op_id = 0)
636{
637 if ($op_id <= 0)
638 {
f41b492f 639 showError ("Missing argument", __FUNCTION__);
e673ee24
DO
640 return;
641 }
e673ee24 642 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
065eeb52 643 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
644 // We expect one row.
645 $row = $result->fetch (PDO::FETCH_ASSOC);
646 if ($row == NULL)
647 {
f41b492f 648 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
e673ee24
DO
649 return;
650 }
651 $omid = $row['old_molecule_id'];
652 $nmid = $row['new_molecule_id'];
653 $result->closeCursor();
654 return array ($omid, $nmid);
655}
656
c7fe33be 657function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
e673ee24
DO
658{
659 if ($object_id <= 0)
660 {
f41b492f 661 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
662 return;
663 }
664 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
065eeb52 665 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
666 $rows = $result->fetchAll (PDO::FETCH_NUM);
667 $result->closeCursor();
668 $ret = array();
669 foreach ($rows as $row)
670 {
b422aee6
DO
671 if (!$fetch_rackdata)
672 {
673 $ret[$row[0]] = $row[0];
674 continue;
675 }
e673ee24
DO
676 $rackData = getRackData ($row[0]);
677 if ($rackData == NULL)
678 {
f41b492f 679 showError ('getRackData() failed', __FUNCTION__);
e673ee24
DO
680 return NULL;
681 }
682 $ret[$row[0]] = $rackData;
683 }
684 $result->closeCursor();
685 return $ret;
686}
687
7cc02fc1 688function getObjectGroupInfo ()
e673ee24
DO
689{
690 $query =
691 'select dict_key as id, dict_value as name, count(id) as count from ' .
692 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
693 'where chapter_name = "RackObjectType" ' .
7cc02fc1 694 'group by dict_key order by dict_value';
065eeb52 695 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 696 $ret = array();
105cea6e 697 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
e673ee24 698 $clist = array ('id', 'name', 'count');
105cea6e 699 $total = 0;
e673ee24 700 while ($row = $result->fetch (PDO::FETCH_ASSOC))
7cc02fc1 701 if ($row['count'] > 0)
105cea6e
DO
702 {
703 $total += $row['count'];
64b95774 704 foreach ($clist as $cname)
7cc02fc1 705 $ret[$row['id']][$cname] = $row[$cname];
105cea6e 706 }
e673ee24 707 $result->closeCursor();
105cea6e 708 $ret[0]['count'] = $total;
7cc02fc1 709 return $ret;
e673ee24
DO
710}
711
712// This function returns objects, which have no rackspace assigned to them.
713// Additionally it keeps rack_id parameter, so we can silently pre-select
714// the rack required.
715function getUnmountedObjects ()
716{
e673ee24
DO
717 $query =
718 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
719 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
720 'left join RackSpace on id = object_id '.
068ffc0c 721 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
065eeb52 722 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
723 $ret = array();
724 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
725 while ($row = $result->fetch (PDO::FETCH_ASSOC))
726 {
64b95774 727 foreach ($clist as $cname)
e673ee24
DO
728 $ret[$row['id']][$cname] = $row[$cname];
729 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
730 }
731 $result->closeCursor();
732 return $ret;
733}
734
735function getProblematicObjects ()
736{
e673ee24
DO
737 $query =
738 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
739 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
740 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
065eeb52 741 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
742 $ret = array();
743 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
744 while ($row = $result->fetch (PDO::FETCH_ASSOC))
745 {
64b95774 746 foreach ($clist as $cname)
e673ee24
DO
747 $ret[$row['id']][$cname] = $row[$cname];
748 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
749 }
750 $result->closeCursor();
751 return $ret;
752}
753
754function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
755{
756 if ($object_id <= 0)
757 {
f41b492f 758 showError ('Invalid object_id', __FUNCTION__);
e673ee24
DO
759 return;
760 }
761 $port_l2address = l2addressForDatabase ($port_l2address);
762 $result = useInsertBlade
763 (
764 'Port',
765 array
766 (
767 'name' => "'${port_name}'",
768 'object_id' => "'${object_id}'",
769 'label' => "'${port_label}'",
770 'type' => "'${port_type_id}'",
771 'l2address' => "${port_l2address}"
772 )
773 );
774 if ($result)
775 return '';
776 else
777 return 'SQL query failed';
778}
779
d0a69ce8
DO
780// The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
781// string value. In case it is omitted, we just assign it its current value.
782// It would be nice to simplify this semantics later.
783function commitUpdatePort ($port_id, $port_name, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
e673ee24
DO
784{
785 global $dbxlink;
786 $port_l2address = l2addressForDatabase ($port_l2address);
787 $query =
788 "update Port set name='$port_name', label='$port_label', " .
789 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
790 "where id='$port_id'";
791 $result = $dbxlink->exec ($query);
792 if ($result == 1)
793 return '';
794 $errorInfo = $dbxlink->errorInfo();
795 // We could update nothing.
796 if ($errorInfo[0] == '00000')
797 return '';
798 return $errorInfo[2];
799}
800
801function delObjectPort ($port_id)
802{
803 if (unlinkPort ($port_id) != '')
4d2e93f2 804 return __FUNCTION__ . ': unlinkPort() failed';
e673ee24 805 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
4d2e93f2 806 return __FUNCTION__ . ': useDeleteBlade() failed';
e673ee24
DO
807 return '';
808}
809
6ef9683b 810function getAllIPv4Allocations ()
e673ee24 811{
e673ee24
DO
812 $query =
813 "select object_id as object_id, ".
814 "RackObject.name as object_name, ".
815 "IPBonds.name as name, ".
816 "INET_NTOA(ip) as ip ".
817 "from IPBonds join RackObject on id=object_id ";
065eeb52 818 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
819 $ret = array();
820 $count=0;
821 while ($row = $result->fetch (PDO::FETCH_ASSOC))
822 {
823 $ret[$count]['object_id']=$row['object_id'];
824 $ret[$count]['object_name']=$row['object_name'];
825 $ret[$count]['name']=$row['name'];
826 $ret[$count]['ip']=$row['ip'];
827 $count++;
828 }
829 $result->closeCursor();
830 return $ret;
831}
832
e673ee24
DO
833function getEmptyPortsOfType ($type_id)
834{
e673ee24
DO
835 $query =
836 "select distinct Port.id as Port_id, ".
837 "Port.object_id as Port_object_id, ".
838 "RackObject.name as Object_name, ".
839 "Port.name as Port_name, ".
840 "Port.type as Port_type_id, ".
841 "dict_value as Port_type_name ".
842 "from ( ".
843 " ( ".
844 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
845 " ) ".
846 " join RackObject on Port.object_id = RackObject.id ".
847 ") ".
848 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
849 "inner join PortCompat on Port.type = PortCompat.type2 ".
850 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
851 "and Port.reservation_comment is null order by Object_name, Port_name";
065eeb52 852 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
853 $ret = array();
854 $count=0;
855 while ($row = $result->fetch (PDO::FETCH_ASSOC))
856 {
857 $ret[$count]['Port_id']=$row['Port_id'];
858 $ret[$count]['Port_object_id']=$row['Port_object_id'];
859 $ret[$count]['Object_name']=$row['Object_name'];
860 $ret[$count]['Port_name']=$row['Port_name'];
861 $ret[$count]['Port_type_id']=$row['Port_type_id'];
862 $ret[$count]['Port_type_name']=$row['Port_type_name'];
863 $count++;
864 }
865 $result->closeCursor();
866 return $ret;
867}
868
869function linkPorts ($porta, $portb)
870{
871 if ($porta == $portb)
872 return "Ports can't be the same";
873 if ($porta > $portb)
874 {
875 $tmp = $porta;
876 $porta = $portb;
877 $portb = $tmp;
878 }
879 global $dbxlink;
880 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
881 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
882 // FIXME: who cares about the return value?
883 $result = $dbxlink->exec ($query1);
884 $result = $dbxlink->exec ($query2);
885 return '';
e673ee24
DO
886}
887
888function unlinkPort ($port)
889{
890 global $dbxlink;
891 $query =
892 "delete from Link where porta='$port' or portb='$port'";
893 $result = $dbxlink->exec ($query);
894 return '';
e673ee24
DO
895}
896
2c817354
DO
897// Return all IPv4 addresses allocated to the objects. Attach detailed
898// info about address to each alocation records. Index result by dotted-quad
899// address.
0ab782bc
DO
900function getObjectIPv4Allocations ($object_id = 0)
901{
902 $ret = array();
903 $query = 'select name as osif, type, inet_ntoa(ip) as dottedquad from IPBonds ' .
904 "where object_id = ${object_id} " .
905 'order by ip';
906 $result = useSelectBlade ($query, __FUNCTION__);
85970da2 907 // don't spawn a sub-query with unfetched buffer, it may fail
0ab782bc 908 while ($row = $result->fetch (PDO::FETCH_ASSOC))
85970da2
DO
909 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
910 unset ($result);
911 foreach (array_keys ($ret) as $dottedquad)
912 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
0ab782bc
DO
913 return $ret;
914}
915
e6ca609a
DO
916// Return minimal IPv4 address, optionally with "ip" key set, if requested.
917function constructIPv4Address ($dottedquad = NULL)
a910829d 918{
e6ca609a 919 $ret = array
a910829d
DO
920 (
921 'name' => '',
922 'reserved' => 'no',
a910829d
DO
923 'outpf' => array(),
924 'inpf' => array(),
a910829d 925 'rslist' => array(),
2d318652 926 'allocs' => array(),
a910829d
DO
927 'lblist' => array()
928 );
e6ca609a
DO
929 if ($dottedquad != NULL)
930 $ret['ip'] = $dottedquad;
931 return $ret;
932}
933
934// Check the range requested for meaningful IPv4 records, build them
935// into a list and return. Return an empty list if nothing matched.
936// Both arguments are expected in signed int32 form. The resulting list
937// is keyed by uint32 form of each IP address, items aren't sorted.
f7414fa5
DO
938// LATER: accept a list of pairs and build WHERE sub-expression accordingly
939function scanIPv4Space ($pairlist)
e6ca609a
DO
940{
941 $ret = array();
f7414fa5
DO
942 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
943 return $ret;;
a910829d 944 $dnamechache = array();
f7414fa5
DO
945 // FIXME: this is a copy-and-paste prototype
946 $or = '';
947 $whereexpr1 = '(';
948 $whereexpr2 = '(';
949 $whereexpr3 = '(';
950 $whereexpr4 = '(';
951 $whereexpr5a = '(';
952 $whereexpr5b = '(';
953 foreach ($pairlist as $tmp)
954 {
955 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
956 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
957 $whereexpr1 .= $or . "ip between ${db_first} and ${db_last}";
958 $whereexpr2 .= $or . "ip between ${db_first} and ${db_last}";
959 $whereexpr3 .= $or . "vip between ${db_first} and ${db_last}";
960 $whereexpr4 .= $or . "rsip between ${db_first} and ${db_last}";
961 $whereexpr5a .= $or . "remoteip between ${db_first} and ${db_last}";
962 $whereexpr5b .= $or . "localip between ${db_first} and ${db_last}";
963 $or = ' or ';
964 }
965 $whereexpr1 .= ')';
966 $whereexpr2 .= ')';
967 $whereexpr3 .= ')';
968 $whereexpr4 .= ')';
969 $whereexpr5a .= ')';
970 $whereexpr5b .= ')';
a910829d 971
2d318652
DO
972 $db_first = sprintf ('%u', 0x00000000 + $i32_first);
973 $db_last = sprintf ('%u', 0x00000000 + $i32_last);
a910829d 974 // 1. collect labels and reservations
2d318652 975 $query = "select INET_NTOA(ip) as ip, name, reserved from IPAddress ".
f7414fa5 976 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
a910829d
DO
977 $result = useSelectBlade ($query, __FUNCTION__);
978 while ($row = $result->fetch (PDO::FETCH_ASSOC))
979 {
2d318652
DO
980 $ip_bin = ip2long ($row['ip']);
981 if (!isset ($ret[$ip_bin]))
e6ca609a 982 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
2d318652
DO
983 $ret[$ip_bin]['name'] = $row['name'];
984 $ret[$ip_bin]['reserved'] = $row['reserved'];
a910829d
DO
985 }
986 unset ($result);
987
988 // 2. check for allocations
989 $query =
2d318652 990 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
a910829d
DO
991 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
992 "dict_value as objtype_name from " .
993 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
994 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
f7414fa5 995 "where ${whereexpr2} " .
a910829d
DO
996 "and chapter_name = 'RackObjectType'" .
997 "order by ipb.type, object_name";
998 $result = useSelectBlade ($query, __FUNCTION__);
999 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1000 {
2d318652
DO
1001 $ip_bin = ip2long ($row['ip']);
1002 if (!isset ($ret[$ip_bin]))
e6ca609a 1003 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1004 if (!isset ($dnamecache[$row['object_id']]))
1005 {
1006 $quasiobject['name'] = $row['object_name'];
1007 $quasiobject['objtype_id'] = $row['objtype_id'];
1008 $quasiobject['objtype_name'] = $row['objtype_name'];
1009 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1010 }
1011 $tmp = array();
1012 foreach (array ('object_id', 'type', 'name') as $cname)
1013 $tmp[$cname] = $row[$cname];
1014 $tmp['object_name'] = $dnamecache[$row['object_id']];
2d318652 1015 $ret[$ip_bin]['allocs'][] = $tmp;
a910829d
DO
1016 }
1017 unset ($result);
1018
1019 // 3. look for virtual services and related LB
2d318652 1020 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
a910829d
DO
1021 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
1022 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
1023 "inner join RackObject as ro on lb.object_id = ro.id " .
1024 "left join Dictionary on objtype_id=dict_key " .
1025 "natural join Chapter " .
f7414fa5 1026 "where ${whereexpr3} " .
a910829d
DO
1027 "and chapter_name = 'RackObjectType'" .
1028 "order by vport, proto, ro.name, object_id";
1029 $result = useSelectBlade ($query, __FUNCTION__);
1030 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1031 {
2d318652 1032 $ip_bin = ip2long ($row['ip']);
f3d0cb20 1033 if (!isset ($ret[$ip_bin]))
e6ca609a 1034 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1035 if (!isset ($dnamecache[$row['object_id']]))
1036 {
1037 $quasiobject['name'] = $row['object_name'];
1038 $quasiobject['objtype_id'] = $row['objtype_id'];
1039 $quasiobject['objtype_name'] = $row['objtype_name'];
1040 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1041 }
1042 $tmp = array();
2d318652 1043 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
a910829d
DO
1044 $tmp[$cname] = $row[$cname];
1045 $tmp['object_name'] = $dnamecache[$row['object_id']];
2d318652
DO
1046 $tmp['vip'] = $row['ip'];
1047 $ret[$ip_bin]['lblist'][] = $tmp;
a910829d
DO
1048 }
1049 unset ($result);
1050
1051 // 4. don't forget about real servers along with pools
2d318652 1052 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
a910829d 1053 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
f7414fa5 1054 "where ${whereexpr4} " .
a910829d
DO
1055 "order by ip, rsport, rspool_id";
1056 $result = useSelectBlade ($query, __FUNCTION__);
1057 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1058 {
2d318652
DO
1059 $ip_bin = ip2long ($row['ip']);
1060 if (!isset ($ret[$ip_bin]))
e6ca609a 1061 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
a910829d
DO
1062 $tmp = array();
1063 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1064 $tmp[$cname] = $row[$cname];
2d318652 1065 $ret[$ip_bin]['rslist'][] = $tmp;
a910829d
DO
1066 }
1067 unset ($result);
1068
1069 // 5. add NAT rules, part 1
1070 $query =
1071 "select " .
1072 "proto, " .
1073 "INET_NTOA(localip) as localip, " .
1074 "localport, " .
1075 "INET_NTOA(remoteip) as remoteip, " .
1076 "remoteport, " .
1077 "description " .
1078 "from PortForwarding " .
f7414fa5
DO
1079 "where ${whereexpr5a} or " .
1080 "${whereexpr5b} " .
a910829d
DO
1081 "order by localip, localport, remoteip, remoteport, proto";
1082 $result = useSelectBlade ($query, __FUNCTION__);
1083 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1084 {
2d318652
DO
1085 $remoteip_bin = ip2long ($row['remoteip']);
1086 $localip_bin = ip2long ($row['localip']);
1087 if ($i32_first <= $remoteip_bin and $remoteip_bin <= $i32_last)
1088 {
1089 if (!isset ($ret[$remoteip_bin]))
e6ca609a 1090 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
2d318652
DO
1091 $ret[$remoteip_bin]['inpf'][] = $row;
1092 }
1093 if ($i32_first <= $localip_bin and $localip_bin <= $i32_last)
1094 {
1095 if (!isset ($ret[$localip_bin]))
e6ca609a 1096 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
2d318652
DO
1097 $ret[$localip_bin]['outpf'][] = $row;
1098 }
a910829d
DO
1099 }
1100 return $ret;
1101}
1102
1103// Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
2d318652 1104function getIPv4NetworkInfo ($id = 0)
a910829d
DO
1105{
1106 if ($id <= 0)
1107 {
1108 showError ('Invalid arg', __FUNCTION__);
1109 return NULL;
1110 }
2d318652 1111 $query = "select INET_NTOA(ip) as ip, mask, name ".
a910829d
DO
1112 "from IPRanges where id = $id";
1113 $result = useSelectBlade ($query, __FUNCTION__);
1114 $ret = $result->fetch (PDO::FETCH_ASSOC);
1115 if ($ret == NULL)
1116 return NULL;
1117 unset ($result);
1118 $ret['id'] = $id;
2d318652 1119 $ret['ip_bin'] = ip2long ($ret['ip']);
a910829d
DO
1120 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1121 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1122 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
1123 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
d65353ad 1124 $ret['parent_id'] = getIPv4AddressNetworkId ($ret['ip'], $ret['mask']);
a910829d
DO
1125 return $ret;
1126}
1127
2d318652
DO
1128function getIPv4Address ($dottedquad = '')
1129{
1130 if ($dottedquad == '')
1131 {
1132 showError ('Invalid arg', __FUNCTION__);
1133 return NULL;
1134 }
1135 $i32 = ip2long ($dottedquad); // signed 32 bit
f7414fa5 1136 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
2d318652 1137 if (!isset ($scanres[$i32]))
8b980e24 1138 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
e6ca609a 1139 return constructIPv4Address ($dottedquad);
2d318652
DO
1140 markupIPv4AddrList ($scanres);
1141 return $scanres[$i32];
a910829d
DO
1142}
1143
5222f192
DO
1144function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1145{
1146 $result = useInsertBlade
1147 (
1148 'IPBonds',
1149 array
1150 (
1151 'ip' => "INET_ATON('$ip')",
1152 'object_id' => "'${object_id}'",
1153 'name' => "'${name}'",
1154 'type' => "'${type}'"
1155 )
1156 );
1157 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
1158}
1159
d65353ad
DO
1160function getIPv4NetworkList ($tagfilter = array(), $tfmode = 'any')
1161{
1162 $whereclause = getWhereClause ($tagfilter);
1163 $query =
1164 "select distinct id ".
1165 "from IPRanges left join TagStorage on id = target_id and target_realm = 'ipv4net' " .
1166 "where true ${whereclause} order by ip";
1167 $result = useSelectBlade ($query, __FUNCTION__);
1168 $ret = array();
1169 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1170 $ret[$row['id']] = NULL;
1171 unset ($result);
1172 $keys = array_keys ($ret);
1173 foreach ($keys as $netid)
1174 {
1175 $ret[$netid] = getIPv4NetworkInfo ($netid);
1176 if ($ret[$netid]['parent_id'] and !in_array ($ret[$netid]['parent_id'], $keys))
1177 {
1178 $ret[$netid]['real_parent_id'] = $ret[$netid]['parent_id'];
1179 $ret[$netid]['parent_id'] = NULL;
1180 }
1181 }
1182 return $ret;
1183}
1184
bb0a44e9 1185// Return the id of the smallest IPv4 network containing the given IPv4 address
d65353ad
DO
1186// or NULL, if nothing was found. When finding the covering network for
1187// another network, it is important to filter out matched records with longer
1188// masks (they aren't going to be the right pick).
1189function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
e673ee24 1190{
3702d093
DO
1191// N.B. To perform the same for IPv6 address and networks, some pre-requisites
1192// are necessary and a different query. IPv6 addresses are 128 bit long, which
1193// is too much for both PHP and MySQL data types. These values must be split
1194// into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1195// Then each network must have its 128-bit netmask split same way and either
1196// stored right in its record or JOINed from decoder and accessible as m_u32_0,
1197// m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1198// covering the given address would look as follows:
1199// $query = 'select id from IPv6Network as n where ' .
1200// "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1201// "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1202// "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1203// "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1204// "mask < ${masklen} " .
1205// 'order by mask desc limit 1';
1206
bb0a44e9
DO
1207 $query = 'select id from IPRanges where ' .
1208 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
d65353ad 1209 "and mask < ${masklen} " .
bb0a44e9 1210 'order by mask desc limit 1';
065eeb52 1211 $result = useSelectBlade ($query, __FUNCTION__);
bb0a44e9
DO
1212 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1213 return $row['id'];
e673ee24
DO
1214 return NULL;
1215}
1216
1217function updateRange ($id=0, $name='')
1218{
1219 global $dbxlink;
1220 $query =
1221 "update IPRanges set name='$name' where id='$id'";
1222 $result = $dbxlink->exec ($query);
1223 return '';
e673ee24
DO
1224}
1225
1226// This function is actually used not only to update, but also to create records,
1227// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1228// (MySQL 4.0 workaround).
b4c1ef87 1229function updateAddress ($ip = 0, $name = '', $reserved = 'no')
e673ee24
DO
1230{
1231 // DELETE may safely fail.
f5575f12 1232 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')");
e673ee24
DO
1233 // INSERT may appear not necessary.
1234 if ($name == '' and $reserved == 'no')
1235 return '';
1236 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1237 return '';
1238 else
b4c1ef87 1239 return __FUNCTION__ . '(): useInsertBlade() failed';
e673ee24
DO
1240}
1241
e673ee24
DO
1242function updateBond ($ip='', $object_id=0, $name='', $type='')
1243{
1244 global $dbxlink;
1245
1246 $query =
1247 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1248 $result = $dbxlink->exec ($query);
1249 return '';
1250}
1251
1252function unbindIpFromObject ($ip='', $object_id=0)
1253{
1254 global $dbxlink;
1255
1256 $query =
1257 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1258 $result = $dbxlink->exec ($query);
1259 return '';
1260}
1261
1262// This function returns either all or one user account. Array key is user name.
11c8e4be 1263function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
e673ee24 1264{
81736ac1 1265 $whereclause = getWhereClause ($tagfilter);
e673ee24
DO
1266 $query =
1267 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
ebae41b3
DO
1268 'from UserAccount left join TagStorage ' .
1269 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1270 "where true ${whereclause} " .
1271 'order by user_name';
065eeb52 1272 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1273 $ret = array();
1274 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1275 while ($row = $result->fetch (PDO::FETCH_ASSOC))
64b95774 1276 foreach ($clist as $cname)
e673ee24
DO
1277 $ret[$row['user_name']][$cname] = $row[$cname];
1278 $result->closeCursor();
1279 return $ret;
1280}
1281
e673ee24
DO
1282function searchByl2address ($l2addr)
1283{
e673ee24
DO
1284 $l2addr = l2addressForDatabase ($l2addr);
1285 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1286 "where l2address = ${l2addr}";
065eeb52 1287 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1288 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1289 $result->closeCursor();
1290 if (count ($rows) == 0) // No results.
1291 return NULL;
1292 if (count ($rows) == 1) // Target found.
1293 return $rows[0];
f41b492f 1294 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
e673ee24
DO
1295 return NULL;
1296}
1297
ea5fc465
DO
1298function getIPv4PrefixSearchResult ($terms)
1299{
1300 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1301 $or = '';
1302 foreach (explode (' ', $terms) as $term)
1303 {
1304 $query .= $or . "name like '%${term}%'";
1305 $or = ' or ';
1306 }
065eeb52 1307 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1308 $ret = array();
1309 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1310 $ret[] = $row;
1311 return $ret;
1312}
1313
1314function getIPv4AddressSearchResult ($terms)
1315{
1316 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1317 $or = '';
1318 foreach (explode (' ', $terms) as $term)
1319 {
1320 $query .= $or . "name like '%${term}%'";
1321 $or = ' or ';
1322 }
065eeb52 1323 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1324 $ret = array();
1325 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1326 $ret[] = $row;
1327 return $ret;
1328}
1329
05411ccd
DO
1330function getIPv4RSPoolSearchResult ($terms)
1331{
1332 $query = "select id as pool_id, name from IPRSPool where ";
1333 $or = '';
1334 foreach (explode (' ', $terms) as $term)
1335 {
1336 $query .= $or . "name like '%${term}%'";
1337 $or = ' or ';
1338 }
065eeb52 1339 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1340 $ret = array();
1341 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1342 $ret[] = $row;
1343 return $ret;
1344}
1345
1346function getIPv4VServiceSearchResult ($terms)
1347{
1348 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1349 $or = '';
1350 foreach (explode (' ', $terms) as $term)
1351 {
1352 $query .= $or . "name like '%${term}%'";
1353 $or = ' or ';
1354 }
065eeb52 1355 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1356 $ret = array();
1357 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1358 $ret[] = $row;
1359 return $ret;
1360}
1361
6a88e734
DO
1362function getAccountSearchResult ($terms)
1363{
1364 return getSearchResultByField
1365 (
1366 'UserAccount',
1367 array ('user_id', 'user_name', 'user_realname'),
1368 'user_name',
1369 $terms,
1370 'user_name'
1371 );
1372}
1373
1374function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1375{
1376 $pfx = '';
1377 $query = 'select ';
1378 foreach ($rcolumns as $col)
1379 {
1380 $query .= $pfx . $col;
1381 $pfx = ', ';
1382 }
1383 $pfx = '';
1384 $query .= " from ${tname} where ";
1385 foreach (explode (' ', $terms) as $term)
1386 {
1387 $query .= $pfx . "${scolumn} like '%${term}%'";
1388 $pfx = ' or ';
1389 }
1390 if ($ocolumn != '')
1391 $query .= " order by ${ocolumn}";
1392 $result = useSelectBlade ($query, __FUNCTION__);
1393 $ret = array();
1394 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1395 $ret[] = $row;
1396 return $ret;
1397}
1398
e673ee24
DO
1399// This function returns either port ID or NULL for specified arguments.
1400function getPortID ($object_id, $port_name)
1401{
e673ee24 1402 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
065eeb52 1403 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1404 $rows = $result->fetchAll (PDO::FETCH_NUM);
1405 if (count ($rows) != 1)
1406 return NULL;
1407 $ret = $rows[0][0];
1408 $result->closeCursor();
1409 return $ret;
1410}
1411
1412function commitCreateUserAccount ($username, $realname, $password)
1413{
1414 return useInsertBlade
1415 (
1416 'UserAccount',
1417 array
1418 (
1419 'user_name' => "'${username}'",
1420 'user_realname' => "'${realname}'",
1421 'user_password_hash' => "'${password}'"
1422 )
1423 );
1424}
1425
1426function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1427{
1428 global $dbxlink;
1429 $query =
1430 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1431 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1432 $result = $dbxlink->query ($query);
1433 if ($result == NULL)
1434 {
f41b492f 1435 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1436 die;
1437 }
1438 return TRUE;
1439}
1440
1441function commitEnableUserAccount ($id, $new_enabled_value)
1442{
1443 global $dbxlink;
1444 $query =
1445 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1446 "where user_id = ${id} limit 1";
1447 $result = $dbxlink->query ($query);
1448 if ($result == NULL)
1449 {
f41b492f 1450 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1451 die;
1452 }
1453 return TRUE;
1454}
1455
e673ee24
DO
1456// This function returns an array of all port type pairs from PortCompat table.
1457function getPortCompat ()
1458{
e673ee24
DO
1459 $query =
1460 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1461 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1462 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1463 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1464 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1465 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
065eeb52 1466 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1467 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1468 $result->closeCursor();
1469 return $ret;
1470}
1471
1472function removePortCompat ($type1 = 0, $type2 = 0)
1473{
1474 global $dbxlink;
1475 if ($type1 == 0 or $type2 == 0)
1476 {
f41b492f 1477 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1478 die;
1479 }
1480 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1481 $result = $dbxlink->query ($query);
1482 if ($result == NULL)
1483 {
f41b492f 1484 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1485 die;
1486 }
1487 return TRUE;
1488}
1489
1490function addPortCompat ($type1 = 0, $type2 = 0)
1491{
1492 if ($type1 <= 0 or $type2 <= 0)
1493 {
f41b492f 1494 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1495 die;
1496 }
1497 return useInsertBlade
1498 (
1499 'PortCompat',
1500 array ('type1' => $type1, 'type2' => $type2)
1501 );
1502}
1503
1504// This function returns the dictionary as an array of trees, each tree
1505// representing a single chapter. Each element has 'id', 'name', 'sticky'
1506// and 'word' keys with the latter holding all the words within the chapter.
2dd59b15 1507function getDict ($parse_links = FALSE)
e673ee24 1508{
6bb8e41d 1509 $query1 =
e673ee24
DO
1510 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1511 "Chapter natural left join Dictionary order by chapter_name, dict_value";
065eeb52 1512 $result = useSelectBlade ($query1, __FUNCTION__);
e673ee24 1513 $dict = array();
89fa639f 1514 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
1515 {
1516 $chapter_no = $row['chapter_no'];
1517 if (!isset ($dict[$chapter_no]))
1518 {
1519 $dict[$chapter_no]['no'] = $chapter_no;
1520 $dict[$chapter_no]['name'] = $row['chapter_name'];
1521 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1522 $dict[$chapter_no]['word'] = array();
1523 }
1524 if ($row['dict_key'] != NULL)
6bb8e41d 1525 {
2dd59b15
DO
1526 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1527 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1528 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1529 }
e673ee24 1530 }
89fa639f
DO
1531 $result->closeCursor();
1532 unset ($result);
6bb8e41d
DO
1533// Find the list of all assigned values of dictionary-addressed attributes, each with
1534// chapter/word keyed reference counters. Use the structure to adjust reference counters
1535// of the returned disctionary words.
1536 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1537 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1538 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1539 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1540 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1541 "order by a.attr_id, am.chapter_no, uint_value";
065eeb52 1542 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1543 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1544 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1545 $result->closeCursor();
e673ee24
DO
1546 return $dict;
1547}
1548
da95280e
DO
1549function getDictStats ()
1550{
82f7e2e8 1551 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
da95280e 1552 $query =
5aa28abb
DO
1553 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1554 "Chapter natural left join Dictionary group by Chapter.chapter_no";
065eeb52 1555 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1556 $tc = $tw = $uc = $uw = 0;
89fa639f 1557 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1558 {
1559 $tc++;
1560 $tw += $row['wc'];;
1561 if (in_array ($row['chapter_no'], $stock_chapters))
1562 continue;
1563 $uc++;
1564 $uw += $row['wc'];;
1565 }
89fa639f
DO
1566 $result->closeCursor();
1567 unset ($result);
08b4cb24
DO
1568 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1569 "AttributeValue as av on ro.id = av.object_id group by ro.id";
065eeb52 1570 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1571 $to = $ta = $so = 0;
89fa639f 1572 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1573 {
1574 $to++;
1575 if ($row['attrc'] != 0)
1576 {
1577 $so++;
1578 $ta += $row['attrc'];
1579 }
1580 }
89fa639f 1581 $result->closeCursor();
da95280e
DO
1582 $ret = array();
1583 $ret['Total chapters in dictionary'] = $tc;
1584 $ret['Total words in dictionary'] = $tw;
1585 $ret['User chapters'] = $uc;
1586 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1587 $ret['Total objects'] = $to;
1588 $ret['Objects with stickers'] = $so;
1589 $ret['Total stickers attached'] = $ta;
da95280e
DO
1590 return $ret;
1591}
1592
6807f0be 1593function getIPv4Stats ()
9ec5fdf1 1594{
9ec5fdf1
DO
1595 $ret = array();
1596 $subject = array();
1597 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1598 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1599 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1600 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1601 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1602 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1603 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1604 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1605
1606 foreach ($subject as $item)
1607 {
065eeb52 1608 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
1609 $row = $result->fetch (PDO::FETCH_NUM);
1610 $ret[$item['txt']] = $row[0];
1611 $result->closeCursor();
1612 unset ($result);
1613 }
1614 return $ret;
1615}
1616
6807f0be 1617function getRackspaceStats ()
9ec5fdf1 1618{
9ec5fdf1
DO
1619 $ret = array();
1620 $subject = array();
1621 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1622 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1623 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1624 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1625
1626 foreach ($subject as $item)
1627 {
065eeb52 1628 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1629 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1630 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1631 $result->closeCursor();
1632 unset ($result);
1633 }
1634 return $ret;
1635}
1636
e9b9a095 1637function renderTagStats ()
5bbbeaa2 1638{
e9b9a095
DO
1639 global $taglist, $root;
1640 $query = "select id, tag, count(tag_id) as refcnt from " .
5bbbeaa2 1641 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
e9b9a095
DO
1642 "group by tag_id order by refcnt desc limit 50";
1643 // The same data is already present in pre-loaded tag list, but not in
1644 // the form we need. So let's ask the DB server for cooked top list and
1645 // use the cooked tag list to break it down.
065eeb52 1646 $result = useSelectBlade ($query, __FUNCTION__);
e9b9a095
DO
1647 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1648 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
1649 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th></tr>';
1650 $pagebyrealm = array
1651 (
1652 'object' => 'objgroup&group_id=0',
1653 'ipv4net' => 'ipv4space&tab=default',
1654 'rack' => 'rackspace&tab=default',
1655 'ipv4vs' => 'ipv4vslist&tab=default',
1656 'ipv4rspool' => 'ipv4rsplist&tab=default',
1657 'user' => 'userlist&tab=default'
1658 );
1659 foreach ($refc as $ref)
1660 {
1661 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
1662 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user') as $realm)
1663 {
1664 echo '<td>';
1665 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1666 echo '&nbsp;';
1667 else
1668 {
1669 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&tagfilter[]=${ref['id']}'>";
1670 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1671 }
1672 echo '</td>';
1673 }
1674 echo '</tr>';
1675 }
1676 echo '</table>';
5bbbeaa2
DO
1677}
1678
6807f0be
DO
1679/*
1680
1681The following allows figuring out records in TagStorage, which refer to non-existing entities:
1682
1683mysql> select target_id from TagStorage left join IPRanges on target_id = id where target_realm = 'ipv4net' and id is null;
1684mysql> select target_id from TagStorage left join RackObject on target_id = id where target_realm = 'object' and id is null;
1685mysql> select target_id from TagStorage left join Rack on target_id = id where target_realm = 'rack' and id is null;
1686mysql> select target_id from TagStorage left join IPVirtualService on target_id = id where target_realm = 'ipv4vs' and id is null;
1687mysql> select target_id from TagStorage left join IPRSPool on target_id = id where target_realm = 'ipv4rspool' and id is null;
1688mysql> select target_id from TagStorage left join UserAccount on target_id = user_id where target_realm = 'user' and user_id is null;
1689
1690Accordingly, these are the records, which refer to non-existent tags:
1691
1692mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1693
1694*/
1695
e673ee24
DO
1696function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1697{
1698 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1699 {
f41b492f 1700 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1701 die;
1702 }
1703 global $dbxlink;
1704 $query =
1705 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1706 "and dict_key=${dict_key} limit 1";
1707 $result = $dbxlink->query ($query);
1708 if ($result == NULL)
1709 {
f41b492f 1710 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1711 die;
1712 }
1713 return TRUE;
1714}
1715
1716function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1717{
1718 if ($chapter_no <= 0 or empty ($dict_value))
1719 {
f41b492f 1720 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1721 die;
1722 }
1723 return useInsertBlade
1724 (
1725 'Dictionary',
1726 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1727 );
1728}
1729
1730function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1731{
1732 if ($chapter_no <= 0 or $dict_key <= 0)
1733 {
f41b492f 1734 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1735 die;
1736 }
1737 global $dbxlink;
1738 $query =
1739 "delete from Dictionary where chapter_no=${chapter_no} " .
1740 "and dict_key=${dict_key} limit 1";
1741 $result = $dbxlink->query ($query);
1742 if ($result == NULL)
1743 {
f41b492f 1744 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1745 die;
1746 }
1747 return TRUE;
1748}
1749
1750function commitAddChapter ($chapter_name = '')
1751{
1752 if (empty ($chapter_name))
1753 {
f41b492f 1754 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1755 die;
1756 }
1757 return useInsertBlade
1758 (
1759 'Chapter',
1760 array ('chapter_name' => "'${chapter_name}'")
1761 );
1762}
1763
1764function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1765{
1766 if ($chapter_no <= 0 or empty ($chapter_name))
1767 {
f41b492f 1768 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1769 die;
1770 }
1771 global $dbxlink;
1772 $query =
1773 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1774 "and sticky = 'no' limit 1";
1775 $result = $dbxlink->query ($query);
1776 if ($result == NULL)
1777 {
f41b492f 1778 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1779 die;
1780 }
1781 return TRUE;
1782}
1783
1784function commitDeleteChapter ($chapter_no = 0)
1785{
1786 if ($chapter_no <= 0)
1787 {
f41b492f 1788 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1789 die;
1790 }
1791 global $dbxlink;
1792 $query =
1793 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1794 $result = $dbxlink->query ($query);
1795 if ($result == NULL)
1796 {
f41b492f 1797 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1798 die;
1799 }
1800 return TRUE;
1801}
1802
4c330a14
DO
1803// This is a dictionary accessor. We perform link rendering, so the user sees
1804// nice <select> drop-downs.
e673ee24
DO
1805function readChapter ($chapter_name = '')
1806{
1807 if (empty ($chapter_name))
1808 {
f41b492f 1809 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1810 return NULL;
1811 }
e673ee24
DO
1812 $query =
1813 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1814 "where chapter_name = '${chapter_name}'";
065eeb52 1815 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1816 $chapter = array();
1817 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1818 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1819 $result->closeCursor();
4aa8609b
DO
1820 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1821 asort ($chapter);
e673ee24
DO
1822 return $chapter;
1823}
1824
1825function getAttrMap ()
1826{
e673ee24
DO
1827 $query =
1828 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1829 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1830 "Attribute as a natural left join AttributeMap as am " .
1831 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1832 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1833 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1834 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1835 "order by attr_name";
065eeb52 1836 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1837 $ret = array();
1838 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1839 {
1840 $attr_id = $row['attr_id'];
1841 if (!isset ($ret[$attr_id]))
1842 {
1843 $ret[$attr_id]['id'] = $attr_id;
1844 $ret[$attr_id]['type'] = $row['attr_type'];
1845 $ret[$attr_id]['name'] = $row['attr_name'];
1846 $ret[$attr_id]['application'] = array();
1847 }
1848 if ($row['objtype_id'] == '')
1849 continue;
1850 $application['objtype_id'] = $row['objtype_id'];
1851 $application['objtype_name'] = $row['objtype_name'];
1852 if ($row['attr_type'] == 'dict')
1853 {
1854 $application['chapter_no'] = $row['chapter_no'];
1855 $application['chapter_name'] = $row['chapter_name'];
1856 }
1857 $ret[$attr_id]['application'][] = $application;
1858 }
1859 $result->closeCursor();
1860 return $ret;
1861}
1862
1863function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1864{
1865 if ($attr_id <= 0 or empty ($attr_name))
1866 {
f41b492f 1867 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1868 die;
1869 }
1870 global $dbxlink;
1871 $query =
1872 "update Attribute set attr_name = '${attr_name}' " .
1873 "where attr_id = ${attr_id} limit 1";
1874 $result = $dbxlink->query ($query);
1875 if ($result == NULL)
1876 {
f41b492f 1877 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
1878 die;
1879 }
1880 return TRUE;
1881}
1882
1883function commitAddAttribute ($attr_name = '', $attr_type = '')
1884{
1885 if (empty ($attr_name))
1886 {
f41b492f 1887 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1888 die;
1889 }
1890 switch ($attr_type)
1891 {
1892 case 'uint':
1893 case 'float':
1894 case 'string':
1895 case 'dict':
1896 break;
1897 default:
f41b492f 1898 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1899 die;
1900 }
1901 return useInsertBlade
1902 (
1903 'Attribute',
1904 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1905 );
1906}
1907
1908function commitDeleteAttribute ($attr_id = 0)
1909{
1910 if ($attr_id <= 0)
1911 {
f41b492f 1912 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1913 die;
1914 }
f5575f12 1915 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
e673ee24
DO
1916}
1917
1918// FIXME: don't store garbage in chapter_no for non-dictionary types.
1919function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1920{
1921 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1922 {
f41b492f 1923 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1924 die;
1925 }
1926 return useInsertBlade
1927 (
1928 'AttributeMap',
1929 array
1930 (
1931 'attr_id' => $attr_id,
1932 'objtype_id' => $objtype_id,
1933 'chapter_no' => $chapter_no
1934 )
1935 );
1936}
1937
1938function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1939{
1940 if ($attr_id <= 0 or $objtype_id <= 0)
1941 {
f41b492f 1942 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1943 die;
1944 }
1945 global $dbxlink;
1946 $query =
1947 "delete from AttributeMap where attr_id=${attr_id} " .
1948 "and objtype_id=${objtype_id} limit 1";
1949 $result = $dbxlink->query ($query);
1950 if ($result == NULL)
1951 {
f41b492f 1952 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1953 die;
1954 }
1955 return TRUE;
1956}
1957
1958// This function returns all optional attributes for requested object
1959// as an array of records. NULL is returned on error and empty array
1960// is returned, if there are no attributes found.
24cbe8af 1961function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
1962{
1963 if ($object_id <= 0)
1964 {
f41b492f 1965 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
1966 return NULL;
1967 }
e673ee24
DO
1968 $ret = array();
1969 $query =
1970 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1971 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1972 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1973 "inner join Attribute as A using (attr_id) " .
1974 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1975 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1976 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1a576609 1977 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
065eeb52 1978 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1979 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1980 {
1981 $record = array();
1982 $record['id'] = $row['attr_id'];
1983 $record['name'] = $row['attr_name'];
1984 $record['type'] = $row['attr_type'];
1985 switch ($row['attr_type'])
1986 {
1987 case 'uint':
1988 case 'float':
1989 case 'string':
24cbe8af
DO
1990 $record['value'] = $row[$row['attr_type'] . '_value'];
1991 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1992 break;
e673ee24 1993 case 'dict':
24cbe8af
DO
1994 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1995 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
1996 $record['chapter_name'] = $row['chapter_name'];
1997 $record['key'] = $row['uint_value'];
1998 break;
1999 default:
2000 $record['value'] = NULL;
2001 break;
2002 }
2003 $ret[$row['attr_id']] = $record;
2004 }
2005 $result->closeCursor();
2006 return $ret;
2007}
2008
2009function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2010{
2011 if ($object_id <= 0 or $attr_id <= 0)
2012 {
f41b492f 2013 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2014 die;
2015 }
2016 global $dbxlink;
2017 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2018 $result = $dbxlink->query ($query);
2019 if ($result == NULL)
2020 {
f41b492f 2021 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2022 die;
2023 }
2024 return TRUE;
2025}
2026
2027// FIXME: don't share common code with use commitResetAttrValue()
2028function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2029{
2030 if ($object_id <= 0 or $attr_id <= 0)
2031 {
f41b492f 2032 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2033 die;
2034 }
2035 if (empty ($value))
2036 return commitResetAttrValue ($object_id, $attr_id);
2037 global $dbxlink;
2038 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
2039 $result = $dbxlink->query ($query1);
2040 if ($result == NULL)
2041 {
f41b492f 2042 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
2043 die;
2044 }
2045 $row = $result->fetch (PDO::FETCH_NUM);
2046 if ($row == NULL)
2047 {
f41b492f 2048 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
2049 die;
2050 }
2051 $attr_type = $row[0];
2052 $result->closeCursor();
2053 switch ($attr_type)
2054 {
2055 case 'uint':
2056 case 'float':
2057 case 'string':
2058 $column = $attr_type . '_value';
2059 break;
2060 case 'dict':
2061 $column = 'uint_value';
2062 break;
2063 default:
f41b492f 2064 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
2065 die;
2066 }
2067 $query2 =
2068 "delete from AttributeValue where " .
2069 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2070 $result = $dbxlink->query ($query2);
2071 if ($result == NULL)
2072 {
f41b492f 2073 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
2074 die;
2075 }
2076 // We know $value isn't empty here.
2077 $query3 =
2078 "insert into AttributeValue set ${column} = '${value}', " .
2079 "object_id = ${object_id}, attr_id = ${attr_id} ";
2080 $result = $dbxlink->query ($query3);
2081 if ($result == NULL)
2082 {
f41b492f 2083 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
2084 die;
2085 }
2086 return TRUE;
2087}
2088
2089function commitUseupPort ($port_id = 0)
2090{
2091 if ($port_id <= 0)
2092 {
f41b492f 2093 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
2094 die;
2095 }
2096 global $dbxlink;
2097 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2098 $result = $dbxlink->exec ($query);
2099 if ($result == NULL)
2100 {
f41b492f 2101 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
2102 die;
2103 }
2104 return TRUE;
2105
2106}
2107
2108// This is a swiss-knife blade to insert a record into a table.
2109// The first argument is table name.
2110// The second argument is an array of "name" => "value" pairs.
2111// The function returns either TRUE or FALSE (we expect one row
2112// to be inserted).
2113function useInsertBlade ($tablename, $values)
2114{
2115 global $dbxlink;
2116 $namelist = $valuelist = '';
2117 foreach ($values as $name => $value)
2118 {
2119 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2120 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2121 }
2122 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2123 $result = $dbxlink->exec ($query);
2124 if ($result != 1)
2125 return FALSE;
2126 return TRUE;
2127}
2128
2129// This swiss-knife blade deletes one record from the specified table
2130// using the specified key name and value.
f5575f12 2131function useDeleteBlade ($tablename, $keyname, $keyvalue)
e673ee24
DO
2132{
2133 global $dbxlink;
f5575f12 2134 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
e673ee24
DO
2135}
2136
5967b83d
DO
2137function useSelectBlade ($query, $caller = 'N/A')
2138{
2139 global $dbxlink;
2140 $result = $dbxlink->query ($query);
2141 if ($result == NULL)
2142 {
2143 $ei = $dbxlink->errorInfo();
105a3bc8 2144 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
2145 return NULL;
2146 }
2147 return $result;
2148}
2149
9c0b0016
DO
2150function loadConfigCache ()
2151{
4fe32e78 2152 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 2153 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
2154 $cache = array();
2155 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2156 $cache[$row['varname']] = $row;
2157 $result->closeCursor();
2158 return $cache;
2159}
2160
2161// setConfigVar() is expected to perform all necessary filtering
2162function storeConfigVar ($varname = NULL, $varvalue = NULL)
2163{
c461c579 2164 global $dbxlink;
bb6b9880 2165 if (empty ($varname) || $varvalue === NULL)
9c0b0016 2166 {
f41b492f 2167 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
2168 return FALSE;
2169 }
2170 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2171 $result = $dbxlink->query ($query);
2172 if ($result == NULL)
2173 {
f41b492f 2174 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
2175 return FALSE;
2176 }
2177 $rc = $result->rowCount();
2178 $result->closeCursor();
f7ee57a1 2179 if ($rc == 0 or $rc == 1)
9c0b0016 2180 return TRUE;
f41b492f 2181 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2182 return FALSE;
2183}
2184
fbbb74fb
DO
2185// Database version detector. Should behave corretly on any
2186// working dataset a user might have.
2187function getDatabaseVersion ()
2188{
2189 global $dbxlink;
2190 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2191 $result = $dbxlink->query ($query);
2192 if ($result == NULL)
2193 {
2194 $errorInfo = $dbxlink->errorInfo();
2195 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2196 return '0.14.4';
4d2e93f2 2197 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2198 }
2199 $rows = $result->fetchAll (PDO::FETCH_NUM);
2200 if (count ($rows) != 1 || empty ($rows[0][0]))
2201 {
2202 $result->closeCursor();
4d2e93f2 2203 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2204 }
2205 $ret = $rows[0][0];
2206 $result->closeCursor();
2207 return $ret;
2208}
2209
da04825a
DO
2210// Return an array of virtual services. For each of them list real server pools
2211// with their load balancers and other stats.
62a1dcb5
DO
2212function getSLBSummary ()
2213{
6fec9f39
DO
2214 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2215 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2216 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
3e56d972 2217 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
6fec9f39
DO
2218 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2219 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 2220 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2221 $ret = array();
2222 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2223 {
4cadac8f 2224 $vsid = $row['vsid'];
da04825a 2225 $object_id = $row['object_id'];
4cadac8f
DO
2226 if (!isset ($ret[$vsid]))
2227 {
2228 $ret[$vsid] = array();
13bffb29 2229 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2230 $ret[$vsid][$cname] = $row[$cname];
da04825a 2231 $ret[$vsid]['lblist'] = array();
4cadac8f 2232 }
6fec9f39
DO
2233 // There's only one assigned RS pool possible for each LB-VS combination.
2234 $ret[$vsid]['lblist'][$row['object_id']] = array
2235 (
2236 'id' => $row['rspool_id'],
2237 'size' => $row['rscount'],
2238 'name' => $row['pool_name']
2239 );
c3bdc503 2240 }
060ba26e 2241 $result->closeCursor();
c3bdc503 2242 return $ret;
62a1dcb5
DO
2243}
2244
da04825a
DO
2245// Get the detailed composition of a particular virtual service, namely the list
2246// of all pools, each shown with the list of objects servicing it. VS/RS configs
2247// will be returned as well.
060ba26e
DO
2248function getVServiceInfo ($vsid = 0)
2249{
2b4eee17
DO
2250 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2251 "from IPVirtualService where id = ${vsid}";
065eeb52 2252 $result = useSelectBlade ($query1, __FUNCTION__);
060ba26e 2253 $vsinfo = array ();
89fa639f 2254 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
2255 if (!$row)
2256 return NULL;
2257 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2258 $vsinfo[$cname] = $row[$cname];
2259 $vsinfo['rspool'] = array();
89fa639f
DO
2260 $result->closeCursor();
2261 unset ($result);
2b4eee17
DO
2262 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2263 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2264 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2265 "where vs_id = ${vsid} order by pool.name, object_id";
065eeb52 2266 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2267 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 2268 {
2b4eee17 2269 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 2270 {
2b4eee17
DO
2271 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2272 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2273 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2274 $vsinfo['rspool'][$row['id']]['lblist'] = array();
060ba26e 2275 }
2b4eee17
DO
2276 if ($row['object_id'] == NULL)
2277 continue;
2278 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2279 (
2280 'vsconfig' => $row['lb_vsconfig'],
2281 'rsconfig' => $row['lb_rsconfig']
2282 );
060ba26e 2283 }
89fa639f 2284 $result->closeCursor();
060ba26e
DO
2285 return $vsinfo;
2286}
2287
71b8bda1
DO
2288// Collect and return the following info about the given real server pool:
2289// basic information
2290// parent virtual service information
c1ca768c 2291// load balancers list (each with a list of VSes)
71b8bda1
DO
2292// real servers list
2293
2294function getRSPoolInfo ($id = 0)
2295{
c1ca768c 2296 $query1 = "select id, name, vsconfig, rsconfig from " .
481a7f8b 2297 "IPRSPool where id = ${id}";
065eeb52 2298 $result = useSelectBlade ($query1, __FUNCTION__);
71b8bda1 2299 $ret = array();
89fa639f 2300 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2301 if (!$row)
2302 return NULL;
70c24883 2303 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2304 $ret[$c] = $row[$c];
89fa639f
DO
2305 $result->closeCursor();
2306 unset ($result);
71b8bda1
DO
2307 $ret['lblist'] = array();
2308 $ret['rslist'] = array();
1519d6fa
DO
2309 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2310 "where rspool_id = ${id} order by object_id, vs_id";
065eeb52 2311 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2312 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2313 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2314 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2315 $result->closeCursor();
2316 unset ($result);
1f7d18fa 2317 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
676a8268 2318 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
065eeb52 2319 $result = useSelectBlade ($query3, __FUNCTION__);
89fa639f 2320 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2321 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2322 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2323 $result->closeCursor();
71b8bda1
DO
2324 return $ret;
2325}
2326
7e7a8387 2327function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2328{
79a9edb4 2329 if ($pool_id <= 0)
ca461127
DO
2330 {
2331 showError ('Invalid arguments', __FUNCTION__);
2332 die;
2333 }
79a9edb4
DO
2334 if (empty ($rsport) or $rsport == 0)
2335 $rsport = 'NULL';
ca461127
DO
2336 return useInsertBlade
2337 (
2338 'IPRealServer',
2339 array
2340 (
2341 'rsip' => "inet_aton('${rsip}')",
2342 'rsport' => $rsport,
2343 'rspool_id' => $pool_id,
bcbeadb4 2344 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2345 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2346 )
2347 );
2348}
2349
c63a8d6e 2350function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21
DO
2351{
2352 if (empty ($vip) or $vport <= 0 or empty ($proto))
c63a8d6e
DO
2353 return __FUNCTION__ . ': invalid arguments';
2354 if (!useInsertBlade
d6517a21
DO
2355 (
2356 'IPVirtualService',
2357 array
2358 (
2359 'vip' => "inet_aton('${vip}')",
2360 'vport' => $vport,
2361 'proto' => "'${proto}'",
2362 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2363 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2364 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2365 )
c63a8d6e
DO
2366 ))
2367 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2368 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2369}
2370
c1ca768c 2371function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2372{
c1ca768c 2373 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2374 {
2375 showError ('Invalid arguments', __FUNCTION__);
2376 die;
2377 }
2378 return useInsertBlade
2379 (
2380 'IPLoadBalancer',
2381 array
2382 (
2383 'object_id' => $object_id,
2384 'rspool_id' => $pool_id,
c1ca768c 2385 'vs_id' => $vs_id,
3241551e
DO
2386 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2387 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2388 )
ca461127
DO
2389 );
2390}
2391
fb1c4a54
DO
2392function commitDeleteRS ($id = 0)
2393{
2394 if ($id <= 0)
2395 return FALSE;
f5575f12 2396 return useDeleteBlade ('IPRealServer', 'id', $id);
fb1c4a54
DO
2397}
2398
d6517a21
DO
2399function commitDeleteVS ($id = 0)
2400{
2401 if ($id <= 0)
2402 return FALSE;
01b6b4d6 2403 return useDeleteBlade ('IPVirtualService', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2404}
2405
c1ca768c 2406function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2407{
2408 global $dbxlink;
c4d85fd1 2409 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2410 return FALSE;
c1ca768c
DO
2411 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2412 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2413 $result = $dbxlink->exec ($query);
2414 if ($result === NULL)
2415 return FALSE;
2416 elseif ($result != 1)
2417 return FALSE;
2418 else
2419 return TRUE;
2420}
2421
fb1c4a54
DO
2422function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2423{
79a9edb4 2424 if ($rsid <= 0)
fb1c4a54
DO
2425 {
2426 showError ('Invalid args', __FUNCTION__);
2427 die;
2428 }
2429 if (long2ip (ip2long ($rsip)) !== $rsip)
2430 {
2431 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2432 die;
2433 }
79a9edb4
DO
2434 if (empty ($rsport) or $rsport == 0)
2435 $rsport = 'NULL';
fb1c4a54
DO
2436 global $dbxlink;
2437 $query =
2438 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2439 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2440 " where id = ${rsid} limit 1";
2441 $result = $dbxlink->query ($query);
2442 if ($result == NULL)
2443 {
2444 showError ("SQL query '${query}' failed", __FUNCTION__);
2445 die;
2446 }
2447 return TRUE;
2448}
2449
c1ca768c 2450function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2451{
c1ca768c 2452 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2453 {
2454 showError ('Invalid args', __FUNCTION__);
2455 die;
2456 }
2457 global $dbxlink;
2458 $query =
2459 "update IPLoadBalancer set vsconfig = " .
2460 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2461 ', rsconfig = ' .
2462 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2463 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2464 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2465 $result = $dbxlink->exec ($query);
2466 if ($result === NULL)
2467 return FALSE;
3241551e
DO
2468 else
2469 return TRUE;
2470}
2471
d6517a21
DO
2472function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2473{
2474 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2475 {
2476 showError ('Invalid args', __FUNCTION__);
2477 die;
2478 }
2479 global $dbxlink;
2480 $query = "update IPVirtualService set " .
2481 "vip = inet_aton('${vip}'), " .
2482 "vport = ${vport}, " .
2483 "proto = '${proto}', " .
2484 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2485 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2486 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2487 " where id = ${vsid} limit 1";
d6517a21
DO
2488 $result = $dbxlink->exec ($query);
2489 if ($result === NULL)
2490 return FALSE;
d6517a21
DO
2491 else
2492 return TRUE;
2493}
2494
e57dca7f 2495// Return the list of virtual services, indexed by vs_id.
70c24883 2496// Each record will be shown with its basic info plus RS pools counter.
11c8e4be 2497function getVSList ($tagfilter = array(), $tfmode = 'any')
e57dca7f 2498{
81736ac1 2499 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2500 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2501 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
996b02ba 2502 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
83d3dde9 2503 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
065eeb52 2504 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2505 $ret = array ();
e57dca7f 2506 while ($row = $result->fetch (PDO::FETCH_ASSOC))
d6517a21 2507 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
4b0932b6 2508 $ret[$row['id']][$cname] = $row[$cname];
e57dca7f 2509 $result->closeCursor();
4b0932b6 2510 return $ret;
e57dca7f
DO
2511}
2512
9a81d416 2513// Return the list of RS pool, indexed by pool id.
11c8e4be 2514function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
9a81d416 2515{
81736ac1 2516 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2517 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2518 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2e4170aa 2519 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
56c076ed 2520 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
065eeb52 2521 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2522 $ret = array ();
9a81d416 2523 while ($row = $result->fetch (PDO::FETCH_ASSOC))
70c24883 2524 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
4b0932b6 2525 $ret[$row['id']][$cname] = $row[$cname];
9a81d416 2526 $result->closeCursor();
4b0932b6 2527 return $ret;
9a81d416
DO
2528}
2529
5a1680d2
DO
2530function loadThumbCache ($rack_id = 0)
2531{
5a1680d2
DO
2532 $ret = NULL;
2533 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2534 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2535 $row = $result->fetch (PDO::FETCH_ASSOC);
2536 if ($row)
2537 $ret = base64_decode ($row['thumb_data']);
2538 $result->closeCursor();
2539 return $ret;
2540}
2541
2542function saveThumbCache ($rack_id = 0, $cache = NULL)
2543{
2544 global $dbxlink;
2545 if ($rack_id == 0 or $cache == NULL)
2546 {
2547 showError ('Invalid arguments', __FUNCTION__);
2548 return;
2549 }
2550 $data = base64_encode ($cache);
2551 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2552 $result = $dbxlink->exec ($query);
2553}
9a81d416 2554
c7fe33be
DO
2555function resetThumbCache ($rack_id = 0)
2556{
2557 global $dbxlink;
2558 if ($rack_id == 0)
2559 {
2560 showError ('Invalid argument', __FUNCTION__);
2561 return;
2562 }
2563 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2564 $result = $dbxlink->exec ($query);
2565}
2566
748805bf
DO
2567// Return the list of attached RS pools for the given object. As long as we have
2568// the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2569// by vs_id, because there will be only one RS pool listed for each VS of the
2570// current object.
78e7b769
DO
2571function getRSPoolsForObject ($object_id = 0)
2572{
2573 if ($object_id <= 0)
2574 {
2575 showError ('Invalid object_id', __FUNCTION__);
2576 return NULL;
2577 }
748805bf 2578 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2579 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
748805bf
DO
2580 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2581 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2582 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2583 "where lb.object_id = ${object_id} " .
2584 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2585 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2586 $ret = array ();
78e7b769 2587 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2588 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2589 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2590 $result->closeCursor();
748805bf 2591 return $ret;
78e7b769
DO
2592}
2593
c63a8d6e 2594function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2595{
c63a8d6e
DO
2596 if (empty ($name))
2597 return __FUNCTION__ . ': invalid arguments';
2598 if (!useInsertBlade
5ad76f01
DO
2599 (
2600 'IPRSPool',
2601 array
2602 (
5ad76f01
DO
2603 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2604 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2605 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2606 )
c63a8d6e
DO
2607 ))
2608 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2609 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2610}
2611
2612function commitDeleteRSPool ($pool_id = 0)
2613{
2614 global $dbxlink;
2615 if ($pool_id <= 0)
2616 return FALSE;
01b6b4d6 2617 return useDeleteBlade ('IPRSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2618}
2619
2620function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2621{
2622 if ($pool_id <= 0)
2623 {
2624 showError ('Invalid arg', __FUNCTION__);
2625 die;
2626 }
2627 global $dbxlink;
2628 $query = "update IPRSPool set " .
2629 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2630 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2631 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2632 " where id = ${pool_id} limit 1";
2633 $result = $dbxlink->exec ($query);
2634 if ($result === NULL)
2635 return FALSE;
2636 elseif ($result != 1)
2637 return FALSE;
2638 else
2639 return TRUE;
2640}
2641
8253d9f0
DO
2642function getRSList ()
2643{
1f7d18fa 2644 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
8253d9f0 2645 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
065eeb52 2646 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2647 $ret = array ();
8253d9f0 2648 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2649 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2650 $ret[$row['id']][$cname] = $row[$cname];
2651 $result->closeCursor();
2652 return $ret;
2653}
2654
2655// Return the list of all currently configured load balancers with their pool count.
2656function getLBList ()
2657{
4b0932b6
DO
2658 $query = "select object_id, count(rspool_id) as poolcount " .
2659 "from IPLoadBalancer group by object_id order by object_id";
065eeb52 2660 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2661 $ret = array ();
2662 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2663 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2664 $result->closeCursor();
4b0932b6 2665 return $ret;
8253d9f0
DO
2666}
2667
9e677cbd
DO
2668// For the given object return: it vsconfig/rsconfig; the list of RS pools
2669// attached (each with vsconfig/rsconfig in turn), each with the list of
2670// virtual services terminating the pool. Each pool also lists all real
2671// servers with rsconfig.
2987fc1f 2672function getSLBConfig ($object_id)
9e677cbd
DO
2673{
2674 if ($object_id <= 0)
2675 {
2676 showError ('Invalid arg', __FUNCTION__);
2677 return NULL;
2678 }
9e677cbd 2679 $ret = array();
d91f08f3
DO
2680 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2681 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2682 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2683 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3
DO
2684 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2685 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2686 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
9e677cbd 2687 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2688 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2689 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2690 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2691 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2692 {
d91f08f3
DO
2693 $vs_id = $row['vs_id'];
2694 if (!isset ($ret[$vs_id]))
2695 {
2696 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)
2697 $ret[$vs_id][$c] = $row[$c];
2698 $ret[$vs_id]['rslist'] = array();
2699 }
2700 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2701 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2702 }
2703 $result->closeCursor();
2704 return $ret;
2705}
1f7d18fa
DO
2706
2707function commitSetInService ($rs_id = 0, $inservice = '')
2708{
2709 if ($rs_id <= 0 or empty ($inservice))
2710 {
2711 showError ('Invalid args', __FUNCTION__);
2712 return NULL;
2713 }
2714 global $dbxlink;
2715 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2716 $result = $dbxlink->exec ($query);
2717 if ($result === NULL)
2718 return FALSE;
2719 elseif ($result != 1)
2720 return FALSE;
2721 else
2722 return TRUE;
2723}
2724
ad0e4754
DO
2725function executeAutoPorts ($object_id = 0, $type_id = 0)
2726{
2727 if ($object_id == 0 or $type_id == 0)
2728 {
2729 showError ('Invalid arguments', __FUNCTION__);
2730 die;
2731 }
f3f0161f 2732 $ret = TRUE;
118e4c38 2733 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2734 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2735 return $ret;
ad0e4754
DO
2736}
2737
6e49bd1f 2738// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2739// generated/deducted later at higher levels.
aab37bc0 2740// Result is a chain: randomly indexed taginfo list.
f9bc186f 2741function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2742{
f9bc186f
DO
2743 if ($entity_realm == '' or $entity_id <= 0)
2744 {
2745 showError ('Invalid or missing arguments', __FUNCTION__);
2746 return NULL;
2747 }
a6e8d544 2748 $ret = array();
edf0993c
DO
2749 $query = "select tt.id, tag from " .
2750 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2751 "where target_realm = '${entity_realm}' and target_id = ${entity_id} " .
2752 "order by tt.tag";
2753 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2754 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2755 $ret[$row['id']] = $row;
a6e8d544 2756 $result->closeCursor();
aab37bc0 2757 return getExplicitTagsOnly ($ret);
5967b83d
DO
2758}
2759
f9bc186f
DO
2760function loadRackObjectTags ($id)
2761{
2762 return loadEntityTags ('object', $id);
2763}
2764
2765function loadIPv4PrefixTags ($id)
2766{
2767 return loadEntityTags ('ipv4net', $id);
2768}
2769
41bd8c87
DO
2770function loadRackTags ($id)
2771{
2772 return loadEntityTags ('rack', $id);
2773}
2774
d817ba03
DO
2775function loadIPv4VSTags ($id)
2776{
2777 return loadEntityTags ('ipv4vs', $id);
2778}
2779
2780function loadIPv4RSPoolTags ($id)
2781{
2782 return loadEntityTags ('ipv4rspool', $id);
2783}
2784
ebae41b3
DO
2785function loadUserTags ($user_id)
2786{
2787 return loadEntityTags ('user', $user_id);
2788}
2789
351c0966 2790// Return a tag chain with all DB tags on it.
5967b83d
DO
2791function getTagList ()
2792{
20c901a7 2793 $ret = array();
5b7bd02e
DO
2794 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2795 "from TagTree left join TagStorage on id = tag_id " .
2796 "group by id, target_realm order by tag";
065eeb52 2797 $result = useSelectBlade ($query, __FUNCTION__);
fb7a4967
DO
2798 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2799 // which is utf8_general_ci for UTF-8.
5967b83d 2800 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2801 {
7cc02fc1 2802 if (!isset ($ret[$row['id']]))
20c901a7 2803 $ret[$row['id']] = array
5b7bd02e
DO
2804 (
2805 'id' => $row['id'],
2806 'tag' => $row['tag'],
fb7a4967 2807 'ci' => $ci++,
5b7bd02e
DO
2808 'parent_id' => $row['parent_id'],
2809 'refcnt' => array()
2810 );
2811 if ($row['realm'])
20c901a7 2812 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2813 }
5967b83d 2814 $result->closeCursor();
20c901a7 2815 return $ret;
5967b83d
DO
2816}
2817
fe7044ad
DO
2818function commitCreateTag ($tagname = '', $parent_id = 0)
2819{
2820 if ($tagname == '' or $parent_id === 0)
2821 return "Invalid args to " . __FUNCTION__;
2822 $result = useInsertBlade
2823 (
2824 'TagTree',
2825 array
2826 (
2827 'tag' => "'${tagname}'",
2828 'parent_id' => $parent_id
2829 )
2830 );
2831 if ($result)
2832 return '';
2833 else
2834 return "SQL query failed in " . __FUNCTION__;
2835}
2836
2837function commitDestroyTag ($tagid = 0)
2838{
2839 if ($tagid == 0)
2840 return 'Invalid arg to ' . __FUNCTION__;
f5575f12 2841 if (useDeleteBlade ('TagTree', 'id', $tagid))
fe7044ad
DO
2842 return '';
2843 else
2844 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2845}
f9bc186f 2846
49fb1027 2847function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2848{
49fb1027
DO
2849 if ($parent_id == 0)
2850 $parent_id = 'NULL';
f9bc186f 2851 global $dbxlink;
49fb1027
DO
2852 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2853 "where id = ${tag_id} limit 1";
f9bc186f
DO
2854 $result = $dbxlink->exec ($query);
2855 if ($result === NULL)
49fb1027
DO
2856 return 'SQL query failed in ' . __FUNCTION__;
2857 return '';
f9bc186f
DO
2858}
2859
01b6b4d6
DO
2860// Drop the whole chain stored.
2861function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af
DO
2862{
2863 global $dbxlink;
2864 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2865 $result = $dbxlink->exec ($query);
2866 if ($result === NULL)
2867 return FALSE;
2868 else
2869 return TRUE;
2870}
2871
01b6b4d6
DO
2872// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2873function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2874{
2875 global $dbxlink;
2876 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id} and tag_id = ${tag_id}";
2877 $result = $dbxlink->exec ($query);
2878 if ($result === NULL)
2879 return FALSE;
2880 else
2881 return TRUE;
2882}
2883
351c0966 2884// Push a record into TagStorage unconditionally.
3355ca56 2885function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2886{
3355ca56
DO
2887 if (empty ($realm))
2888 return FALSE;
eb6ea26f
DO
2889 return useInsertBlade
2890 (
2891 'TagStorage',
2892 array
2893 (
2894 'target_realm' => "'${realm}'",
2895 'target_id' => $entity_id,
2896 'tag_id' => $tag_id,
2897 )
2898 );
2899}
2900
351c0966 2901// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
2902// on the implicit list already). Then remove any other records, which
2903// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
2904// that both the tag base is still minimal and all requested tags appear on
2905// the resulting tag chain.
abef7149
DO
2906// Return TRUE, if any changes were committed.
2907function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2908{
2909 // Put the current explicit sub-chain into a buffer and merge all tags from
2910 // the extra chain, which aren't there yet.
2911 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2912 foreach ($extrachain as $extratag)
2913 if (!tagOnChain ($extratag, $newchain))
2914 $newchain[] = $extratag;
2915 // Then minimize the working buffer and check if it differs from the original
2916 // chain we started with. If it is so, save the work and signal the upper layer.
2917 $newchain = getExplicitTagsOnly ($newchain);
2918 if (tagChainCmp ($oldchain, $newchain))
2919 {
01b6b4d6 2920 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
2921 foreach ($newchain as $taginfo)
2922 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2923 return TRUE;
2924 }
2925 return FALSE;
351c0966
DO
2926}
2927
2928// Presume, that the target record has no tags attached.
2929function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2930{
2931 if (!count ($tagidlist))
c63a8d6e
DO
2932 return '';
2933 if (!$last_insert_id)
2934 $last_insert_id = lastInsertID();
2935 $errcount = 0;
abef7149 2936 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 2937 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
2938 $errcount++;
2939 if (!$errcount)
2940 return '';
2941 else
2942 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2943}
2944
42023f03
DO
2945function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2946{
2947 // $range is in x.x.x.x/x format, split into ip/mask vars
2948 $rangeArray = explode('/', $range);
2949 if (count ($rangeArray) != 2)
2950 return "Invalid IPv4 prefix '${range}'";
2951 $ip = $rangeArray[0];
2952 $mask = $rangeArray[1];
2953
2954 if (empty ($ip) or empty ($mask))
2955 return "Invalid IPv4 prefix '${range}'";
2956 $ipL = ip2long($ip);
2957 $maskL = ip2long($mask);
2958 if ($ipL == -1 || $ipL === FALSE)
2959 return 'Bad IPv4 address';
2960 if ($mask < 32 && $mask > 0)
2961 $maskL = $mask;
2962 else
2963 {
2964 $maskB = decbin($maskL);
2965 if (strlen($maskB)!=32)
2966 return 'Invalid netmask';
2967 $ones=0;
2968 $zeroes=FALSE;
2969 foreach( str_split ($maskB) as $digit)
2970 {
2971 if ($digit == '0')
2972 $zeroes = TRUE;
2973 if ($digit == '1')
2974 {
2975 $ones++;
2976 if ($zeroes == TRUE)
2977 return 'Invalid netmask';
2978 }
2979 }
2980 $maskL = $ones;
2981 }
2982 $binmask = binMaskFromDec($maskL);
2983 $ipL = $ipL & $binmask;
42023f03
DO
2984 $result = useInsertBlade
2985 (
2986 'IPRanges',
2987 array
2988 (
2989 'ip' => sprintf ('%u', $ipL),
2990 'mask' => "'${maskL}'",
2991 'name' => "'${name}'"
2992 )
2993 );
2994
2995 if ($is_bcast and $maskL < 31)
2996 {
2997 $network_addr = long2ip ($ipL);
2998 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2999 updateAddress ($network_addr, 'network', 'yes');
3000 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3001 }
351c0966 3002 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
3003}
3004
3005// FIXME: This function doesn't wipe relevant records from IPAddress table.
3006function destroyIPv4Prefix ($id = 0)
3007{
3008 if ($id <= 0)
3009 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
f5575f12 3010 if (!useDeleteBlade ('IPRanges', 'id', $id))
42023f03 3011 return __FUNCTION__ . ': SQL query #1 failed';
01b6b4d6 3012 if (!destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
3013 return __FUNCTION__ . ': SQL query #2 failed';
3014 return '';
3015}
3016
ebae41b3
DO
3017function loadScript ($name)
3018{
3019 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3020 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
3021 if ($row !== FALSE)
3022 return $row[0];
3023 else
3024 return NULL;
ebae41b3
DO
3025}
3026
3027function saveScript ($name, $text)
3028{
3029 if (empty ($name))
3030 {
3031 showError ('Invalid argument');
3032 return FALSE;
3033 }
4a6a28f1 3034 // delete regardless of existence
f5575f12 3035 useDeleteBlade ('Script', 'script_name', "'${name}'");
4a6a28f1 3036 return useInsertBlade
ebae41b3
DO
3037 (
3038 'Script',
3039 array
3040 (
3041 'script_name' => "'${name}'",
3042 'script_text' => "'${text}'"
3043 )
3044 );
3045}
3046
3047function saveUserPassword ($user_id, $newp)
bcd37231 3048{
ebae41b3
DO
3049 $newhash = hash (PASSWORD_HASH, $newp);
3050 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
bcd37231
DO
3051}
3052
cf6c472b
DO
3053function objectIsPortless ($id = 0)
3054{
3055 if ($id <= 0)
3056 {
3057 showError ('Invalid argument', __FUNCTION__);
3058 return;
3059 }
3060 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3061 {
3062 showError ('SQL query failed', __FUNCTION__);
3063 return;
3064 }
3065 $row = $result->fetch (PDO::FETCH_NUM);
3066 $count = $row[0];
3067 $result->closeCursor();
3068 unset ($result);
81736ac1 3069 return $count === '0';
cf6c472b
DO
3070}
3071
15555995
DO
3072function recordExists ($id = 0, $realm = 'object')
3073{
3074 if ($id <= 0)
3075 return FALSE;
3076 $table = array
3077 (
3078 'object' => 'RackObject',
1a315491
DO
3079 'ipv4net' => 'IPRanges',
3080 'user' => 'UserAccount',
15555995
DO
3081 );
3082 $idcol = array
3083 (
3084 'object' => 'id',
1a315491
DO
3085 'ipv4net' => 'id',
3086 'user' => 'user_id',
15555995
DO
3087 );
3088 $query = 'select count(*) from ' . $table[$realm] . ' where ' . $idcol[$realm] . ' = ' . $id;
3089 if (($result = useSelectBlade ($query, __FUNCTION__)) == NULL)
3090 {
3091 showError ('SQL query failed', __FUNCTION__);
3092 return FALSE;
3093 }
3094 $row = $result->fetch (PDO::FETCH_NUM);
3095 $count = $row[0];
3096 $result->closeCursor();
3097 unset ($result);
3098 return $count === '1';
3099}
3100
0f3c6639
DO
3101function tagExistsInDatabase ($tname)
3102{
3103 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3104 $row = $result->fetch (PDO::FETCH_NUM);
3105 $count = $row[0];
3106 $result->closeCursor();
3107 unset ($result);
3108 return $count !== '0';
3109}
3110
d983f70a
DO
3111function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3112{
3113 if (NULL === getIPv4AddressNetworkId ($localip))
3114 return "$localip: Non existant ip";
3115 if (NULL === getIPv4AddressNetworkId ($localip))
3116 return "$remoteip: Non existant ip";
3117 if ( ($localport <= 0) or ($localport >= 65536) )
3118 return "$localport: invaild port";
3119 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3120 return "$remoteport: invaild port";
3121
3122 $result = useInsertBlade
3123 (
3124 'PortForwarding',
3125 array
3126 (
3127 'object_id' => $object_id,
3128 'localip' => "INET_ATON('${localip}')",
3129 'remoteip' => "INET_ATON('$remoteip')",
3130 'localport' => $localport,
3131 'remoteport' => $remoteport,
3132 'proto' => "'${proto}'",
3133 'description' => "'${description}'",
3134 )
3135 );
3136 if ($result)
3137 return '';
3138 else
3139 return __FUNCTION__ . ': Failed to insert the rule.';
3140}
3141
3142function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3143{
3144 global $dbxlink;
3145
3146 $query =
3147 "delete from PortForwarding where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3148 $result = $dbxlink->exec ($query);
3149 return '';
3150}
3151
3152function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3153{
3154 global $dbxlink;
3155
3156 $query =
3157 "update PortForwarding set description='$description' where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3158 $result = $dbxlink->exec ($query);
3159 return '';
3160}
3161
3162function getNATv4ForObject ($object_id)
3163{
3164 $ret = array();
3165 $ret['out'] = array();
3166 $ret['in'] = array();
3167 $query =
3168 "select ".
3169 "proto, ".
3170 "INET_NTOA(localip) as localip, ".
3171 "localport, ".
3172 "INET_NTOA(remoteip) as remoteip, ".
3173 "remoteport, ".
3174 "ipa1.name as local_addr_name, " .
3175 "ipa2.name as remote_addr_name, " .
3176 "description ".
3177 "from PortForwarding ".
3178 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
3179 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
3180 "where object_id='$object_id' ".
3181 "order by localip, localport, proto, remoteip, remoteport";
3182 $result = useSelectBlade ($query, __FUNCTION__);
3183 $count=0;
3184 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3185 {
3186 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3187 $ret['out'][$count][$cname] = $row[$cname];
3188 $count++;
3189 }
3190 $result->closeCursor();
3191 unset ($result);
3192
3193 $query =
3194 "select ".
3195 "proto, ".
3196 "INET_NTOA(localip) as localip, ".
3197 "localport, ".
3198 "INET_NTOA(remoteip) as remoteip, ".
3199 "remoteport, ".
3200 "PortForwarding.object_id as object_id, ".
3201 "RackObject.name as object_name, ".
3202 "description ".
3203 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
3204 "where IPBonds.object_id='$object_id' ".
3205 "order by remoteip, remoteport, proto, localip, localport";
3206 $result = useSelectBlade ($query, __FUNCTION__);
3207 $count=0;
3208 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3209 {
3210 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3211 $ret['in'][$count][$cname] = $row[$cname];
3212 $count++;
3213 }
3214 $result->closeCursor();
3215
3216 return $ret;
3217}
3218
3219// This function performs search and then calculates score for each result.
3220// Given previous search results in $objects argument, it adds new results
3221// to the array and updates score for existing results, if it is greater than
3222// existing score.
3223function mergeSearchResults (&$objects, $terms, $fieldname)
3224{
3225 global $dbxlink;
3226 $query =
3227 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3228 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3229 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
3230 $count = 0;
3231 foreach (explode (' ', $terms) as $term)
3232 {
3233 if ($count) $query .= ' or ';
3234 $query .= "${fieldname} like '%$term%'";
3235 $count++;
3236 }
3237 $query .= " order by ${fieldname}";
3238 $result = useSelectBlade ($query, __FUNCTION__);
3239// FIXME: this dead call was executed 4 times per 1 object search!
3240// $typeList = getObjectTypeList();
3241 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3242 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3243 {
3244 foreach ($clist as $cname)
3245 $object[$cname] = $row[$cname];
3246 $object['score'] = 0;
3247 $object['dname'] = displayedName ($object);
3248 unset ($object['objtype_id']);
3249 foreach (explode (' ', $terms) as $term)
3250 if (strstr ($object['name'], $term))
3251 $object['score'] += 1;
3252 unset ($object['name']);
3253 if (!isset ($objects[$row['id']]))
3254 $objects[$row['id']] = $object;
3255 elseif ($objects[$row['id']]['score'] < $object['score'])
3256 $objects[$row['id']]['score'] = $object['score'];
3257 }
3258 return $objects;
3259}
3260
09620506
DO
3261function getLostIPv4Addresses ()
3262{
f7414fa5 3263 dragon();
09620506
DO
3264}
3265
e673ee24 3266?>