r2095 + don't depend on obsolete getIPAddress() and getIPRange() any more
[racktables] / inc / functions.php
1 <?php
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.
30 function displayedName ($objectData)
31 {
32 if ($objectData['name'] != '')
33 return $objectData['name'];
34 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
35 return "ANONYMOUS " . $objectData['objtype_name'];
36 else
37 return "[${objectData['objtype_name']}]";
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.
43 function 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 (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
61 break 2;
62 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
63 break 2;
64 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
65 break 2;
66 if ($object_id == 0)
67 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
68 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
69 break 2;
70 }
71 }
72 // If the first row can't offer anything, bail out.
73 if ($height == 0 and $object_id == 0)
74 break;
75 $height++;
76 }
77 while ($startRow - $height > 0);
78 # echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
79 # echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
80 # echo ") 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.
86 function 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 // Explicitly show even single-cell spanned atoms, because rectHeight()
98 // is expeciting this data for correct calculation.
99 if ($colspan != 0)
100 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
101 else
102 {
103 $colspan = $templateWidth[$template_idx];
104 if ($colspan >= 1)
105 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
106 if ($maxheight >= 1)
107 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
108 }
109 }
110 }
111 }
112 return;
113 }
114
115 // This function sets rowspan/solspan/skipped atom attributes for renderRack()
116 // What we actually have to do is to find _all_ possible rectangles for each unit
117 // and then select the widest of those with the maximal square.
118 function markAllSpans (&$rackData = NULL)
119 {
120 if ($rackData == NULL)
121 {
122 showError ('Invalid rackData', __FUNCTION__);
123 return;
124 }
125 for ($i = $rackData['height']; $i > 0; $i--)
126 while (markBestSpan ($rackData, $i));
127 }
128
129 // Calculate height of 6 possible span templates (array is presorted by width
130 // descending) and mark the best (if any).
131 function markBestSpan (&$rackData, $i)
132 {
133 global $template, $templateWidth;
134 for ($j = 0; $j < 6; $j++)
135 {
136 $height[$j] = rectHeight ($rackData, $i, $j);
137 $square[$j] = $height[$j] * $templateWidth[$j];
138 }
139 // find the widest rectangle of those with maximal height
140 $maxsquare = max ($square);
141 if (!$maxsquare)
142 return FALSE;
143 $best_template_index = 0;
144 for ($j = 0; $j < 6; $j++)
145 if ($square[$j] == $maxsquare)
146 {
147 $best_template_index = $j;
148 $bestheight = $height[$j];
149 break;
150 }
151 // distribute span marks
152 markSpan ($rackData, $i, $bestheight, $best_template_index);
153 return TRUE;
154 }
155
156 // We can mount 'F' atoms and unmount our own 'T' atoms.
157 function applyObjectMountMask (&$rackData, $object_id)
158 {
159 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
160 for ($locidx = 0; $locidx < 3; $locidx++)
161 switch ($rackData[$unit_no][$locidx]['state'])
162 {
163 case 'F':
164 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
165 break;
166 case 'T':
167 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
168 break;
169 default:
170 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
171 }
172 }
173
174 // Design change means transition between 'F' and 'A' and back.
175 function applyRackDesignMask (&$rackData)
176 {
177 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
178 for ($locidx = 0; $locidx < 3; $locidx++)
179 switch ($rackData[$unit_no][$locidx]['state'])
180 {
181 case 'F':
182 case 'A':
183 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
184 break;
185 default:
186 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
187 }
188 }
189
190 // The same for 'F' and 'U'.
191 function applyRackProblemMask (&$rackData)
192 {
193 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
194 for ($locidx = 0; $locidx < 3; $locidx++)
195 switch ($rackData[$unit_no][$locidx]['state'])
196 {
197 case 'F':
198 case 'U':
199 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
200 break;
201 default:
202 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
203 }
204 }
205
206 // This mask should allow toggling 'T' and 'W' on object's rackspace.
207 function applyObjectProblemMask (&$rackData)
208 {
209 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
210 for ($locidx = 0; $locidx < 3; $locidx++)
211 switch ($rackData[$unit_no][$locidx]['state'])
212 {
213 case 'T':
214 case 'W':
215 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
216 break;
217 default:
218 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
219 }
220 }
221
222 // This function highlights specified object (and removes previous highlight).
223 function highlightObject (&$rackData, $object_id)
224 {
225 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
226 for ($locidx = 0; $locidx < 3; $locidx++)
227 if
228 (
229 $rackData[$unit_no][$locidx]['state'] == 'T' and
230 $rackData[$unit_no][$locidx]['object_id'] == $object_id
231 )
232 $rackData[$unit_no][$locidx]['hl'] = 'h';
233 else
234 unset ($rackData[$unit_no][$locidx]['hl']);
235 }
236
237 // This function marks atoms to selected or not depending on their current state.
238 function markupAtomGrid (&$data, $checked_state)
239 {
240 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
241 for ($locidx = 0; $locidx < 3; $locidx++)
242 {
243 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
244 continue;
245 if ($data[$unit_no][$locidx]['state'] == $checked_state)
246 $data[$unit_no][$locidx]['checked'] = ' checked';
247 else
248 $data[$unit_no][$locidx]['checked'] = '';
249 }
250 }
251
252 // This function is almost a clone of processGridForm(), but doesn't save anything to database
253 // Return value is the changed rack data.
254 // Here we assume that correct filter has already been applied, so we just
255 // set or unset checkbox inputs w/o changing atom state.
256 function mergeGridFormToRack (&$rackData)
257 {
258 $rack_id = $rackData['id'];
259 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
260 for ($locidx = 0; $locidx < 3; $locidx++)
261 {
262 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
263 continue;
264 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
265 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
266 $rackData[$unit_no][$locidx]['checked'] = ' checked';
267 else
268 $rackData[$unit_no][$locidx]['checked'] = '';
269 }
270 }
271
272 function binMaskFromDec ($maskL)
273 {
274 $binmask=0;
275 for ($i=0; $i<$maskL; $i++)
276 {
277 $binmask*=2;
278 $binmask+=1;
279 }
280 for ($i=$maskL; $i<32; $i++)
281 {
282 $binmask*=2;
283 }
284 return $binmask;
285 }
286
287 function binInvMaskFromDec ($maskL)
288 {
289 $binmask=0;
290 for ($i=0; $i<$maskL; $i++)
291 {
292 $binmask*=2;
293 }
294 for ($i=$maskL; $i<32; $i++)
295 {
296 $binmask*=2;
297 $binmask+=1;
298 }
299 return $binmask;
300 }
301
302 // This function looks up 'has_problems' flag for 'T' atoms
303 // and modifies 'hl' key. May be, this should be better done
304 // in getRackData(). We don't honour 'skipped' key, because
305 // the function is also used for thumb creation.
306 function markupObjectProblems (&$rackData)
307 {
308 for ($i = $rackData['height']; $i > 0; $i--)
309 for ($locidx = 0; $locidx < 3; $locidx++)
310 if ($rackData[$i][$locidx]['state'] == 'T')
311 {
312 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
313 if ($object['has_problems'] == 'yes')
314 {
315 // Object can be already highlighted.
316 if (isset ($rackData[$i][$locidx]['hl']))
317 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
318 else
319 $rackData[$i][$locidx]['hl'] = 'w';
320 }
321 }
322 }
323
324 function search_cmpObj ($a, $b)
325 {
326 return ($a['score'] > $b['score'] ? -1 : 1);
327 }
328
329 // This function performs search and then calculates score for each result.
330 // Given previous search results in $objects argument, it adds new results
331 // to the array and updates score for existing results, if it is greater than
332 // existing score.
333 function mergeSearchResults (&$objects, $terms, $fieldname)
334 {
335 global $dbxlink;
336 $query =
337 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
338 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
339 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
340 $count = 0;
341 foreach (explode (' ', $terms) as $term)
342 {
343 if ($count) $query .= ' or ';
344 $query .= "${fieldname} like '%$term%'";
345 $count++;
346 }
347 $query .= " order by ${fieldname}";
348 $result = useSelectBlade ($query, __FUNCTION__);
349 // FIXME: this dead call was executed 4 times per 1 object search!
350 // $typeList = getObjectTypeList();
351 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
352 while ($row = $result->fetch (PDO::FETCH_ASSOC))
353 {
354 foreach ($clist as $cname)
355 $object[$cname] = $row[$cname];
356 $object['score'] = 0;
357 $object['dname'] = displayedName ($object);
358 unset ($object['objtype_id']);
359 foreach (explode (' ', $terms) as $term)
360 if (strstr ($object['name'], $term))
361 $object['score'] += 1;
362 unset ($object['name']);
363 if (!isset ($objects[$row['id']]))
364 $objects[$row['id']] = $object;
365 elseif ($objects[$row['id']]['score'] < $object['score'])
366 $objects[$row['id']]['score'] = $object['score'];
367 }
368 return $objects;
369 }
370
371 function getObjectSearchResults ($terms)
372 {
373 $objects = array();
374 mergeSearchResults ($objects, $terms, 'name');
375 mergeSearchResults ($objects, $terms, 'label');
376 mergeSearchResults ($objects, $terms, 'asset_no');
377 mergeSearchResults ($objects, $terms, 'barcode');
378 if (count ($objects) == 1)
379 usort ($objects, 'search_cmpObj');
380 return $objects;
381 }
382
383 // This function removes all colons and dots from a string.
384 function l2addressForDatabase ($string)
385 {
386 if (empty ($string))
387 return 'NULL';
388 $pieces = explode (':', $string);
389 // This workaround is for SunOS ifconfig.
390 foreach ($pieces as &$byte)
391 if (strlen ($byte) == 1)
392 $byte = '0' . $byte;
393 // And this workaround is for PHP.
394 unset ($byte);
395 $string = implode ('', $pieces);
396 $pieces = explode ('.', $string);
397 $string = implode ('', $pieces);
398 $string = strtoupper ($string);
399 return "'$string'";
400 }
401
402 function l2addressFromDatabase ($string)
403 {
404 switch (strlen ($string))
405 {
406 case 12: // Ethernet
407 case 16: // FireWire
408 $ret = implode (':', str_split ($string, 2));
409 break;
410 default:
411 $ret = $string;
412 break;
413 }
414 return $ret;
415 }
416
417 // The following 2 functions return previous and next rack IDs for
418 // a given rack ID. The order of racks is the same as in renderRackspace()
419 // or renderRow().
420 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
421 {
422 if ($row_id <= 0 or $rack_id <= 0)
423 {
424 showError ('Invalid arguments passed', __FUNCTION__);
425 return NULL;
426 }
427 $rackList = getRacksForRow ($row_id);
428 doubleLink ($rackList);
429 if (isset ($rackList[$rack_id]['prev_key']))
430 return $rackList[$rack_id]['prev_key'];
431 return NULL;
432 }
433
434 function getNextIDforRack ($row_id = 0, $rack_id = 0)
435 {
436 if ($row_id <= 0 or $rack_id <= 0)
437 {
438 showError ('Invalid arguments passed', __FUNCTION__);
439 return NULL;
440 }
441 $rackList = getRacksForRow ($row_id);
442 doubleLink ($rackList);
443 if (isset ($rackList[$rack_id]['next_key']))
444 return $rackList[$rack_id]['next_key'];
445 return NULL;
446 }
447
448 // This function finds previous and next array keys for each array key and
449 // modifies its argument accordingly.
450 function doubleLink (&$array)
451 {
452 $prev_key = NULL;
453 foreach (array_keys ($array) as $key)
454 {
455 if ($prev_key)
456 {
457 $array[$key]['prev_key'] = $prev_key;
458 $array[$prev_key]['next_key'] = $key;
459 }
460 $prev_key = $key;
461 }
462 }
463
464 // After applying usort() to a rack list we will lose original array keys.
465 // This function restores the keys so they are equal to rack IDs.
466 function restoreRackIDs ($racks)
467 {
468 $ret = array();
469 foreach ($racks as $rack)
470 $ret[$rack['id']] = $rack;
471 return $ret;
472 }
473
474 function sortTokenize ($a, $b)
475 {
476 $aold='';
477 while ($a != $aold)
478 {
479 $aold=$a;
480 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
481 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
482 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
483 }
484
485 $bold='';
486 while ($b != $bold)
487 {
488 $bold=$b;
489 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
490 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
491 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
492 }
493
494
495
496 $ar = explode(' ', $a);
497 $br = explode(' ', $b);
498 for ($i=0; $i<count($ar) && $i<count($br); $i++)
499 {
500 $ret = 0;
501 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
502 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
503 else
504 $ret = strcasecmp($ar[$i], $br[$i]);
505 if ($ret != 0)
506 return $ret;
507 }
508 if ($i<count($ar))
509 return 1;
510 if ($i<count($br))
511 return -1;
512 return 0;
513 }
514
515 function sortByName ($a, $b)
516 {
517 return sortTokenize($a['name'], $b['name']);
518 }
519
520 function sortRacks ($a, $b)
521 {
522 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
523 }
524
525 function eq ($a, $b)
526 {
527 return $a==$b;
528 }
529
530 function neq ($a, $b)
531 {
532 return $a!=$b;
533 }
534
535 function countRefsOfType ($refs, $type, $eq)
536 {
537 $count=0;
538 foreach ($refs as $ref)
539 {
540 if ($eq($ref['type'], $type))
541 $count++;
542 }
543 return $count;
544 }
545
546 function sortEmptyPorts ($a, $b)
547 {
548 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
549 if ($objname_cmp == 0)
550 {
551 return sortTokenize($a['Port_name'], $b['Port_name']);
552 }
553 return $objname_cmp;
554 }
555
556 function sortObjectAddressesAndNames ($a, $b)
557 {
558 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
559 if ($objname_cmp == 0)
560 {
561 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
562 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
563 $objname_cmp = sortTokenize($name_a, $name_b);
564 if ($objname_cmp == 0)
565 sortTokenize($a['ip'], $b['ip']);
566 return $objname_cmp;
567 }
568 return $objname_cmp;
569 }
570
571
572
573 function sortAddresses ($a, $b)
574 {
575 $name_cmp = sortTokenize($a['name'], $b['name']);
576 if ($name_cmp == 0)
577 {
578 return sortTokenize($a['ip'], $b['ip']);
579 }
580 return $name_cmp;
581 }
582
583 // This function expands port compat list into a matrix.
584 function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
585 {
586 $matrix = array();
587 // Create type matrix and markup compatible types.
588 foreach (array_keys ($portTypeList) as $type1)
589 foreach (array_keys ($portTypeList) as $type2)
590 $matrix[$type1][$type2] = FALSE;
591 foreach ($portCompatList as $pair)
592 $matrix[$pair['type1']][$pair['type2']] = TRUE;
593 return $matrix;
594 }
595
596 function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
597 {
598 global $dbxlink;
599
600 $range = getRangeByIp($localip);
601 if (!$range)
602 return "$localip: Non existant ip";
603
604 $range = getRangeByIp($remoteip);
605 if (!$range)
606 return "$remoteip: Non existant ip";
607
608 if ( ($localport <= 0) or ($localport >= 65536) )
609 return "$localport: invaild port";
610
611 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
612 return "$remoteport: invaild port";
613
614 $result = useInsertBlade
615 (
616 'PortForwarding',
617 array
618 (
619 'object_id' => $object_id,
620 'localip' => "INET_ATON('${localip}')",
621 'remoteip' => "INET_ATON('$remoteip')",
622 'localport' => $localport,
623 'remoteport' => $remoteport,
624 'proto' => "'${proto}'",
625 'description' => "'${description}'",
626 )
627 );
628 if ($result)
629 return '';
630 else
631 return __FUNCTION__ . ': Failed to insert the rule.';
632 }
633
634 function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
635 {
636 global $dbxlink;
637
638 $query =
639 "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'";
640 $result = $dbxlink->exec ($query);
641 return '';
642 }
643
644 function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
645 {
646 global $dbxlink;
647
648 $query =
649 "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'";
650 $result = $dbxlink->exec ($query);
651 return '';
652 }
653
654 function getNATv4ForObject ($object_id)
655 {
656 $ret = array();
657 $ret['out'] = array();
658 $ret['in'] = array();
659 $query =
660 "select ".
661 "proto, ".
662 "INET_NTOA(localip) as localip, ".
663 "localport, ".
664 "INET_NTOA(remoteip) as remoteip, ".
665 "remoteport, ".
666 "ipa1.name as local_addr_name, " .
667 "ipa2.name as remote_addr_name, " .
668 "description ".
669 "from PortForwarding ".
670 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
671 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
672 "where object_id='$object_id' ".
673 "order by localip, localport, proto, remoteip, remoteport";
674 $result = useSelectBlade ($query, __FUNCTION__);
675 $count=0;
676 while ($row = $result->fetch (PDO::FETCH_ASSOC))
677 {
678 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
679 $ret['out'][$count][$cname] = $row[$cname];
680 $count++;
681 }
682 $result->closeCursor();
683 unset ($result);
684
685 $query =
686 "select ".
687 "proto, ".
688 "INET_NTOA(localip) as localip, ".
689 "localport, ".
690 "INET_NTOA(remoteip) as remoteip, ".
691 "remoteport, ".
692 "PortForwarding.object_id as object_id, ".
693 "RackObject.name as object_name, ".
694 "description ".
695 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
696 "where IPBonds.object_id='$object_id' ".
697 "order by remoteip, remoteport, proto, localip, localport";
698 $result = useSelectBlade ($query, __FUNCTION__);
699 $count=0;
700 while ($row = $result->fetch (PDO::FETCH_ASSOC))
701 {
702 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
703 $ret['in'][$count][$cname] = $row[$cname];
704 $count++;
705 }
706 $result->closeCursor();
707
708 return $ret;
709 }
710
711 // This function returns an array of single element of object's FQDN attribute,
712 // if FQDN is set. The next choice is object's common name, if it looks like a
713 // hostname. Otherwise an array of all 'regular' IP addresses of the
714 // object is returned (which may appear 0 and more elements long).
715 function findAllEndpoints ($object_id, $fallback = '')
716 {
717 $values = getAttrValues ($object_id);
718 foreach ($values as $record)
719 if ($record['name'] == 'FQDN' && !empty ($record['value']))
720 return array ($record['value']);
721 $addresses = getObjectAddresses ($object_id);
722 $regular = array();
723 foreach ($addresses as $idx => $address)
724 if ($address['type'] == 'regular')
725 $regular[] = $address['ip'];
726 if (!count ($regular) && !empty ($fallback))
727 return array ($fallback);
728 return $regular;
729 }
730
731 // Some records in the dictionary may be written as plain text or as Wiki
732 // link in the following syntax:
733 // 1. word
734 // 2. [[word URL]] // FIXME: this isn't working
735 // 3. [[word word word | URL]]
736 // This function parses the line and returns text suitable for either A
737 // (rendering <A HREF>) or O (for <OPTION>).
738 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
739 {
740 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
741 {
742 if ($strip_optgroup)
743 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
744 else
745 return $line;
746 }
747 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
748 $s = explode ('|', $line);
749 $o_value = trim ($s[0]);
750 if ($strip_optgroup)
751 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
752 $a_value = trim ($s[1]);
753 if ($which == 'a')
754 return "<a href='${a_value}'>${o_value}</a>";
755 if ($which == 'o')
756 return $o_value;
757 }
758
759 function buildVServiceName ($vsinfo = NULL)
760 {
761 if ($vsinfo == NULL)
762 {
763 showError ('NULL argument', __FUNCTION__);
764 return NULL;
765 }
766 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
767 }
768
769 function buildRSPoolName ($rspool = NULL)
770 {
771 if ($rspool == NULL)
772 {
773 showError ('NULL argument', __FUNCTION__);
774 return NULL;
775 }
776 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
777 }
778
779 // rackspace usage for a single rack
780 // (T + W + U) / (height * 3 - A)
781 function getRSUforRack ($data = NULL)
782 {
783 if ($data == NULL)
784 {
785 showError ('Invalid argument', __FUNCTION__);
786 return NULL;
787 }
788 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
789 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
790 for ($locidx = 0; $locidx < 3; $locidx++)
791 $counter[$data[$unit_no][$locidx]['state']]++;
792 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
793 }
794
795 // Same for row.
796 function getRSUforRackRow ($rowData = NULL)
797 {
798 if ($rowData === NULL)
799 {
800 showError ('Invalid argument', __FUNCTION__);
801 return NULL;
802 }
803 if (!count ($rowData))
804 return 0;
805 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
806 $total_height = 0;
807 foreach (array_keys ($rowData) as $rack_id)
808 {
809 $data = getRackData ($rack_id);
810 $total_height += $data['height'];
811 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
812 for ($locidx = 0; $locidx < 3; $locidx++)
813 $counter[$data[$unit_no][$locidx]['state']]++;
814 }
815 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
816 }
817
818 function getObjectCount ($rackData)
819 {
820 $objects = array();
821 for ($i = $rackData['height']; $i > 0; $i--)
822 for ($locidx = 0; $locidx < 3; $locidx++)
823 if
824 (
825 $rackData[$i][$locidx]['state'] == 'T' and
826 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
827 )
828 $objects[] = $rackData[$i][$locidx]['object_id'];
829 return count ($objects);
830 }
831
832 // Make sure the string is always wrapped with LF characters
833 function lf_wrap ($str)
834 {
835 $ret = trim ($str, "\r\n");
836 if (!empty ($ret))
837 $ret .= "\n";
838 return $ret;
839 }
840
841 // Adopted from Mantis BTS code.
842 function string_insert_hrefs ($s)
843 {
844 if (getConfigVar ('DETECT_URLS') != 'yes')
845 return $s;
846 # Find any URL in a string and replace it by a clickable link
847 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
848 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
849 $s);
850 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
851 '<a href="mailto:\0">\0</a>',
852 $s);
853 return $s;
854 }
855
856 // Idem.
857 function email_regex_simple ()
858 {
859 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
860 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
861 }
862
863 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
864 // for the requested object_type_id.
865 function getAutoPorts ($type_id)
866 {
867 $ret = array();
868 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
869 foreach ($typemap as $equation)
870 {
871 $tmp = explode ('=', $equation);
872 if (count ($tmp) != 2)
873 continue;
874 $objtype_id = $tmp[0];
875 if ($objtype_id != $type_id)
876 continue;
877 $portlist = $tmp[1];
878 foreach (explode ('+', $portlist) as $product)
879 {
880 $tmp = explode ('*', $product);
881 if (count ($tmp) != 3)
882 continue;
883 $nports = $tmp[0];
884 $port_type = $tmp[1];
885 $format = $tmp[2];
886 for ($i = 0; $i < $nports; $i++)
887 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
888 }
889 }
890 return $ret;
891 }
892
893 // Find if a particular tag id exists on the tree, then attach the
894 // given child tag to it. If the parent tag doesn't exist, return FALSE.
895 function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
896 {
897 foreach ($tree as $tagid => $taginfo)
898 {
899 if ($tagid == $parent_id)
900 {
901 $tree[$tagid]['kids'][$child_id] = $child_info;
902 return TRUE;
903 }
904 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
905 return TRUE;
906 }
907 return FALSE;
908 }
909
910 // Build a tree from the tag list and return it.
911 function getTagTree ()
912 {
913 global $taglist;
914 $mytaglist = $taglist;
915 $ret = array();
916 while (count ($mytaglist) > 0)
917 {
918 $picked = FALSE;
919 foreach ($mytaglist as $tagid => $taginfo)
920 {
921 $taginfo['kids'] = array();
922 if ($taginfo['parent_id'] == NULL)
923 {
924 $ret[$tagid] = $taginfo;
925 $picked = TRUE;
926 unset ($mytaglist[$tagid]);
927 }
928 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
929 {
930 $picked = TRUE;
931 unset ($mytaglist[$tagid]);
932 }
933 }
934 if (!$picked) // Only orphaned items on the list.
935 break;
936 }
937 return $ret;
938 }
939
940 // Build a tree from the tag list and return everything _except_ the tree.
941 function getOrphanedTags ()
942 {
943 global $taglist;
944 $mytaglist = $taglist;
945 $dummy = array();
946 while (count ($mytaglist) > 0)
947 {
948 $picked = FALSE;
949 foreach ($mytaglist as $tagid => $taginfo)
950 {
951 $taginfo['kids'] = array();
952 if ($taginfo['parent_id'] == NULL)
953 {
954 $dummy[$tagid] = $taginfo;
955 $picked = TRUE;
956 unset ($mytaglist[$tagid]);
957 }
958 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
959 {
960 $picked = TRUE;
961 unset ($mytaglist[$tagid]);
962 }
963 }
964 if (!$picked) // Only orphaned items on the list.
965 return $mytaglist;
966 }
967 return array();
968 }
969
970 function serializeTags ($chain, $baseurl = '')
971 {
972 $comma = '';
973 $ret = '';
974 foreach ($chain as $taginfo)
975 {
976 $ret .= $comma .
977 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
978 $taginfo['tag'] .
979 ($baseurl == '' ? '' : '</a>');
980 $comma = ', ';
981 }
982 return $ret;
983 }
984
985 // a helper for getTagChainExpansion()
986 function traceTagChain ($tree, $chain)
987 {
988 // For each tag find its path from the root, then combine items
989 // of all paths and add them to the chain, if they aren't there yet.
990 $ret = array();
991 foreach ($tree as $taginfo1)
992 {
993 $hit = FALSE;
994 foreach ($chain as $taginfo2)
995 if ($taginfo1['id'] == $taginfo2['id'])
996 {
997 $hit = TRUE;
998 break;
999 }
1000 if (count ($taginfo1['kids']) > 0)
1001 {
1002 $subsearch = traceTagChain ($taginfo1['kids'], $chain);
1003 if (count ($subsearch))
1004 {
1005 $hit = TRUE;
1006 $ret = array_merge ($ret, $subsearch);
1007 }
1008 }
1009 if ($hit)
1010 $ret[] = $taginfo1;
1011 }
1012 return $ret;
1013 }
1014
1015 // For each tag add all its parent tags onto the list. Don't expect anything
1016 // except user's tags on the chain.
1017 function getTagChainExpansion ($chain)
1018 {
1019 global $tagtree;
1020 return traceTagChain ($tagtree, $chain);
1021 }
1022
1023 // Return the list of missing implicit tags.
1024 function getImplicitTags ($oldtags)
1025 {
1026 $ret = array();
1027 $newtags = getTagChainExpansion ($oldtags);
1028 foreach ($newtags as $newtag)
1029 {
1030 $already_exists = FALSE;
1031 foreach ($oldtags as $oldtag)
1032 if ($newtag['id'] == $oldtag['id'])
1033 {
1034 $already_exists = TRUE;
1035 break;
1036 }
1037 if ($already_exists)
1038 continue;
1039 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
1040 }
1041 return $ret;
1042 }
1043
1044 // Minimize the chain: exclude all implicit tags and return the result.
1045 function getExplicitTagsOnly ($chain, $tree = NULL)
1046 {
1047 global $tagtree;
1048 if ($tree === NULL)
1049 $tree = $tagtree;
1050 $ret = array();
1051 foreach ($tree as $taginfo)
1052 {
1053 if (isset ($taginfo['kids']))
1054 {
1055 $harvest = getExplicitTagsOnly ($chain, $taginfo['kids']);
1056 if (count ($harvest) > 0)
1057 {
1058 $ret = array_merge ($ret, $harvest);
1059 continue;
1060 }
1061 }
1062 // This tag isn't implicit, test is for being explicit.
1063 foreach ($chain as $testtag)
1064 if ($taginfo['id'] == $testtag['id'])
1065 {
1066 $ret[] = $testtag;
1067 break;
1068 }
1069 }
1070 return $ret;
1071 }
1072
1073 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
1074 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
1075 // a list of tag structures.
1076 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1077 {
1078 global $tagtree;
1079 if ($tree === NULL)
1080 $tree = $tagtree;
1081 $getallkids = $getall;
1082 $ret = array();
1083 foreach ($tree as $taginfo)
1084 {
1085 foreach ($idlist as $test_id)
1086 if ($getall or $taginfo['id'] == $test_id)
1087 {
1088 $ret[] = $taginfo['id'];
1089 // Once matched node makes all sub-nodes match, but don't make
1090 // a mistake of matching every other node at the current level.
1091 $getallkids = TRUE;
1092 break;
1093 }
1094 if (isset ($taginfo['kids']))
1095 $ret = array_merge ($ret, complementByKids ($idlist, $taginfo['kids'], $getallkids));
1096 $getallkids = FALSE;
1097 }
1098 return $ret;
1099 }
1100
1101 function getUserAutoTags ($username = NULL)
1102 {
1103 global $remote_username, $accounts;
1104 if ($username == NULL)
1105 $username = $remote_username;
1106 $ret = array();
1107 $ret[] = array ('tag' => '$username_' . $username);
1108 if (isset ($accounts[$username]['user_id']))
1109 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
1110 return $ret;
1111 }
1112
1113 function loadRackObjectAutoTags ()
1114 {
1115 assertUIntArg ('object_id', __FUNCTION__);
1116 $object_id = $_REQUEST['object_id'];
1117 $oinfo = getObjectInfo ($object_id);
1118 $ret = array();
1119 $ret[] = array ('tag' => '$id_' . $object_id);
1120 $ret[] = array ('tag' => '$any_object');
1121 if (validTagName ($oinfo['name']))
1122 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
1123 return $ret;
1124 }
1125
1126 // Common code for both prefix and address tag listers.
1127 function getIPv4PrefixTags ($prefix)
1128 {
1129 $ret = array();
1130 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $prefix['ip']) . '-' . $prefix['mask']);
1131 // FIXME: find and list tags for all parent networks?
1132 $ret[] = array ('tag' => '$any_ip4net');
1133 $ret[] = array ('tag' => '$any_net');
1134 return $ret;
1135 }
1136
1137 function loadIPv4PrefixAutoTags ()
1138 {
1139 assertUIntArg ('id', __FUNCTION__);
1140 return array_merge
1141 (
1142 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
1143 getIPv4PrefixTags (getIPv4NetworkInfo ($_REQUEST['id']))
1144 );
1145 }
1146
1147 function loadIPv4AddressAutoTags ()
1148 {
1149 assertIPv4Arg ('ip', __FUNCTION__);
1150 return array_merge
1151 (
1152 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
1153 getIPv4PrefixTags (getRangeByIP ($_REQUEST['ip']))
1154 );
1155 }
1156
1157 function loadRackAutoTags ()
1158 {
1159 assertUIntArg ('rack_id', __FUNCTION__);
1160 $ret = array();
1161 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
1162 $ret[] = array ('tag' => '$any_rack');
1163 return $ret;
1164 }
1165
1166 function loadIPv4VSAutoTags ()
1167 {
1168 assertUIntArg ('vs_id', __FUNCTION__);
1169 $ret = array();
1170 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
1171 $ret[] = array ('tag' => '$any_ipv4vs');
1172 $ret[] = array ('tag' => '$any_vs');
1173 return $ret;
1174 }
1175
1176 function loadIPv4RSPoolAutoTags ()
1177 {
1178 assertUIntArg ('pool_id', __FUNCTION__);
1179 $ret = array();
1180 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1181 $ret[] = array ('tag' => '$any_ipv4rsp');
1182 $ret[] = array ('tag' => '$any_rsp');
1183 return $ret;
1184 }
1185
1186 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1187 // hold all appropriate (explicit and implicit) tags respectively.
1188 // Otherwise some limited redirection is necessary (only page and tab
1189 // names are preserved, ophandler name change isn't handled).
1190 function fixContext ()
1191 {
1192 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
1193
1194 $pmap = array
1195 (
1196 'accounts' => 'userlist',
1197 'rspools' => 'ipv4rsplist',
1198 'rspool' => 'ipv4rsp',
1199 'vservices' => 'ipv4vslist',
1200 'vservice' => 'ipv4vs',
1201 );
1202 $tmap = array();
1203 $tmap['objects']['newmulti'] = 'addmore';
1204 $tmap['objects']['newobj'] = 'addmore';
1205 $tmap['object']['switchvlans'] = 'livevlans';
1206 $tmap['object']['slb'] = 'editrspvs';
1207 $tmap['object']['portfwrd'] = 'nat4';
1208 $tmap['object']['network'] = 'ipv4';
1209 if (isset ($pmap[$pageno]))
1210 redirectUser ($pmap[$pageno], $tabno);
1211 if (isset ($tmap[$pageno][$tabno]))
1212 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1213
1214 if (isset ($page[$pageno]['autotagloader']))
1215 $auto_tags = $page[$pageno]['autotagloader'] ();
1216 if
1217 (
1218 isset ($page[$pageno]['tagloader']) and
1219 isset ($page[$pageno]['bypass']) and
1220 isset ($_REQUEST[$page[$pageno]['bypass']])
1221 )
1222 {
1223 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1224 $impl_tags = getImplicitTags ($expl_tags);
1225 }
1226 }
1227
1228 // Build a tag chain from supplied tag id list and return it.
1229 function buildTagChainFromIds ($tagidlist)
1230 {
1231 global $taglist;
1232 $ret = array();
1233 foreach ($tagidlist as $tag_id)
1234 if (isset ($taglist[$tag_id]))
1235 $ret[] = $taglist[$tag_id];
1236 return $ret;
1237 }
1238
1239 // Process a given tag tree and return only meaningful branches. The resulting
1240 // (sub)tree will have refcnt leaves on every last branch.
1241 function getObjectiveTagTree ($tree, $realm)
1242 {
1243 $ret = array();
1244 foreach ($tree as $taginfo)
1245 {
1246 $subsearch = array();
1247 $pick = FALSE;
1248 if (count ($taginfo['kids']))
1249 {
1250 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1251 $pick = count ($subsearch) > 0;
1252 }
1253 if (isset ($taginfo['refcnt'][$realm]))
1254 $pick = TRUE;
1255 if (!$pick)
1256 continue;
1257 $ret[] = array
1258 (
1259 'id' => $taginfo['id'],
1260 'tag' => $taginfo['tag'],
1261 'parent_id' => $taginfo['parent_id'],
1262 'refcnt' => $taginfo['refcnt'],
1263 'kids' => $subsearch
1264 );
1265 }
1266 return $ret;
1267 }
1268
1269 function getTagFilter ()
1270 {
1271 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
1272 }
1273
1274 function getTagFilterStr ($tagfilter = array())
1275 {
1276 $ret = '';
1277 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
1278 $ret .= "&tagfilter[]=" . $taginfo['id'];
1279 return $ret;
1280 }
1281
1282 function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
1283 {
1284 global $root, $page, $pageno, $tabno;
1285 if ($nextpage === NULL)
1286 $nextpage = $pageno;
1287 if ($nexttab === NULL)
1288 $nexttab = $tabno;
1289 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1290 if (isset ($page[$nextpage]['bypass']))
1291 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
1292 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
1293 return $url;
1294 }
1295
1296 function buildRedirectURL ($status, $args = array(), $nextpage = NULL, $nexttab = NULL)
1297 {
1298 global $msgcode, $pageno, $tabno, $op;
1299 if ($nextpage === NULL)
1300 $nextpage = $pageno;
1301 if ($nexttab === NULL)
1302 $nexttab = $tabno;
1303 return buildWideRedirectURL (oneLiner ($msgcode[$pageno][$tabno][$op][$status], $args), $nextpage, $nexttab);
1304 }
1305
1306 // Return a message log consisting of only one message.
1307 function oneLiner ($code, $args = array())
1308 {
1309 $ret = array ('v' => 2);
1310 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1311 return $ret;
1312 }
1313
1314 function validTagName ($s, $allow_autotag = FALSE)
1315 {
1316 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1317 return TRUE;
1318 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1319 return TRUE;
1320 return FALSE;
1321 }
1322
1323 function redirectUser ($p, $t)
1324 {
1325 global $page, $root;
1326 $l = "{$root}?page=${p}&tab=${t}";
1327 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1328 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1329 header ("Location: " . $l);
1330 die;
1331 }
1332
1333 function getRackCodeStats ()
1334 {
1335 global $rackCode;
1336 $defc = $grantc = 0;
1337 foreach ($rackCode as $s)
1338 switch ($s['type'])
1339 {
1340 case 'SYNT_DEFINITION':
1341 $defc++;
1342 break;
1343 case 'SYNT_GRANT':
1344 $grantc++;
1345 break;
1346 default:
1347 break;
1348 }
1349 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1350 return $ret;
1351 }
1352
1353 function getRackImageWidth ()
1354 {
1355 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1356 }
1357
1358 function getRackImageHeight ($units)
1359 {
1360 return 3 + 3 + $units * 2;
1361 }
1362
1363 // Perform substitutions and return resulting string
1364 // used solely by buildLVSConfig()
1365 function apply_macros ($macros, $subject)
1366 {
1367 $ret = $subject;
1368 foreach ($macros as $search => $replace)
1369 $ret = str_replace ($search, $replace, $ret);
1370 return $ret;
1371 }
1372
1373 function buildLVSConfig ($object_id = 0)
1374 {
1375 if ($object_id <= 0)
1376 {
1377 showError ('Invalid argument', __FUNCTION__);
1378 return;
1379 }
1380 $oInfo = getObjectInfo ($object_id);
1381 $lbconfig = getSLBConfig ($object_id);
1382 if ($lbconfig === NULL)
1383 {
1384 showError ('getSLBConfig() failed', __FUNCTION__);
1385 return;
1386 }
1387 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1388 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1389 foreach ($lbconfig as $vs_id => $vsinfo)
1390 {
1391 $newconfig .= "########################################################\n" .
1392 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1393 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1394 "########################################################\n";
1395 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1396 $macros = array
1397 (
1398 '%VIP%' => $vsinfo['vip'],
1399 '%VPORT%' => $vsinfo['vport'],
1400 '%PROTO%' => $vsinfo['proto'],
1401 '%VNAME%' => $vsinfo['vs_name'],
1402 '%RSPOOLNAME%' => $vsinfo['pool_name']
1403 );
1404 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1405 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1406 $newconfig .= apply_macros
1407 (
1408 $macros,
1409 lf_wrap ($vsinfo['vs_vsconfig']) .
1410 lf_wrap ($vsinfo['lb_vsconfig']) .
1411 lf_wrap ($vsinfo['pool_vsconfig'])
1412 );
1413 foreach ($vsinfo['rslist'] as $rs)
1414 {
1415 $macros['%RSIP%'] = $rs['rsip'];
1416 $macros['%RSPORT%'] = $rs['rsport'];
1417 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1418 $newconfig .= apply_macros
1419 (
1420 $macros,
1421 lf_wrap ($vsinfo['vs_rsconfig']) .
1422 lf_wrap ($vsinfo['lb_rsconfig']) .
1423 lf_wrap ($vsinfo['pool_rsconfig']) .
1424 lf_wrap ($rs['rs_rsconfig'])
1425 );
1426 $newconfig .= "\t}\n";
1427 }
1428 $newconfig .= "}\n\n\n";
1429 }
1430 return $newconfig;
1431 }
1432
1433 // Indicate occupation state of each IP address: none, ordinary or problematic.
1434 function markupIPv4AddrList (&$addrlist)
1435 {
1436 foreach (array_keys ($addrlist) as $ip_bin)
1437 {
1438 $singlealloc = 0;
1439 $nvirtual = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'shared', 'eq');
1440 $nloopback = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'virtual', 'eq');
1441 $nconnected = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'regular', 'eq');
1442 $nrouter = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'router', 'eq');
1443 $nsl = ($nvirtual + $nloopback > 0) ? 1 : 0;
1444 $nrsv = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0;
1445 $nrealms = $nrsv + $nsl + $nconnected + $nrouter;
1446
1447 if ($nrealms == 1)
1448 $addrlist[$ip_bin]['class'] = 'trbusy';
1449 elseif ($nrealms > 1)
1450 $addrlist[$ip_bin]['class'] = 'trerror';
1451 else
1452 $addrlist[$ip_bin]['class'] = '';
1453 }
1454 }
1455
1456 ?>