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