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