r2192 - finally fix the issue with network sorting order
[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 // netmask conversion from length to number
273 function binMaskFromDec ($maskL)
274 {
275 $map_straight = array (
276 0 => 0x00000000,
277 1 => 0x80000000,
278 2 => 0xc0000000,
279 3 => 0xe0000000,
280 4 => 0xf0000000,
281 5 => 0xf8000000,
282 6 => 0xfc000000,
283 7 => 0xfe000000,
284 8 => 0xff000000,
285 9 => 0xff800000,
286 10 => 0xffc00000,
287 11 => 0xffe00000,
288 12 => 0xfff00000,
289 13 => 0xfff80000,
290 14 => 0xfffc0000,
291 15 => 0xfffe0000,
292 16 => 0xffff0000,
293 17 => 0xffff8000,
294 18 => 0xffffc000,
295 19 => 0xffffe000,
296 20 => 0xfffff000,
297 21 => 0xfffff800,
298 22 => 0xfffffc00,
299 23 => 0xfffffe00,
300 24 => 0xffffff00,
301 25 => 0xffffff80,
302 26 => 0xffffffc0,
303 27 => 0xffffffe0,
304 28 => 0xfffffff0,
305 29 => 0xfffffff8,
306 30 => 0xfffffffc,
307 31 => 0xfffffffe,
308 32 => 0xffffffff,
309 );
310 return $map_straight[$maskL];
311 }
312
313 // complementary value
314 function binInvMaskFromDec ($maskL)
315 {
316 $map_compl = array (
317 0 => 0xffffffff,
318 1 => 0x7fffffff,
319 2 => 0x3fffffff,
320 3 => 0x1fffffff,
321 4 => 0x0fffffff,
322 5 => 0x07ffffff,
323 6 => 0x03ffffff,
324 7 => 0x01ffffff,
325 8 => 0x00ffffff,
326 9 => 0x007fffff,
327 10 => 0x003fffff,
328 11 => 0x001fffff,
329 12 => 0x000fffff,
330 13 => 0x0007ffff,
331 14 => 0x0003ffff,
332 15 => 0x0001ffff,
333 16 => 0x0000ffff,
334 17 => 0x00007fff,
335 18 => 0x00003fff,
336 19 => 0x00001fff,
337 20 => 0x00000fff,
338 21 => 0x000007ff,
339 22 => 0x000003ff,
340 23 => 0x000001ff,
341 24 => 0x000000ff,
342 25 => 0x0000007f,
343 26 => 0x0000003f,
344 27 => 0x0000001f,
345 28 => 0x0000000f,
346 29 => 0x00000007,
347 30 => 0x00000003,
348 31 => 0x00000001,
349 32 => 0x00000000,
350 );
351 return $map_compl[$maskL];
352 }
353
354 // This function looks up 'has_problems' flag for 'T' atoms
355 // and modifies 'hl' key. May be, this should be better done
356 // in getRackData(). We don't honour 'skipped' key, because
357 // the function is also used for thumb creation.
358 function markupObjectProblems (&$rackData)
359 {
360 for ($i = $rackData['height']; $i > 0; $i--)
361 for ($locidx = 0; $locidx < 3; $locidx++)
362 if ($rackData[$i][$locidx]['state'] == 'T')
363 {
364 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
365 if ($object['has_problems'] == 'yes')
366 {
367 // Object can be already highlighted.
368 if (isset ($rackData[$i][$locidx]['hl']))
369 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
370 else
371 $rackData[$i][$locidx]['hl'] = 'w';
372 }
373 }
374 }
375
376 function search_cmpObj ($a, $b)
377 {
378 return ($a['score'] > $b['score'] ? -1 : 1);
379 }
380
381 function getObjectSearchResults ($terms)
382 {
383 $objects = array();
384 mergeSearchResults ($objects, $terms, 'name');
385 mergeSearchResults ($objects, $terms, 'label');
386 mergeSearchResults ($objects, $terms, 'asset_no');
387 mergeSearchResults ($objects, $terms, 'barcode');
388 if (count ($objects) == 1)
389 usort ($objects, 'search_cmpObj');
390 return $objects;
391 }
392
393 // This function removes all colons and dots from a string.
394 function l2addressForDatabase ($string)
395 {
396 if (empty ($string))
397 return 'NULL';
398 $pieces = explode (':', $string);
399 // This workaround is for SunOS ifconfig.
400 foreach ($pieces as &$byte)
401 if (strlen ($byte) == 1)
402 $byte = '0' . $byte;
403 // And this workaround is for PHP.
404 unset ($byte);
405 $string = implode ('', $pieces);
406 $pieces = explode ('.', $string);
407 $string = implode ('', $pieces);
408 $string = strtoupper ($string);
409 return "'$string'";
410 }
411
412 function l2addressFromDatabase ($string)
413 {
414 switch (strlen ($string))
415 {
416 case 12: // Ethernet
417 case 16: // FireWire
418 $ret = implode (':', str_split ($string, 2));
419 break;
420 default:
421 $ret = $string;
422 break;
423 }
424 return $ret;
425 }
426
427 // The following 2 functions return previous and next rack IDs for
428 // a given rack ID. The order of racks is the same as in renderRackspace()
429 // or renderRow().
430 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
431 {
432 if ($row_id <= 0 or $rack_id <= 0)
433 {
434 showError ('Invalid arguments passed', __FUNCTION__);
435 return NULL;
436 }
437 $rackList = getRacksForRow ($row_id);
438 doubleLink ($rackList);
439 if (isset ($rackList[$rack_id]['prev_key']))
440 return $rackList[$rack_id]['prev_key'];
441 return NULL;
442 }
443
444 function getNextIDforRack ($row_id = 0, $rack_id = 0)
445 {
446 if ($row_id <= 0 or $rack_id <= 0)
447 {
448 showError ('Invalid arguments passed', __FUNCTION__);
449 return NULL;
450 }
451 $rackList = getRacksForRow ($row_id);
452 doubleLink ($rackList);
453 if (isset ($rackList[$rack_id]['next_key']))
454 return $rackList[$rack_id]['next_key'];
455 return NULL;
456 }
457
458 // This function finds previous and next array keys for each array key and
459 // modifies its argument accordingly.
460 function doubleLink (&$array)
461 {
462 $prev_key = NULL;
463 foreach (array_keys ($array) as $key)
464 {
465 if ($prev_key)
466 {
467 $array[$key]['prev_key'] = $prev_key;
468 $array[$prev_key]['next_key'] = $key;
469 }
470 $prev_key = $key;
471 }
472 }
473
474 // After applying usort() to a rack list we will lose original array keys.
475 // This function restores the keys so they are equal to rack IDs.
476 function restoreRackIDs ($racks)
477 {
478 $ret = array();
479 foreach ($racks as $rack)
480 $ret[$rack['id']] = $rack;
481 return $ret;
482 }
483
484 function sortTokenize ($a, $b)
485 {
486 $aold='';
487 while ($a != $aold)
488 {
489 $aold=$a;
490 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
491 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
492 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
493 }
494
495 $bold='';
496 while ($b != $bold)
497 {
498 $bold=$b;
499 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
500 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
501 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
502 }
503
504
505
506 $ar = explode(' ', $a);
507 $br = explode(' ', $b);
508 for ($i=0; $i<count($ar) && $i<count($br); $i++)
509 {
510 $ret = 0;
511 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
512 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
513 else
514 $ret = strcasecmp($ar[$i], $br[$i]);
515 if ($ret != 0)
516 return $ret;
517 }
518 if ($i<count($ar))
519 return 1;
520 if ($i<count($br))
521 return -1;
522 return 0;
523 }
524
525 function sortByName ($a, $b)
526 {
527 return sortTokenize($a['name'], $b['name']);
528 }
529
530 function sortRacks ($a, $b)
531 {
532 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
533 }
534
535 function sortEmptyPorts ($a, $b)
536 {
537 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
538 if ($objname_cmp == 0)
539 {
540 return sortTokenize($a['Port_name'], $b['Port_name']);
541 }
542 return $objname_cmp;
543 }
544
545 function sortObjectAddressesAndNames ($a, $b)
546 {
547 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
548 if ($objname_cmp == 0)
549 {
550 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
551 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
552 $objname_cmp = sortTokenize($name_a, $name_b);
553 if ($objname_cmp == 0)
554 sortTokenize($a['ip'], $b['ip']);
555 return $objname_cmp;
556 }
557 return $objname_cmp;
558 }
559
560 function sortAddresses ($a, $b)
561 {
562 $name_cmp = sortTokenize($a['name'], $b['name']);
563 if ($name_cmp == 0)
564 {
565 return sortTokenize($a['ip'], $b['ip']);
566 }
567 return $name_cmp;
568 }
569
570 // This function expands port compat list into a matrix.
571 function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
572 {
573 $matrix = array();
574 // Create type matrix and markup compatible types.
575 foreach (array_keys ($portTypeList) as $type1)
576 foreach (array_keys ($portTypeList) as $type2)
577 $matrix[$type1][$type2] = FALSE;
578 foreach ($portCompatList as $pair)
579 $matrix[$pair['type1']][$pair['type2']] = TRUE;
580 return $matrix;
581 }
582
583 // This function returns an array of single element of object's FQDN attribute,
584 // if FQDN is set. The next choice is object's common name, if it looks like a
585 // hostname. Otherwise an array of all 'regular' IP addresses of the
586 // object is returned (which may appear 0 and more elements long).
587 function findAllEndpoints ($object_id, $fallback = '')
588 {
589 $values = getAttrValues ($object_id);
590 foreach ($values as $record)
591 if ($record['name'] == 'FQDN' && !empty ($record['value']))
592 return array ($record['value']);
593 $regular = array();
594 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
595 if ($alloc['type'] == 'regular')
596 $regular[] = $dottedquad;
597 if (!count ($regular) && !empty ($fallback))
598 return array ($fallback);
599 return $regular;
600 }
601
602 // Some records in the dictionary may be written as plain text or as Wiki
603 // link in the following syntax:
604 // 1. word
605 // 2. [[word URL]] // FIXME: this isn't working
606 // 3. [[word word word | URL]]
607 // This function parses the line and returns text suitable for either A
608 // (rendering <A HREF>) or O (for <OPTION>).
609 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
610 {
611 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
612 {
613 if ($strip_optgroup)
614 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
615 else
616 return $line;
617 }
618 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
619 $s = explode ('|', $line);
620 $o_value = trim ($s[0]);
621 if ($strip_optgroup)
622 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
623 $a_value = trim ($s[1]);
624 if ($which == 'a')
625 return "<a href='${a_value}'>${o_value}</a>";
626 if ($which == 'o')
627 return $o_value;
628 }
629
630 function buildVServiceName ($vsinfo = NULL)
631 {
632 if ($vsinfo == NULL)
633 {
634 showError ('NULL argument', __FUNCTION__);
635 return NULL;
636 }
637 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
638 }
639
640 function buildRSPoolName ($rspool = NULL)
641 {
642 if ($rspool == NULL)
643 {
644 showError ('NULL argument', __FUNCTION__);
645 return NULL;
646 }
647 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
648 }
649
650 // rackspace usage for a single rack
651 // (T + W + U) / (height * 3 - A)
652 function getRSUforRack ($data = NULL)
653 {
654 if ($data == NULL)
655 {
656 showError ('Invalid argument', __FUNCTION__);
657 return NULL;
658 }
659 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
660 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
661 for ($locidx = 0; $locidx < 3; $locidx++)
662 $counter[$data[$unit_no][$locidx]['state']]++;
663 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
664 }
665
666 // Same for row.
667 function getRSUforRackRow ($rowData = NULL)
668 {
669 if ($rowData === NULL)
670 {
671 showError ('Invalid argument', __FUNCTION__);
672 return NULL;
673 }
674 if (!count ($rowData))
675 return 0;
676 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
677 $total_height = 0;
678 foreach (array_keys ($rowData) as $rack_id)
679 {
680 $data = getRackData ($rack_id);
681 $total_height += $data['height'];
682 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
683 for ($locidx = 0; $locidx < 3; $locidx++)
684 $counter[$data[$unit_no][$locidx]['state']]++;
685 }
686 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
687 }
688
689 // Return a list of object IDs, which can be found in the given rackspace block.
690 function stuffInRackspace ($rackData)
691 {
692 $objects = array();
693 for ($i = $rackData['height']; $i > 0; $i--)
694 for ($locidx = 0; $locidx < 3; $locidx++)
695 if
696 (
697 $rackData[$i][$locidx]['state'] == 'T' and
698 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
699 )
700 $objects[] = $rackData[$i][$locidx]['object_id'];
701 return $objects;
702 }
703
704 // Make sure the string is always wrapped with LF characters
705 function lf_wrap ($str)
706 {
707 $ret = trim ($str, "\r\n");
708 if (!empty ($ret))
709 $ret .= "\n";
710 return $ret;
711 }
712
713 // Adopted from Mantis BTS code.
714 function string_insert_hrefs ($s)
715 {
716 if (getConfigVar ('DETECT_URLS') != 'yes')
717 return $s;
718 # Find any URL in a string and replace it by a clickable link
719 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
720 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
721 $s);
722 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
723 '<a href="mailto:\0">\0</a>',
724 $s);
725 return $s;
726 }
727
728 // Idem.
729 function email_regex_simple ()
730 {
731 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
732 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
733 }
734
735 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
736 // for the requested object_type_id.
737 function getAutoPorts ($type_id)
738 {
739 $ret = array();
740 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
741 foreach ($typemap as $equation)
742 {
743 $tmp = explode ('=', $equation);
744 if (count ($tmp) != 2)
745 continue;
746 $objtype_id = $tmp[0];
747 if ($objtype_id != $type_id)
748 continue;
749 $portlist = $tmp[1];
750 foreach (explode ('+', $portlist) as $product)
751 {
752 $tmp = explode ('*', $product);
753 if (count ($tmp) != 3)
754 continue;
755 $nports = $tmp[0];
756 $port_type = $tmp[1];
757 $format = $tmp[2];
758 for ($i = 0; $i < $nports; $i++)
759 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
760 }
761 }
762 return $ret;
763 }
764
765 // Find if a particular tag id exists on the tree, then attach the
766 // given child tag to it. If the parent tag doesn't exist, return FALSE.
767 function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
768 {
769 foreach ($tree as $tagid => $taginfo)
770 {
771 if ($tagid == $parent_id)
772 {
773 $tree[$tagid]['kids'][$child_id] = $child_info;
774 return TRUE;
775 }
776 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
777 return TRUE;
778 }
779 return FALSE;
780 }
781
782 function getTagTree ()
783 {
784 global $taglist;
785 return treeFromList ($taglist);
786 }
787
788 // Build a tree from the item list and return it. Input and output data is
789 // indexed by item id (nested items in output are recursively stored in 'kids'
790 // key, which is in turn indexed by id.
791 function treeFromList ($mytaglist)
792 {
793 $ret = array();
794 while (count ($mytaglist) > 0)
795 {
796 $picked = FALSE;
797 foreach ($mytaglist as $tagid => $taginfo)
798 {
799 $taginfo['kids'] = array();
800 if ($taginfo['parent_id'] == NULL)
801 {
802 $ret[$tagid] = $taginfo;
803 $picked = TRUE;
804 unset ($mytaglist[$tagid]);
805 }
806 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
807 {
808 $picked = TRUE;
809 unset ($mytaglist[$tagid]);
810 }
811 }
812 if (!$picked) // Only orphaned items on the list.
813 break;
814 }
815 return $ret;
816 }
817
818 // Build a tree from the tag list and return everything _except_ the tree.
819 function getOrphanedTags ()
820 {
821 global $taglist;
822 $mytaglist = $taglist;
823 $dummy = array();
824 while (count ($mytaglist) > 0)
825 {
826 $picked = FALSE;
827 foreach ($mytaglist as $tagid => $taginfo)
828 {
829 $taginfo['kids'] = array();
830 if ($taginfo['parent_id'] == NULL)
831 {
832 $dummy[$tagid] = $taginfo;
833 $picked = TRUE;
834 unset ($mytaglist[$tagid]);
835 }
836 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
837 {
838 $picked = TRUE;
839 unset ($mytaglist[$tagid]);
840 }
841 }
842 if (!$picked) // Only orphaned items on the list.
843 return $mytaglist;
844 }
845 return array();
846 }
847
848 function serializeTags ($chain, $baseurl = '')
849 {
850 $comma = '';
851 $ret = '';
852 foreach ($chain as $taginfo)
853 {
854 $ret .= $comma .
855 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
856 $taginfo['tag'] .
857 ($baseurl == '' ? '' : '</a>');
858 $comma = ', ';
859 }
860 return $ret;
861 }
862
863 // a helper for getTagChainExpansion()
864 function traceTagChain ($tree, $chain)
865 {
866 // For each tag find its path from the root, then combine items
867 // of all paths and add them to the chain, if they aren't there yet.
868 $ret = array();
869 foreach ($tree as $taginfo1)
870 {
871 $hit = FALSE;
872 foreach ($chain as $taginfo2)
873 if ($taginfo1['id'] == $taginfo2['id'])
874 {
875 $hit = TRUE;
876 break;
877 }
878 if (count ($taginfo1['kids']) > 0)
879 {
880 $subsearch = traceTagChain ($taginfo1['kids'], $chain);
881 if (count ($subsearch))
882 {
883 $hit = TRUE;
884 $ret = array_merge ($ret, $subsearch);
885 }
886 }
887 if ($hit)
888 $ret[] = $taginfo1;
889 }
890 return $ret;
891 }
892
893 // For each tag add all its parent tags onto the list. Don't expect anything
894 // except user's tags on the chain.
895 function getTagChainExpansion ($chain)
896 {
897 global $tagtree;
898 return traceTagChain ($tagtree, $chain);
899 }
900
901 // Return the list of missing implicit tags.
902 function getImplicitTags ($oldtags)
903 {
904 $ret = array();
905 $newtags = getTagChainExpansion ($oldtags);
906 foreach ($newtags as $newtag)
907 {
908 $already_exists = FALSE;
909 foreach ($oldtags as $oldtag)
910 if ($newtag['id'] == $oldtag['id'])
911 {
912 $already_exists = TRUE;
913 break;
914 }
915 if ($already_exists)
916 continue;
917 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
918 }
919 return $ret;
920 }
921
922 // Minimize the chain: exclude all implicit tags and return the result.
923 function getExplicitTagsOnly ($chain, $tree = NULL)
924 {
925 global $tagtree;
926 if ($tree === NULL)
927 $tree = $tagtree;
928 $ret = array();
929 foreach ($tree as $taginfo)
930 {
931 if (isset ($taginfo['kids']))
932 {
933 $harvest = getExplicitTagsOnly ($chain, $taginfo['kids']);
934 if (count ($harvest) > 0)
935 {
936 $ret = array_merge ($ret, $harvest);
937 continue;
938 }
939 }
940 // This tag isn't implicit, test is for being explicit.
941 foreach ($chain as $testtag)
942 if ($taginfo['id'] == $testtag['id'])
943 {
944 $ret[] = $testtag;
945 break;
946 }
947 }
948 return $ret;
949 }
950
951 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
952 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
953 // a list of tag structures. Same structure (tag ID list) is returned after processing.
954 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
955 {
956 global $tagtree;
957 if ($tree === NULL)
958 $tree = $tagtree;
959 $getallkids = $getall;
960 $ret = array();
961 foreach ($tree as $taginfo)
962 {
963 foreach ($idlist as $test_id)
964 if ($getall or $taginfo['id'] == $test_id)
965 {
966 $ret[] = $taginfo['id'];
967 // Once matched node makes all sub-nodes match, but don't make
968 // a mistake of matching every other node at the current level.
969 $getallkids = TRUE;
970 break;
971 }
972 if (isset ($taginfo['kids']))
973 $ret = array_merge ($ret, complementByKids ($idlist, $taginfo['kids'], $getallkids));
974 $getallkids = FALSE;
975 }
976 return $ret;
977 }
978
979 function getUserAutoTags ($username = NULL)
980 {
981 global $remote_username, $accounts;
982 if ($username == NULL)
983 $username = $remote_username;
984 $ret = array();
985 $ret[] = array ('tag' => '$username_' . $username);
986 if (isset ($accounts[$username]['user_id']))
987 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
988 return $ret;
989 }
990
991 function loadRackObjectAutoTags ()
992 {
993 assertUIntArg ('object_id', __FUNCTION__);
994 $object_id = $_REQUEST['object_id'];
995 $oinfo = getObjectInfo ($object_id);
996 $ret = array();
997 $ret[] = array ('tag' => '$id_' . $object_id);
998 $ret[] = array ('tag' => '$typeid_' . $oinfo['objtype_id']);
999 $ret[] = array ('tag' => '$any_object');
1000 if (validTagName ($oinfo['name']))
1001 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
1002 return $ret;
1003 }
1004
1005 // Common code for both prefix and address tag listers.
1006 function getIPv4PrefixTags ($netid)
1007 {
1008 $netinfo = getIPv4NetworkInfo ($netid);
1009 $ret = array();
1010 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $netinfo['ip']) . '-' . $netinfo['mask']);
1011 // FIXME: find and list tags for all parent networks?
1012 $ret[] = array ('tag' => '$any_ip4net');
1013 $ret[] = array ('tag' => '$any_net');
1014 return $ret;
1015 }
1016
1017 function loadIPv4PrefixAutoTags ()
1018 {
1019 assertUIntArg ('id', __FUNCTION__);
1020 return array_merge
1021 (
1022 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
1023 getIPv4PrefixTags ($_REQUEST['id'])
1024 );
1025 }
1026
1027 function loadIPv4AddressAutoTags ()
1028 {
1029 assertIPv4Arg ('ip', __FUNCTION__);
1030 return array_merge
1031 (
1032 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
1033 getIPv4PrefixTags (getIPv4AddressNetworkId ($_REQUEST['ip']))
1034 );
1035 }
1036
1037 function loadRackAutoTags ()
1038 {
1039 assertUIntArg ('rack_id', __FUNCTION__);
1040 $ret = array();
1041 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
1042 $ret[] = array ('tag' => '$any_rack');
1043 return $ret;
1044 }
1045
1046 function loadIPv4VSAutoTags ()
1047 {
1048 assertUIntArg ('vs_id', __FUNCTION__);
1049 $ret = array();
1050 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
1051 $ret[] = array ('tag' => '$any_ipv4vs');
1052 $ret[] = array ('tag' => '$any_vs');
1053 return $ret;
1054 }
1055
1056 function loadIPv4RSPoolAutoTags ()
1057 {
1058 assertUIntArg ('pool_id', __FUNCTION__);
1059 $ret = array();
1060 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1061 $ret[] = array ('tag' => '$any_ipv4rsp');
1062 $ret[] = array ('tag' => '$any_rsp');
1063 return $ret;
1064 }
1065
1066 // Check, if the given tag is present on the chain (will only work
1067 // for regular tags with tag ID set.
1068 function tagOnChain ($taginfo, $tagchain)
1069 {
1070 if (!isset ($taginfo['id']))
1071 return FALSE;
1072 foreach ($tagchain as $test)
1073 if ($test['id'] == $taginfo['id'])
1074 return TRUE;
1075 return FALSE;
1076 }
1077
1078 // Idem, but use ID list instead of chain.
1079 function tagOnIdList ($taginfo, $tagidlist)
1080 {
1081 if (!isset ($taginfo['id']))
1082 return FALSE;
1083 foreach ($tagidlist as $tagid)
1084 if ($taginfo['id'] == $tagid)
1085 return TRUE;
1086 return FALSE;
1087 }
1088
1089 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1090 // Assume, that neither of the lists contains duplicates.
1091 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1092 function tagChainCmp ($chain1, $chain2)
1093 {
1094 if (count ($chain1) != count ($chain2))
1095 return TRUE;
1096 foreach ($chain1 as $taginfo1)
1097 if (!tagOnChain ($taginfo1, $chain2))
1098 return TRUE;
1099 return FALSE;
1100 }
1101
1102 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1103 // hold all appropriate (explicit and implicit) tags respectively.
1104 // Otherwise some limited redirection is necessary (only page and tab
1105 // names are preserved, ophandler name change isn't handled).
1106 function fixContext ()
1107 {
1108 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
1109
1110 $pmap = array
1111 (
1112 'accounts' => 'userlist',
1113 'rspools' => 'ipv4rsplist',
1114 'rspool' => 'ipv4rsp',
1115 'vservices' => 'ipv4vslist',
1116 'vservice' => 'ipv4vs',
1117 );
1118 $tmap = array();
1119 $tmap['objects']['newmulti'] = 'addmore';
1120 $tmap['objects']['newobj'] = 'addmore';
1121 $tmap['object']['switchvlans'] = 'livevlans';
1122 $tmap['object']['slb'] = 'editrspvs';
1123 $tmap['object']['portfwrd'] = 'nat4';
1124 $tmap['object']['network'] = 'ipv4';
1125 if (isset ($pmap[$pageno]))
1126 redirectUser ($pmap[$pageno], $tabno);
1127 if (isset ($tmap[$pageno][$tabno]))
1128 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1129
1130 if (isset ($page[$pageno]['autotagloader']))
1131 $auto_tags = $page[$pageno]['autotagloader'] ();
1132 if
1133 (
1134 isset ($page[$pageno]['tagloader']) and
1135 isset ($page[$pageno]['bypass']) and
1136 isset ($_REQUEST[$page[$pageno]['bypass']])
1137 )
1138 {
1139 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1140 $impl_tags = getImplicitTags ($expl_tags);
1141 }
1142 }
1143
1144 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1145 // records indexed by tag IDs (tag chain).
1146 function buildTagChainFromIds ($tagidlist)
1147 {
1148 global $taglist;
1149 $ret = array();
1150 foreach (array_unique ($tagidlist) as $tag_id)
1151 if (isset ($taglist[$tag_id]))
1152 $ret[] = $taglist[$tag_id];
1153 return $ret;
1154 }
1155
1156 // Process a given tag tree and return only meaningful branches. The resulting
1157 // (sub)tree will have refcnt leaves on every last branch.
1158 function getObjectiveTagTree ($tree, $realm)
1159 {
1160 $ret = array();
1161 foreach ($tree as $taginfo)
1162 {
1163 $subsearch = array();
1164 $pick = FALSE;
1165 if (count ($taginfo['kids']))
1166 {
1167 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1168 $pick = count ($subsearch) > 0;
1169 }
1170 if (isset ($taginfo['refcnt'][$realm]))
1171 $pick = TRUE;
1172 if (!$pick)
1173 continue;
1174 $ret[] = array
1175 (
1176 'id' => $taginfo['id'],
1177 'tag' => $taginfo['tag'],
1178 'parent_id' => $taginfo['parent_id'],
1179 'refcnt' => $taginfo['refcnt'],
1180 'kids' => $subsearch
1181 );
1182 }
1183 return $ret;
1184 }
1185
1186 function getTagFilter ()
1187 {
1188 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
1189 }
1190
1191 function getTagFilterStr ($tagfilter = array())
1192 {
1193 $ret = '';
1194 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
1195 $ret .= "&tagfilter[]=" . $taginfo['id'];
1196 return $ret;
1197 }
1198
1199 function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
1200 {
1201 global $root, $page, $pageno, $tabno;
1202 if ($nextpage === NULL)
1203 $nextpage = $pageno;
1204 if ($nexttab === NULL)
1205 $nexttab = $tabno;
1206 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1207 if (isset ($page[$nextpage]['bypass']))
1208 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
1209 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
1210 return $url;
1211 }
1212
1213 function buildRedirectURL ($status, $args = array(), $nextpage = NULL, $nexttab = NULL)
1214 {
1215 global $msgcode, $pageno, $tabno, $op;
1216 if ($nextpage === NULL)
1217 $nextpage = $pageno;
1218 if ($nexttab === NULL)
1219 $nexttab = $tabno;
1220 return buildWideRedirectURL (oneLiner ($msgcode[$pageno][$tabno][$op][$status], $args), $nextpage, $nexttab);
1221 }
1222
1223 // Return a message log consisting of only one message.
1224 function oneLiner ($code, $args = array())
1225 {
1226 $ret = array ('v' => 2);
1227 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1228 return $ret;
1229 }
1230
1231 // Return mesage code by status code.
1232 function getMessageCode ($status)
1233 {
1234 global $pageno, $tabno, $op, $msgcode;
1235 return $msgcode[$pageno][$tabno][$op][$status];
1236 }
1237
1238 function validTagName ($s, $allow_autotag = FALSE)
1239 {
1240 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1241 return TRUE;
1242 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1243 return TRUE;
1244 return FALSE;
1245 }
1246
1247 function redirectUser ($p, $t)
1248 {
1249 global $page, $root;
1250 $l = "{$root}?page=${p}&tab=${t}";
1251 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1252 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1253 header ("Location: " . $l);
1254 die;
1255 }
1256
1257 function getRackCodeStats ()
1258 {
1259 global $rackCode;
1260 $defc = $grantc = 0;
1261 foreach ($rackCode as $s)
1262 switch ($s['type'])
1263 {
1264 case 'SYNT_DEFINITION':
1265 $defc++;
1266 break;
1267 case 'SYNT_GRANT':
1268 $grantc++;
1269 break;
1270 default:
1271 break;
1272 }
1273 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1274 return $ret;
1275 }
1276
1277 function getRackImageWidth ()
1278 {
1279 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1280 }
1281
1282 function getRackImageHeight ($units)
1283 {
1284 return 3 + 3 + $units * 2;
1285 }
1286
1287 // Perform substitutions and return resulting string
1288 // used solely by buildLVSConfig()
1289 function apply_macros ($macros, $subject)
1290 {
1291 $ret = $subject;
1292 foreach ($macros as $search => $replace)
1293 $ret = str_replace ($search, $replace, $ret);
1294 return $ret;
1295 }
1296
1297 function buildLVSConfig ($object_id = 0)
1298 {
1299 if ($object_id <= 0)
1300 {
1301 showError ('Invalid argument', __FUNCTION__);
1302 return;
1303 }
1304 $oInfo = getObjectInfo ($object_id);
1305 $lbconfig = getSLBConfig ($object_id);
1306 if ($lbconfig === NULL)
1307 {
1308 showError ('getSLBConfig() failed', __FUNCTION__);
1309 return;
1310 }
1311 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1312 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1313 foreach ($lbconfig as $vs_id => $vsinfo)
1314 {
1315 $newconfig .= "########################################################\n" .
1316 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1317 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1318 "########################################################\n";
1319 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1320 $macros = array
1321 (
1322 '%VIP%' => $vsinfo['vip'],
1323 '%VPORT%' => $vsinfo['vport'],
1324 '%PROTO%' => $vsinfo['proto'],
1325 '%VNAME%' => $vsinfo['vs_name'],
1326 '%RSPOOLNAME%' => $vsinfo['pool_name']
1327 );
1328 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1329 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1330 $newconfig .= apply_macros
1331 (
1332 $macros,
1333 lf_wrap ($vsinfo['vs_vsconfig']) .
1334 lf_wrap ($vsinfo['lb_vsconfig']) .
1335 lf_wrap ($vsinfo['pool_vsconfig'])
1336 );
1337 foreach ($vsinfo['rslist'] as $rs)
1338 {
1339 if (empty ($rs['rsport']))
1340 $rs['rsport'] = $vsinfo['vport'];
1341 $macros['%RSIP%'] = $rs['rsip'];
1342 $macros['%RSPORT%'] = $rs['rsport'];
1343 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1344 $newconfig .= apply_macros
1345 (
1346 $macros,
1347 lf_wrap ($vsinfo['vs_rsconfig']) .
1348 lf_wrap ($vsinfo['lb_rsconfig']) .
1349 lf_wrap ($vsinfo['pool_rsconfig']) .
1350 lf_wrap ($rs['rs_rsconfig'])
1351 );
1352 $newconfig .= "\t}\n";
1353 }
1354 $newconfig .= "}\n\n\n";
1355 }
1356 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1357 return str_replace ("\r", '', $newconfig);
1358 }
1359
1360 // Indicate occupation state of each IP address: none, ordinary or problematic.
1361 function markupIPv4AddrList (&$addrlist)
1362 {
1363 foreach (array_keys ($addrlist) as $ip_bin)
1364 {
1365 $refc = array
1366 (
1367 'shared' => 0, // virtual
1368 'virtual' => 0, // loopback
1369 'regular' => 0, // connected host
1370 'router' => 0 // connected gateway
1371 );
1372 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1373 $refc[$a['type']]++;
1374 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
1375 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1376 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
1377
1378 if ($nrealms == 1)
1379 $addrlist[$ip_bin]['class'] = 'trbusy';
1380 elseif ($nrealms > 1)
1381 $addrlist[$ip_bin]['class'] = 'trerror';
1382 else
1383 $addrlist[$ip_bin]['class'] = '';
1384 }
1385 }
1386
1387 // Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1388 function findRouters ($addrlist)
1389 {
1390 $ret = array();
1391 foreach ($addrlist as $addr)
1392 foreach ($addr['allocs'] as $alloc)
1393 if ($alloc['type'] == 'router')
1394 $ret[] = array
1395 (
1396 'id' => $alloc['object_id'],
1397 'iface' => $alloc['name'],
1398 'dname' => $alloc['object_name'],
1399 'addr' => $addr['ip']
1400 );
1401 return $ret;
1402 }
1403
1404 // Assist in tag chain sorting.
1405 function taginfoCmp ($tagA, $tagB)
1406 {
1407 return $tagA['ci'] - $tagB['ci'];
1408 }
1409
1410 // Compare networks. When sorting a tree, the records on the list will have
1411 // distinct base IP addresses.
1412 function IPv4NetworkCmp ($netA, $netB)
1413 {
1414 // There's a problem just substracting one u32 integer from another,
1415 // because the result may happen big enough to become a negative i32
1416 // integer itself (PHP tries to cast everything it sees to signed int).
1417 if ($netA['db_first'] > $netB['db_first'])
1418 return 1;
1419 elseif ($netA['db_first'] < $netB['db_first'])
1420 return -1;
1421 else
1422 return 0;
1423 }
1424
1425 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1426 function sortTree (&$tree, $sortfunc = '')
1427 {
1428 if (empty ($sortfunc))
1429 return;
1430 usort ($tree, $sortfunc);
1431 // Don't make a mistake of directly iterating over the items of current level, because this way
1432 // the sorting will be performed on a _copy_ if each item, not the item itself.
1433 foreach (array_keys ($tree) as $tagid)
1434 sortTree ($tree[$tagid]['kids'], $sortfunc);
1435 }
1436
1437 ?>