r1282 + limit progress dots by 50 per line
[racktables] / inc / functions.php
CommitLineData
b325120a 1<?php
e673ee24
DO
2/*
3*
4* This file is a library of computational functions for RackTables.
5*
6*/
7
8$loclist[0] = 'front';
9$loclist[1] = 'interior';
10$loclist[2] = 'rear';
11$loclist['front'] = 0;
12$loclist['interior'] = 1;
13$loclist['rear'] = 2;
14$template[0] = array (TRUE, TRUE, TRUE);
15$template[1] = array (TRUE, TRUE, FALSE);
16$template[2] = array (FALSE, TRUE, TRUE);
17$template[3] = array (TRUE, FALSE, FALSE);
18$template[4] = array (FALSE, TRUE, FALSE);
19$template[5] = array (FALSE, FALSE, TRUE);
20$templateWidth[0] = 3;
21$templateWidth[1] = 2;
22$templateWidth[2] = 2;
23$templateWidth[3] = 1;
24$templateWidth[4] = 1;
25$templateWidth[5] = 1;
26
27// Objects of some types should be explicitly shown as
28// anonymous (labelless). This function is a single place where the
29// decision about displayed name is made.
30function displayedName ($objectData)
31{
32 if ($objectData['name'] != '')
33 return $objectData['name'];
9c0b0016 34 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
a0ec6295 35 return "ANONYMOUS " . $objectData['objtype_name'];
e673ee24 36 else
a0ec6295 37 return "[${objectData['objtype_name']}]";
e673ee24
DO
38}
39
40// This function finds height of solid rectangle of atoms, which are all
41// assigned to the same object. Rectangle base is defined by specified
42// template.
43function rectHeight ($rackData, $startRow, $template_idx)
44{
45 $height = 0;
46 // The first met object_id is used to match all the folowing IDs.
47 $object_id = 0;
48 global $template;
49 do
50 {
51 for ($locidx = 0; $locidx < 3; $locidx++)
52 {
53 // At least one value in template is TRUE, but the following block
54 // can meet 'skipped' atoms. Let's ensure we have something after processing
55 // the first row.
56 if ($template[$template_idx][$locidx])
57 {
58 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
59 break 2;
60 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
61 break 2;
62 if ($object_id == 0)
63 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
64 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
65 break 2;
66 }
67 }
68 // If the first row can't offer anything, bail out.
69 if ($height == 0 and $object_id == 0)
70 break;
71 $height++;
72 }
73 while ($startRow - $height > 0);
74// echo "for startRow==${startRow} and template==(${template[0]}, ${template[1]}, ${template[2]}) height==${height}<br>\n";
75 return $height;
76}
77
78// This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
79// attributes.
80function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
81{
82 global $template, $templateWidth;
83 $colspan = 0;
84 for ($height = 0; $height < $maxheight; $height++)
85 {
86 for ($locidx = 0; $locidx < 3; $locidx++)
87 {
88 if ($template[$template_idx][$locidx])
89 {
90 // Add colspan/rowspan to the first row met and mark the following ones to skip.
91 if ($colspan != 0)
92 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
93 else
94 {
95 $colspan = $templateWidth[$template_idx];
96 if ($colspan > 1)
97 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
98 if ($maxheight > 1)
99 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
100 }
101 }
102 }
103 }
104 return;
105}
106
107// This function finds rowspan/solspan/skipped atom attributes for renderRack()
108// What we actually have to do is to find all possible rectangles for each objects
109// and then find the widest of those with the maximal square.
110function markAllSpans (&$rackData = NULL)
111{
112 if ($rackData == NULL)
113 {
114 showError ('Invalid rackData in markupAllSpans()');
115 return;
116 }
117 for ($i = $rackData['height']; $i > 0; $i--)
118 {
119 // calculate height of 6 possible span templates (array is presorted by width descending)
120 global $template;
121 for ($j = 0; $j < 6; $j++)
122 $height[$j] = rectHeight ($rackData, $i, $j);
123 // find the widest rectangle of those with maximal height
124 $maxheight = max ($height);
125 if ($maxheight > 0)
126 {
127 $best_template_index = 0;
128 for ($j = 0; $j < 6; $j++)
129 if ($height[$j] == $maxheight)
130 {
131 $best_template_index = $j;
132 break;
133 }
134 // distribute span marks
135 markSpan ($rackData, $i, $maxheight, $best_template_index);
136 }
137 }
138}
139
140function delRow ($row_id = 0)
141{
142 if ($row_id == 0)
143 {
144 showError ('Not all required args to delRow() are present.');
145 return;
146 }
147 if (!isset ($_REQUEST['confirmed']) || $_REQUEST['confirmed'] != 'true')
148 {
149 echo "Press <a href='?op=del_row&row_id=${row_id}&confirmed=true'>here</a> to confirm rack row deletion.";
150 return;
151 }
152 global $dbxlink;
153 echo 'Deleting rack row information: ';
154 $result = $dbxlink->query ("update RackRow set deleted = 'yes' where id=${row_id} limit 1");
155 if ($result->rowCount() != 1)
156 {
157 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1');
158 return;
159 }
160 echo 'OK<br>';
161 recordHistory ('RackRow', "id = ${row_id}");
162 echo "Information was deleted. You may return to <a href='?op=list_rows&editmode=on'>rack row list</a>.";
163}
164
165function delRack ($rack_id = 0)
166{
167 if ($rack_id == 0)
168 {
169 showError ('Not all required args to delRack() are present.');
170 return;
171 }
172 if (!isset ($_REQUEST['confirmed']) || $_REQUEST['confirmed'] != 'true')
173 {
174 echo "Press <a href='?op=del_rack&rack_id=${rack_id}&confirmed=true'>here</a> to confirm rack deletion.";
175 return;
176 }
177 global $dbxlink;
178 echo 'Deleting rack information: ';
179 $result = $dbxlink->query ("update Rack set deleted = 'yes' where id=${rack_id} limit 1");
180 if ($result->rowCount() != 1)
181 {
182 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1');
183 return;
184 }
185 echo 'OK<br>';
186 recordHistory ('Rack', "id = ${rack_id}");
187 echo "Information was deleted. You may return to <a href='?op=list_racks&editmode=on'>rack list</a>.";
188}
189
190function delObject ($object_id = 0)
191{
192 if ($object_id == 0)
193 {
194 showError ('Not all required args to delObject() are present.');
195 return;
196 }
197 if (!isset ($_REQUEST['confirmed']) || $_REQUEST['confirmed'] != 'true')
198 {
199 echo "Press <a href='?op=del_object&object_id=${object_id}&confirmed=true'>here</a> to confirm object deletion.";
200 return;
201 }
202 global $dbxlink;
203 echo 'Deleting object information: ';
204 $result = $dbxlink->query ("update RackObject set deleted = 'yes' where id=${object_id} limit 1");
205 if ($result->rowCount() != 1)
206 {
207 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1');
208 return;
209 }
210 echo 'OK<br>';
211 recordHistory ('RackObject', "id = ${object_id}");
212 echo "Information was deleted. You may return to <a href='?op=list_objects&editmode=on'>object list</a>.";
213}
214
215// We can mount 'F' atoms and unmount our own 'T' atoms.
216function applyObjectMountMask (&$rackData, $object_id)
217{
218 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
219 for ($locidx = 0; $locidx < 3; $locidx++)
220 switch ($rackData[$unit_no][$locidx]['state'])
221 {
222 case 'F':
223 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
224 break;
225 case 'T':
226 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
227 break;
228 default:
229 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
230 }
231}
232
233// Design change means transition between 'F' and 'A' and back.
234function applyRackDesignMask (&$rackData)
235{
236 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
237 for ($locidx = 0; $locidx < 3; $locidx++)
238 switch ($rackData[$unit_no][$locidx]['state'])
239 {
240 case 'F':
241 case 'A':
242 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
243 break;
244 default:
245 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
246 }
247}
248
249// The same for 'F' and 'U'.
250function applyRackProblemMask (&$rackData)
251{
252 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
253 for ($locidx = 0; $locidx < 3; $locidx++)
254 switch ($rackData[$unit_no][$locidx]['state'])
255 {
256 case 'F':
257 case 'U':
258 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
259 break;
260 default:
261 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
262 }
263}
264
265// This mask should allow toggling 'T' and 'W' on object's rackspace.
266function applyObjectProblemMask (&$rackData)
267{
268 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
269 for ($locidx = 0; $locidx < 3; $locidx++)
270 switch ($rackData[$unit_no][$locidx]['state'])
271 {
272 case 'T':
273 case 'W':
274 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
275 break;
276 default:
277 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
278 }
279}
280
281// This function highlights specified object (and removes previous highlight).
282function highlightObject (&$rackData, $object_id)
283{
284 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
285 for ($locidx = 0; $locidx < 3; $locidx++)
286 if
287 (
288 $rackData[$unit_no][$locidx]['state'] == 'T' and
289 $rackData[$unit_no][$locidx]['object_id'] == $object_id
290 )
291 $rackData[$unit_no][$locidx]['hl'] = 'h';
292 else
293 unset ($rackData[$unit_no][$locidx]['hl']);
294}
295
296// This function marks atoms to selected or not depending on their current state.
297function markupAtomGrid (&$data, $checked_state)
298{
299 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
300 for ($locidx = 0; $locidx < 3; $locidx++)
301 {
302 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
303 continue;
304 if ($data[$unit_no][$locidx]['state'] == $checked_state)
305 $data[$unit_no][$locidx]['checked'] = ' checked';
306 else
307 $data[$unit_no][$locidx]['checked'] = '';
308 }
309}
310
311// This function is almost a clone of processGridForm(), but doesn't save anything to database
312// Return value is the changed rack data.
313// Here we assume that correct filter has already been applied, so we just
314// set or unset checkbox inputs w/o changing atom state.
315function mergeGridFormToRack (&$rackData)
316{
317 $rack_id = $rackData['id'];
318 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
319 for ($locidx = 0; $locidx < 3; $locidx++)
320 {
321 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
322 continue;
323 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
324 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
325 $rackData[$unit_no][$locidx]['checked'] = ' checked';
326 else
327 $rackData[$unit_no][$locidx]['checked'] = '';
328 }
329}
330
331function binMaskFromDec ($maskL)
332{
333 $binmask=0;
334 for ($i=0; $i<$maskL; $i++)
335 {
336 $binmask*=2;
337 $binmask+=1;
338 }
339 for ($i=$maskL; $i<32; $i++)
340 {
341 $binmask*=2;
342 }
343 return $binmask;
344}
345
346function binInvMaskFromDec ($maskL)
347{
348 $binmask=0;
349 for ($i=0; $i<$maskL; $i++)
350 {
351 $binmask*=2;
352 }
353 for ($i=$maskL; $i<32; $i++)
354 {
355 $binmask*=2;
356 $binmask+=1;
357 }
358 return $binmask;
359}
360
2a201216 361function addRange ($range='', $name='')
e673ee24 362{
2a201216
DY
363 // $range is in x.x.x.x/x format, split into ip/mask vars
364 $rangeArray = explode('/', $range);
365 $ip = $rangeArray[0];
366 $mask = $rangeArray[1];
367
e673ee24
DO
368 $ipL = ip2long($ip);
369 $maskL = ip2long($mask);
370 if ($ipL == -1 || $ipL === FALSE)
371 return 'Bad ip address';
372 if ($mask < 32 && $mask > 0)
373 $maskL = $mask;
374 else
375 {
376 $maskB = decbin($maskL);
377 if (strlen($maskB)!=32)
378 return 'Bad mask';
379 $ones=0;
380 $zeroes=FALSE;
381 foreach( str_split ($maskB) as $digit)
382 {
383 if ($digit == '0')
384 $zeroes = TRUE;
385 if ($digit == '1')
386 {
387 $ones++;
388 if ($zeroes == TRUE)
389 return 'Bad mask';
390 }
391 }
392 $maskL = $ones;
393 }
394 $binmask = binMaskFromDec($maskL);
395 $ipL = $ipL & $binmask;
396
397 $query =
398 "select ".
399 "id, ip, mask, name ".
400 "from IPRanges ";
401
402
403 global $dbxlink;
404
405 $result = $dbxlink->query ($query);
406
407 while ($row = $result->fetch (PDO::FETCH_ASSOC))
408 {
409 $otherip = $row['ip'];
410 $othermask = binMaskFromDec($row['mask']);
411// echo "checking $otherip & $othermask ".($otherip & $othermask)." == $ipL & $othermask ".($ipL & $othermask)." ".decbin($otherip)." ".decbin($othermask)." ".decbin($otherip & $othermask)." ".decbin($ipL)." ".decbin($othermask)." ".decbin($ipL & $othermask)."\n";
412// echo "checking $otherip & $binmask ".($otherip & $binmask)." == $ipL & $binmask ".($ipL & $binmask)." ".decbin($otherip)." ".decbin($binmask)." ".decbin($otherip & $binmask)." ".decbin($ipL)." ".decbin($binmask)." ".decbin($ipL & $binmask)."\n";
413// echo "\n";
414// flush();
415 if (($otherip & $othermask) == ($ipL & $othermask))
416 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
417 if (($otherip & $binmask) == ($ipL & $binmask))
418 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
419 }
420 $result->closeCursor();
421 $query =
422 "insert into IPRanges set ip=".sprintf('%u', $ipL).", mask='$maskL', name='$name'";
423 $result = $dbxlink->exec ($query);
424 return '';
425}
426
427function getIPRange ($id = 0)
428{
429 global $dbxlink;
430 $query =
431 "select ".
432 "id as IPRanges_id, ".
433 "INET_NTOA(ip) as IPRanges_ip, ".
e673ee24
DO
434 "mask as IPRanges_mask, ".
435 "name as IPRanges_name ".
436 "from IPRanges ".
437 "where id = '$id'";
438 $result = $dbxlink->query ($query);
439 if ($result == NULL)
e673ee24 440 return NULL;
5c43a978 441 $ret = array();
55cc3e4e
DO
442 $row = $result->fetch (PDO::FETCH_ASSOC);
443 if ($row == NULL)
444 return $ret;
445 $ret['id'] = $row['IPRanges_id'];
446 $ret['ip'] = $row['IPRanges_ip'];
7e039e88 447 $ret['ip_bin'] = ip2long ($row['IPRanges_ip']);
55cc3e4e
DO
448 $ret['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
449 $ret['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
450 $ret['name'] = $row['IPRanges_name'];
451 $ret['mask'] = $row['IPRanges_mask'];
452 $ret['addrlist'] = array();
55cc3e4e 453 $result->closeCursor();
7e039e88
DO
454 // We risk losing some significant bits in an unsigned 32bit integer,
455 // unless it is converted to a string.
456 $db_first = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']) . "'";
457 $db_last = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv'])) . "'";
5c43a978
DO
458
459 // Don't try to build up the whole structure in a single pass. Request
460 // the list of user comments and reservations and merge allocations in
461 // at a latter point.
55cc3e4e 462 $query =
7e039e88
DO
463 "select INET_NTOA(ip) as ip, name, reserved from IPAddress " .
464 "where ip between ${db_first} and ${db_last} " .
5c43a978
DO
465 "and (reserved = 'yes' or name != '')";
466 $ipa_res = $dbxlink->query ($query);
467 if ($ipa_res == NULL)
55cc3e4e 468 return $ret;
5c43a978 469 while ($row = $ipa_res->fetch (PDO::FETCH_ASSOC))
55cc3e4e 470 {
7e039e88
DO
471 $ip_bin = ip2long ($row['ip']);
472 $ret['addrlist'][$ip_bin] = $row;
5c43a978
DO
473 $tmp = array();
474 foreach (array ('ip', 'name', 'reserved') as $cname)
475 $tmp[$cname] = $row[$cname];
476 $tmp['references'] = array();
7e039e88 477 $ret['addrlist'][$ip_bin] = $tmp;
5c43a978
DO
478 }
479 $ipa_res->closeCursor();
e673ee24 480
5c43a978 481 $query =
dda31a62
DO
482 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
483 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
484 "dict_value as objtype_name from " .
5c43a978 485 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
dda31a62 486 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
7e039e88 487 "where ip between ${db_first} and ${db_last} " .
dda31a62 488 "and chapter_name = 'RackObjectType'" .
5c43a978
DO
489 "order by ipb.type, object_name";
490 $ipb_res = $dbxlink->query ($query);
491 while ($row = $ipb_res->fetch (PDO::FETCH_ASSOC))
492 {
7e039e88
DO
493 $ip_bin = ip2long ($row['ip']);
494 if (!isset ($ret['addrlist'][$ip_bin]))
55cc3e4e 495 {
7e039e88
DO
496 $ret['addrlist'][$ip_bin] = array();
497 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
498 $ret['addrlist'][$ip_bin]['name'] = '';
499 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
500 $ret['addrlist'][$ip_bin]['references'] = array();
e673ee24 501 }
5c43a978 502 $tmp = array();
dda31a62 503 foreach (array ('object_id', 'type', 'name') as $cname)
5c43a978 504 $tmp[$cname] = $row[$cname];
dda31a62
DO
505 $quasiobject['name'] = $row['object_name'];
506 $quasiobject['objtype_id'] = $row['objtype_id'];
507 $quasiobject['objtype_name'] = $row['objtype_name'];
508 $tmp['object_name'] = displayedName ($quasiobject);
7e039e88 509 $ret['addrlist'][$ip_bin]['references'][] = $tmp;
e673ee24 510 }
5c43a978
DO
511 $ipb_res->closeCursor();
512
e673ee24
DO
513 return $ret;
514}
515
dda31a62
DO
516// Don't require any records in IPAddress, but if there is one,
517// merge the data between getting allocation list. Collect enough data
518// to call displayedName() ourselves.
e673ee24
DO
519function getIPAddress ($ip=0)
520{
521 $ret = array();
e673ee24
DO
522 $ret['bonds'] = array();
523 $ret['outpf'] = array();
524 $ret['inpf'] = array();
525 $ret['exists'] = 0;
dda31a62 526 $ret['name'] = '';
e673ee24
DO
527 $ret['reserved'] = 'no';
528 global $dbxlink;
529 $query =
530 "select ".
dda31a62 531 "name, reserved ".
e673ee24 532 "from IPAddress ".
dda31a62 533 "where ip = INET_ATON('$ip') and (reserved = 'yes' or name != '')";
e673ee24
DO
534 $result = $dbxlink->query ($query);
535 if ($result == NULL)
e673ee24 536 return NULL;
959c4f4c 537 if ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 538 {
959c4f4c 539 $ret['exists'] = 1;
959c4f4c
DO
540 $ret['name'] = $row['name'];
541 $ret['reserved'] = $row['reserved'];
e673ee24
DO
542 }
543 $result->closeCursor();
544
dda31a62
DO
545 $query =
546 "select ".
547 "IPBonds.object_id as object_id, ".
548 "IPBonds.name as name, ".
549 "IPBonds.type as type, ".
550 "objtype_id, dict_value as objtype_name, " .
551 "RackObject.name as object_name ".
552 "from IPBonds join RackObject on IPBonds.object_id=RackObject.id ".
553 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
554 "where IPBonds.ip=INET_ATON('$ip') ".
555 "and chapter_name = 'RackObjectType' " .
556 "order by RackObject.id, IPBonds.name";
557 $result = $dbxlink->query ($query);
558 $count=0;
559 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 560 {
dda31a62
DO
561 $ret['bonds'][$count]['object_id'] = $row['object_id'];
562 $ret['bonds'][$count]['name'] = $row['name'];
563 $ret['bonds'][$count]['type'] = $row['type'];
564 $qo = array();
565 $qo['name'] = $row['object_name'];
566 $qo['objtype_id'] = $row['objtype_id'];
567 $qo['objtype_name'] = $row['objtype_name'];
568 $ret['bonds'][$count]['object_name'] = displayedName ($qo);
569 $count++;
570 $ret['exists'] = 1;
e673ee24 571 }
dda31a62 572 $result->closeCursor();
e673ee24
DO
573
574 return $ret;
575}
576
577function bindIpToObject ($ip='', $object_id=0, $name='', $type='')
578{
579 global $dbxlink;
580
581 $range = getRangeByIp($ip);
e673ee24
DO
582 if (!$range)
583 return 'Non-existant ip address. Try adding IP range first';
584
20a92aa2
DO
585 $result = useInsertBlade
586 (
587 'IPBonds',
588 array
589 (
dda31a62 590 'ip' => "INET_ATON('$ip')",
20a92aa2
DO
591 'object_id' => "'${object_id}'",
592 'name' => "'${name}'",
593 'type' => "'${type}'"
594 )
595 );
596 return $result ? '' : 'useInsertBlade() failed in bindIpToObject()';
e673ee24
DO
597}
598
599// This function looks up 'has_problems' flag for 'T' atoms
600// and modifies 'hl' key. May be, this should be better done
601// in getRackData(). We don't honour 'skipped' key, because
602// the function is also used for thumb creation.
603function markupObjectProblems (&$rackData)
604{
605 for ($i = $rackData['height']; $i > 0; $i--)
606 for ($locidx = 0; $locidx < 3; $locidx++)
607 if ($rackData[$i][$locidx]['state'] == 'T')
608 {
609 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
610 if ($object['has_problems'] == 'yes')
611 {
612 // Object can be already highlighted.
613 if (isset ($rackData[$i][$locidx]['hl']))
614 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
615 else
616 $rackData[$i][$locidx]['hl'] = 'w';
617 }
618 }
619}
620
621function search_cmpObj ($a, $b)
622{
623 return ($a['score'] > $b['score'] ? -1 : 1);
624}
625
626// This function performs search and then calculates score for each result.
627// Given previous search results in $objects argument, it adds new results
628// to the array and updates score for existing results, if it is greater than
629// existing score.
630function mergeSearchResults (&$objects, $terms, $fieldname)
631{
632 global $dbxlink;
633 $query =
634 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
635 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
636 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
637 $count = 0;
638 foreach (explode (' ', $terms) as $term)
639 {
640 if ($count) $query .= ' or ';
641 $query .= "${fieldname} like '%$term%'";
642 $count++;
643 }
644 $query .= "";
645 $result = $dbxlink->query($query);
646 if ($result == NULL)
647 {
648 showError ("SQL query failed in mergeSearchResults()");
649 return NULL;
650 }
651// FIXME: this dead call was executed 4 times per 1 object search!
652// $typeList = getObjectTypeList();
653 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
654 while ($row = $result->fetch(PDO::FETCH_ASSOC))
655 {
656 foreach ($clist as $cname)
657 $object[$cname] = $row[$cname];
658 $object['score'] = 0;
659 $object['dname'] = displayedName ($object);
660 unset ($object['objtype_id']);
661 foreach (explode (' ', $terms) as $term)
662 if (strstr ($object['name'], $term))
663 $object['score'] += 1;
664 unset ($object['name']);
665 if (!isset ($objects[$row['id']]))
666 $objects[$row['id']] = $object;
667 elseif ($objects[$row['id']]['score'] < $object['score'])
668 $objects[$row['id']]['score'] = $object['score'];
669 }
670 return $objects;
671}
672
673function getSearchResults ($terms)
674{
675 $objects = array();
676 mergeSearchResults ($objects, $terms, 'name');
677 mergeSearchResults ($objects, $terms, 'label');
678 mergeSearchResults ($objects, $terms, 'asset_no');
679 mergeSearchResults ($objects, $terms, 'barcode');
680 if (count ($objects) == 1)
681 usort ($objects, 'search_cmpObj');
682 return $objects;
683}
684
685// This function removes all colons and dots from a string.
686function l2addressForDatabase ($string)
687{
688 if (empty ($string))
689 return 'NULL';
690 $pieces = explode (':', $string);
691 // This workaround is for SunOS ifconfig.
692 foreach ($pieces as &$byte)
693 if (strlen ($byte) == 1)
694 $byte = '0' . $byte;
695 // And this workaround is for PHP.
696 unset ($byte);
697 $string = implode ('', $pieces);
698 $pieces = explode ('.', $string);
699 $string = implode ('', $pieces);
700 $string = strtoupper ($string);
701 return "'$string'";
702}
703
704function l2addressFromDatabase ($string)
705{
706 switch (strlen ($string))
707 {
708 case 12: // Ethernet
709 case 16: // FireWire
710 $ret = implode (':', str_split ($string, 2));
711 break;
712 default:
713 $ret = $string;
714 break;
715 }
716 return $ret;
717}
718
719// The following 2 functions return previous and next rack IDs for
720// a given rack ID. The order of racks is the same as in renderRackspace()
721// or renderRow().
722function getPrevIDforRack ($row_id = 0, $rack_id = 0)
723{
724 if ($row_id <= 0 or $rack_id <= 0)
725 {
726 showError ('Invalid arguments passed to getPrevIDforRack()');
727 return NULL;
728 }
729 $rackList = getRacksForRow ($row_id);
730 doubleLink ($rackList);
731 if (isset ($rackList[$rack_id]['prev_key']))
732 return $rackList[$rack_id]['prev_key'];
733 return NULL;
734}
735
736function getNextIDforRack ($row_id = 0, $rack_id = 0)
737{
738 if ($row_id <= 0 or $rack_id <= 0)
739 {
740 showError ('Invalid arguments passed to getNextIDforRack()');
741 return NULL;
742 }
743 $rackList = getRacksForRow ($row_id);
744 doubleLink ($rackList);
745 if (isset ($rackList[$rack_id]['next_key']))
746 return $rackList[$rack_id]['next_key'];
747 return NULL;
748}
749
750// This function finds previous and next array keys for each array key and
751// modifies its argument accordingly.
752function doubleLink (&$array)
753{
754 $prev_key = NULL;
755 foreach (array_keys ($array) as $key)
756 {
757 if ($prev_key)
758 {
759 $array[$key]['prev_key'] = $prev_key;
760 $array[$prev_key]['next_key'] = $key;
761 }
762 $prev_key = $key;
763 }
764}
765
766// After applying usort() to a rack list we will lose original array keys.
767// This function restores the keys so they are equal to rack IDs.
768function restoreRackIDs ($racks)
769{
770 $ret = array();
771 foreach ($racks as $rack)
772 $ret[$rack['id']] = $rack;
773 return $ret;
774}
775
776function sortTokenize ($a, $b)
777{
778 $aold='';
779 while ($a != $aold)
780 {
781 $aold=$a;
782 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
783 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
784 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
785 }
786
787 $bold='';
788 while ($b != $bold)
789 {
790 $bold=$b;
791 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
792 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
793 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
794 }
795
796
797
798 $ar = explode(' ', $a);
799 $br = explode(' ', $b);
800 for ($i=0; $i<count($ar) && $i<count($br); $i++)
801 {
802 $ret = 0;
803 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
804 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
805 else
806 $ret = strcasecmp($ar[$i], $br[$i]);
807 if ($ret != 0)
808 return $ret;
809 }
810 if ($i<count($ar))
811 return 1;
812 if ($i<count($br))
813 return -1;
814 return 0;
815}
816
817function sortByName ($a, $b)
818{
819 return sortTokenize($a['name'], $b['name']);
820}
821
822function eq ($a, $b)
823{
824 return $a==$b;
825}
826
827function neq ($a, $b)
828{
829 return $a!=$b;
830}
831
832function countRefsOfType ($refs, $type, $eq)
833{
834 $count=0;
835 foreach ($refs as $ref)
836 {
837 if ($eq($ref['type'], $type))
838 $count++;
839 }
840 return $count;
841}
842
843function sortEmptyPorts ($a, $b)
844{
845 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
846 if ($objname_cmp == 0)
847 {
848 return sortTokenize($a['Port_name'], $b['Port_name']);
849 }
850 return $objname_cmp;
851}
852
853function sortObjectAddressesAndNames ($a, $b)
854{
855 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
856 if ($objname_cmp == 0)
857 {
858 $objname_cmp = sortTokenize($a['port_name'], $b['port_name']);
859 if ($objname_cmp == 0)
860 {
861 sortTokenize($a['ip'], $b['ip']);
862 }
863 return $objname_cmp;
864 }
865 return $objname_cmp;
866}
867
868
869
870function sortAddresses ($a, $b)
871{
872 $name_cmp = sortTokenize($a['name'], $b['name']);
873 if ($name_cmp == 0)
874 {
875 return sortTokenize($a['ip'], $b['ip']);
876 }
877 return $name_cmp;
878}
879
880// This function expands port compat list into a matrix.
881function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
882{
883 $matrix = array();
884 // Create type matrix and markup compatible types.
885 foreach (array_keys ($portTypeList) as $type1)
886 foreach (array_keys ($portTypeList) as $type2)
887 $matrix[$type1][$type2] = FALSE;
888 foreach ($portCompatList as $pair)
889 $matrix[$pair['type1']][$pair['type2']] = TRUE;
890 return $matrix;
891}
892
893function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
894{
895 global $dbxlink;
896
897 $range = getRangeByIp($localip);
898 if (!$range)
899 return "$localip: Non existant ip";
900
901 $range = getRangeByIp($remoteip);
902 if (!$range)
903 return "$remoteip: Non existant ip";
904
905 if ( ($localport <= 0) or ($localport >= 65536) )
906 return "$localport: invaild port";
907
908 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
909 return "$remoteport: invaild port";
910
911 $query =
912 "insert into PortForwarding set object_id='$object_id', localip=INET_ATON('$localip'), remoteip=INET_ATON('$remoteip'), localport='$localport', remoteport='$remoteport', proto='$proto', description='$description'";
913 $result = $dbxlink->exec ($query);
914
915 return '';
916}
917
918function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
919{
920 global $dbxlink;
921
922 $query =
923 "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'";
924 $result = $dbxlink->exec ($query);
925 return '';
926}
927
928function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
929{
930 global $dbxlink;
931
932 $query =
933 "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'";
934 $result = $dbxlink->exec ($query);
935 return '';
936}
937
938function getObjectForwards($object_id)
939{
940 global $dbxlink;
941
942 $ret = array();
943 $ret['out'] = array();
944 $ret['in'] = array();
945 $query =
946 "select ".
947 "dict_value as proto, ".
948 "proto as proto_bin, ".
949 "INET_NTOA(localip) as localip, ".
950 "localport, ".
951 "INET_NTOA(remoteip) as remoteip, ".
952 "remoteport, ".
953 "description ".
954 "from PortForwarding inner join Dictionary on proto = dict_key natural join Chapter ".
955 "where object_id='$object_id' and chapter_name = 'Protocols' ".
956 "order by localip, localport, proto, remoteip, remoteport";
957 $result2 = $dbxlink->query ($query);
958 $count=0;
959 while ($row = $result2->fetch (PDO::FETCH_ASSOC))
960 {
961 $ret['out'][$count]['proto'] = $row['proto'];
962 $ret['out'][$count]['proto_bin'] = $row['proto_bin'];
963 $ret['out'][$count]['localip'] = $row['localip'];
964 $ret['out'][$count]['localport'] = $row['localport'];
965 $ret['out'][$count]['remoteip'] = $row['remoteip'];
966 $ret['out'][$count]['remoteport'] = $row['remoteport'];
967 $ret['out'][$count]['description'] = $row['description'];
968 $count++;
969 }
970 $result2->closeCursor();
971
972 $query =
973 "select ".
974 "dict_value as proto, ".
975 "proto as proto_bin, ".
976 "INET_NTOA(localip) as localip, ".
977 "localport, ".
978 "INET_NTOA(remoteip) as remoteip, ".
979 "remoteport, ".
980 "PortForwarding.object_id as object_id, ".
981 "RackObject.name as object_name, ".
982 "description ".
983 "from ((PortForwarding join IPBonds on remoteip=ip) join RackObject on PortForwarding.object_id=RackObject.id) inner join Dictionary on proto = dict_key natural join Chapter ".
984 "where IPBonds.object_id='$object_id' and chapter_name = 'Protocols' ".
985 "order by remoteip, remoteport, proto, localip, localport";
986 $result3 = $dbxlink->query ($query);
987 $count=0;
988 while ($row = $result3->fetch (PDO::FETCH_ASSOC))
989 {
990 $ret['in'][$count]['proto'] = $row['proto'];
991 $ret['in'][$count]['proto_bin'] = $row['proto_bin'];
992 $ret['in'][$count]['localport'] = $row['localport'];
993 $ret['in'][$count]['localip'] = $row['localip'];
994 $ret['in'][$count]['remoteport'] = $row['remoteport'];
995 $ret['in'][$count]['remoteip'] = $row['remoteip'];
996 $ret['in'][$count]['object_id'] = $row['object_id'];
997 $ret['in'][$count]['object_name'] = $row['object_name'];
998 $ret['in'][$count]['description'] = $row['description'];
999 $count++;
1000 }
1001 $result3->closeCursor();
1002
1003 return $ret;
1004}
1005
c31cd72c 1006// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
1007// if FQDN is set. The next choice is object's common name, if it looks like a
1008// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 1009// object is returned (which may appear 0 and more elements long).
f321b50a 1010function findAllEndpoints ($object_id, $fallback = '')
c31cd72c
DO
1011{
1012 $values = getAttrValues ($object_id);
1013 foreach ($values as $record)
f321b50a 1014 if ($record['name'] == 'FQDN' && !empty ($record['value']))
c31cd72c
DO
1015 return array ($record['value']);
1016 $addresses = getObjectAddresses ($object_id);
1017 $regular = array();
1018 foreach ($addresses as $idx => $address)
1019 if ($address['type'] == 'regular')
fa8112d1 1020 $regular[] = $address['ip'];
f321b50a
DO
1021 if (!count ($regular) && !empty ($fallback))
1022 return array ($fallback);
c31cd72c
DO
1023 return $regular;
1024}
1025
e673ee24 1026?>