r2358 - repace 2 sets of tag and file management functions with unified processors
[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 // Entity type by page number mapping is 1:1 atm, but may change later.
28 $etype_by_pageno = array
29 (
30 'ipv4net' => 'ipv4net',
31 'ipv4rspool' => 'ipv4rspool',
32 'ipv4vs' => 'ipv4vs',
33 'object' => 'object',
34 'rack' => 'rack',
35 'user' => 'user',
36 'file' => 'file',
37 );
38
39 // Objects of some types should be explicitly shown as
40 // anonymous (labelless). This function is a single place where the
41 // decision about displayed name is made.
42 function displayedName ($objectData)
43 {
44 if ($objectData['name'] != '')
45 return $objectData['name'];
46 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
47 return "ANONYMOUS " . $objectData['objtype_name'];
48 else
49 return "[${objectData['objtype_name']}]";
50 }
51
52 // This function finds height of solid rectangle of atoms, which are all
53 // assigned to the same object. Rectangle base is defined by specified
54 // template.
55 function rectHeight ($rackData, $startRow, $template_idx)
56 {
57 $height = 0;
58 // The first met object_id is used to match all the folowing IDs.
59 $object_id = 0;
60 global $template;
61 do
62 {
63 for ($locidx = 0; $locidx < 3; $locidx++)
64 {
65 // At least one value in template is TRUE, but the following block
66 // can meet 'skipped' atoms. Let's ensure we have something after processing
67 // the first row.
68 if ($template[$template_idx][$locidx])
69 {
70 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
71 break 2;
72 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
73 break 2;
74 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
75 break 2;
76 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
77 break 2;
78 if ($object_id == 0)
79 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
80 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
81 break 2;
82 }
83 }
84 // If the first row can't offer anything, bail out.
85 if ($height == 0 and $object_id == 0)
86 break;
87 $height++;
88 }
89 while ($startRow - $height > 0);
90 # echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
91 # echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
92 # echo ") height==${height}<br>\n";
93 return $height;
94 }
95
96 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
97 // attributes.
98 function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
99 {
100 global $template, $templateWidth;
101 $colspan = 0;
102 for ($height = 0; $height < $maxheight; $height++)
103 {
104 for ($locidx = 0; $locidx < 3; $locidx++)
105 {
106 if ($template[$template_idx][$locidx])
107 {
108 // Add colspan/rowspan to the first row met and mark the following ones to skip.
109 // Explicitly show even single-cell spanned atoms, because rectHeight()
110 // is expeciting this data for correct calculation.
111 if ($colspan != 0)
112 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
113 else
114 {
115 $colspan = $templateWidth[$template_idx];
116 if ($colspan >= 1)
117 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
118 if ($maxheight >= 1)
119 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
120 }
121 }
122 }
123 }
124 return;
125 }
126
127 // This function sets rowspan/solspan/skipped atom attributes for renderRack()
128 // What we actually have to do is to find _all_ possible rectangles for each unit
129 // and then select the widest of those with the maximal square.
130 function markAllSpans (&$rackData = NULL)
131 {
132 if ($rackData == NULL)
133 {
134 showError ('Invalid rackData', __FUNCTION__);
135 return;
136 }
137 for ($i = $rackData['height']; $i > 0; $i--)
138 while (markBestSpan ($rackData, $i));
139 }
140
141 // Calculate height of 6 possible span templates (array is presorted by width
142 // descending) and mark the best (if any).
143 function markBestSpan (&$rackData, $i)
144 {
145 global $template, $templateWidth;
146 for ($j = 0; $j < 6; $j++)
147 {
148 $height[$j] = rectHeight ($rackData, $i, $j);
149 $square[$j] = $height[$j] * $templateWidth[$j];
150 }
151 // find the widest rectangle of those with maximal height
152 $maxsquare = max ($square);
153 if (!$maxsquare)
154 return FALSE;
155 $best_template_index = 0;
156 for ($j = 0; $j < 6; $j++)
157 if ($square[$j] == $maxsquare)
158 {
159 $best_template_index = $j;
160 $bestheight = $height[$j];
161 break;
162 }
163 // distribute span marks
164 markSpan ($rackData, $i, $bestheight, $best_template_index);
165 return TRUE;
166 }
167
168 // We can mount 'F' atoms and unmount our own 'T' atoms.
169 function applyObjectMountMask (&$rackData, $object_id)
170 {
171 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
172 for ($locidx = 0; $locidx < 3; $locidx++)
173 switch ($rackData[$unit_no][$locidx]['state'])
174 {
175 case 'F':
176 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
177 break;
178 case 'T':
179 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
180 break;
181 default:
182 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
183 }
184 }
185
186 // Design change means transition between 'F' and 'A' and back.
187 function applyRackDesignMask (&$rackData)
188 {
189 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
190 for ($locidx = 0; $locidx < 3; $locidx++)
191 switch ($rackData[$unit_no][$locidx]['state'])
192 {
193 case 'F':
194 case 'A':
195 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
196 break;
197 default:
198 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
199 }
200 }
201
202 // The same for 'F' and 'U'.
203 function applyRackProblemMask (&$rackData)
204 {
205 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
206 for ($locidx = 0; $locidx < 3; $locidx++)
207 switch ($rackData[$unit_no][$locidx]['state'])
208 {
209 case 'F':
210 case 'U':
211 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
212 break;
213 default:
214 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
215 }
216 }
217
218 // This mask should allow toggling 'T' and 'W' on object's rackspace.
219 function applyObjectProblemMask (&$rackData)
220 {
221 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
222 for ($locidx = 0; $locidx < 3; $locidx++)
223 switch ($rackData[$unit_no][$locidx]['state'])
224 {
225 case 'T':
226 case 'W':
227 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
228 break;
229 default:
230 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
231 }
232 }
233
234 // This function highlights specified object (and removes previous highlight).
235 function highlightObject (&$rackData, $object_id)
236 {
237 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
238 for ($locidx = 0; $locidx < 3; $locidx++)
239 if
240 (
241 $rackData[$unit_no][$locidx]['state'] == 'T' and
242 $rackData[$unit_no][$locidx]['object_id'] == $object_id
243 )
244 $rackData[$unit_no][$locidx]['hl'] = 'h';
245 else
246 unset ($rackData[$unit_no][$locidx]['hl']);
247 }
248
249 // This function marks atoms to selected or not depending on their current state.
250 function markupAtomGrid (&$data, $checked_state)
251 {
252 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
253 for ($locidx = 0; $locidx < 3; $locidx++)
254 {
255 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
256 continue;
257 if ($data[$unit_no][$locidx]['state'] == $checked_state)
258 $data[$unit_no][$locidx]['checked'] = ' checked';
259 else
260 $data[$unit_no][$locidx]['checked'] = '';
261 }
262 }
263
264 // This function is almost a clone of processGridForm(), but doesn't save anything to database
265 // Return value is the changed rack data.
266 // Here we assume that correct filter has already been applied, so we just
267 // set or unset checkbox inputs w/o changing atom state.
268 function mergeGridFormToRack (&$rackData)
269 {
270 $rack_id = $rackData['id'];
271 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
272 for ($locidx = 0; $locidx < 3; $locidx++)
273 {
274 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
275 continue;
276 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
277 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
278 $rackData[$unit_no][$locidx]['checked'] = ' checked';
279 else
280 $rackData[$unit_no][$locidx]['checked'] = '';
281 }
282 }
283
284 // netmask conversion from length to number
285 function binMaskFromDec ($maskL)
286 {
287 $map_straight = array (
288 0 => 0x00000000,
289 1 => 0x80000000,
290 2 => 0xc0000000,
291 3 => 0xe0000000,
292 4 => 0xf0000000,
293 5 => 0xf8000000,
294 6 => 0xfc000000,
295 7 => 0xfe000000,
296 8 => 0xff000000,
297 9 => 0xff800000,
298 10 => 0xffc00000,
299 11 => 0xffe00000,
300 12 => 0xfff00000,
301 13 => 0xfff80000,
302 14 => 0xfffc0000,
303 15 => 0xfffe0000,
304 16 => 0xffff0000,
305 17 => 0xffff8000,
306 18 => 0xffffc000,
307 19 => 0xffffe000,
308 20 => 0xfffff000,
309 21 => 0xfffff800,
310 22 => 0xfffffc00,
311 23 => 0xfffffe00,
312 24 => 0xffffff00,
313 25 => 0xffffff80,
314 26 => 0xffffffc0,
315 27 => 0xffffffe0,
316 28 => 0xfffffff0,
317 29 => 0xfffffff8,
318 30 => 0xfffffffc,
319 31 => 0xfffffffe,
320 32 => 0xffffffff,
321 );
322 return $map_straight[$maskL];
323 }
324
325 // complementary value
326 function binInvMaskFromDec ($maskL)
327 {
328 $map_compl = array (
329 0 => 0xffffffff,
330 1 => 0x7fffffff,
331 2 => 0x3fffffff,
332 3 => 0x1fffffff,
333 4 => 0x0fffffff,
334 5 => 0x07ffffff,
335 6 => 0x03ffffff,
336 7 => 0x01ffffff,
337 8 => 0x00ffffff,
338 9 => 0x007fffff,
339 10 => 0x003fffff,
340 11 => 0x001fffff,
341 12 => 0x000fffff,
342 13 => 0x0007ffff,
343 14 => 0x0003ffff,
344 15 => 0x0001ffff,
345 16 => 0x0000ffff,
346 17 => 0x00007fff,
347 18 => 0x00003fff,
348 19 => 0x00001fff,
349 20 => 0x00000fff,
350 21 => 0x000007ff,
351 22 => 0x000003ff,
352 23 => 0x000001ff,
353 24 => 0x000000ff,
354 25 => 0x0000007f,
355 26 => 0x0000003f,
356 27 => 0x0000001f,
357 28 => 0x0000000f,
358 29 => 0x00000007,
359 30 => 0x00000003,
360 31 => 0x00000001,
361 32 => 0x00000000,
362 );
363 return $map_compl[$maskL];
364 }
365
366 // This function looks up 'has_problems' flag for 'T' atoms
367 // and modifies 'hl' key. May be, this should be better done
368 // in getRackData(). We don't honour 'skipped' key, because
369 // the function is also used for thumb creation.
370 function markupObjectProblems (&$rackData)
371 {
372 for ($i = $rackData['height']; $i > 0; $i--)
373 for ($locidx = 0; $locidx < 3; $locidx++)
374 if ($rackData[$i][$locidx]['state'] == 'T')
375 {
376 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
377 if ($object['has_problems'] == 'yes')
378 {
379 // Object can be already highlighted.
380 if (isset ($rackData[$i][$locidx]['hl']))
381 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
382 else
383 $rackData[$i][$locidx]['hl'] = 'w';
384 }
385 }
386 }
387
388 function search_cmpObj ($a, $b)
389 {
390 return ($a['score'] > $b['score'] ? -1 : 1);
391 }
392
393 function getObjectSearchResults ($terms)
394 {
395 $objects = array();
396 mergeSearchResults ($objects, $terms, 'name');
397 mergeSearchResults ($objects, $terms, 'label');
398 mergeSearchResults ($objects, $terms, 'asset_no');
399 mergeSearchResults ($objects, $terms, 'barcode');
400 if (count ($objects) == 1)
401 usort ($objects, 'search_cmpObj');
402 return $objects;
403 }
404
405 // This function removes all colons and dots from a string.
406 function l2addressForDatabase ($string)
407 {
408 $string = strtoupper ($string);
409 switch (TRUE)
410 {
411 case ($string == '' or preg_match (RE_L2_SOLID, $string)):
412 return $string;
413 case (preg_match (RE_L2_IFCFG, $string)):
414 $pieces = explode (':', $string);
415 // This workaround is for SunOS ifconfig.
416 foreach ($pieces as &$byte)
417 if (strlen ($byte) == 1)
418 $byte = '0' . $byte;
419 // And this workaround is for PHP.
420 unset ($byte);
421 return implode ('', $pieces);
422 case (preg_match (RE_L2_CISCO, $string)):
423 return implode ('', explode ('.', $string));
424 default:
425 return NULL;
426 }
427 }
428
429 function l2addressFromDatabase ($string)
430 {
431 switch (strlen ($string))
432 {
433 case 12: // Ethernet
434 case 16: // FireWire
435 $ret = implode (':', str_split ($string, 2));
436 break;
437 default:
438 $ret = $string;
439 break;
440 }
441 return $ret;
442 }
443
444 // The following 2 functions return previous and next rack IDs for
445 // a given rack ID. The order of racks is the same as in renderRackspace()
446 // or renderRow().
447 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
448 {
449 if ($row_id <= 0 or $rack_id <= 0)
450 {
451 showError ('Invalid arguments passed', __FUNCTION__);
452 return NULL;
453 }
454 $rackList = getRacksForRow ($row_id);
455 doubleLink ($rackList);
456 if (isset ($rackList[$rack_id]['prev_key']))
457 return $rackList[$rack_id]['prev_key'];
458 return NULL;
459 }
460
461 function getNextIDforRack ($row_id = 0, $rack_id = 0)
462 {
463 if ($row_id <= 0 or $rack_id <= 0)
464 {
465 showError ('Invalid arguments passed', __FUNCTION__);
466 return NULL;
467 }
468 $rackList = getRacksForRow ($row_id);
469 doubleLink ($rackList);
470 if (isset ($rackList[$rack_id]['next_key']))
471 return $rackList[$rack_id]['next_key'];
472 return NULL;
473 }
474
475 // This function finds previous and next array keys for each array key and
476 // modifies its argument accordingly.
477 function doubleLink (&$array)
478 {
479 $prev_key = NULL;
480 foreach (array_keys ($array) as $key)
481 {
482 if ($prev_key)
483 {
484 $array[$key]['prev_key'] = $prev_key;
485 $array[$prev_key]['next_key'] = $key;
486 }
487 $prev_key = $key;
488 }
489 }
490
491 function sortTokenize ($a, $b)
492 {
493 $aold='';
494 while ($a != $aold)
495 {
496 $aold=$a;
497 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
498 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
499 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
500 }
501
502 $bold='';
503 while ($b != $bold)
504 {
505 $bold=$b;
506 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
507 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
508 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
509 }
510
511
512
513 $ar = explode(' ', $a);
514 $br = explode(' ', $b);
515 for ($i=0; $i<count($ar) && $i<count($br); $i++)
516 {
517 $ret = 0;
518 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
519 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
520 else
521 $ret = strcasecmp($ar[$i], $br[$i]);
522 if ($ret != 0)
523 return $ret;
524 }
525 if ($i<count($ar))
526 return 1;
527 if ($i<count($br))
528 return -1;
529 return 0;
530 }
531
532 function sortByName ($a, $b)
533 {
534 return sortTokenize($a['name'], $b['name']);
535 }
536
537 function sortEmptyPorts ($a, $b)
538 {
539 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
540 if ($objname_cmp == 0)
541 {
542 return sortTokenize($a['Port_name'], $b['Port_name']);
543 }
544 return $objname_cmp;
545 }
546
547 function sortObjectAddressesAndNames ($a, $b)
548 {
549 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
550 if ($objname_cmp == 0)
551 {
552 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
553 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
554 $objname_cmp = sortTokenize($name_a, $name_b);
555 if ($objname_cmp == 0)
556 sortTokenize($a['ip'], $b['ip']);
557 return $objname_cmp;
558 }
559 return $objname_cmp;
560 }
561
562 function sortAddresses ($a, $b)
563 {
564 $name_cmp = sortTokenize($a['name'], $b['name']);
565 if ($name_cmp == 0)
566 {
567 return sortTokenize($a['ip'], $b['ip']);
568 }
569 return $name_cmp;
570 }
571
572 // This function expands port compat list into a matrix.
573 function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
574 {
575 $matrix = array();
576 // Create type matrix and markup compatible types.
577 foreach (array_keys ($portTypeList) as $type1)
578 foreach (array_keys ($portTypeList) as $type2)
579 $matrix[$type1][$type2] = FALSE;
580 foreach ($portCompatList as $pair)
581 $matrix[$pair['type1']][$pair['type2']] = TRUE;
582 return $matrix;
583 }
584
585 // This function returns an array of single element of object's FQDN attribute,
586 // if FQDN is set. The next choice is object's common name, if it looks like a
587 // hostname. Otherwise an array of all 'regular' IP addresses of the
588 // object is returned (which may appear 0 and more elements long).
589 function findAllEndpoints ($object_id, $fallback = '')
590 {
591 $values = getAttrValues ($object_id);
592 foreach ($values as $record)
593 if ($record['name'] == 'FQDN' && !empty ($record['value']))
594 return array ($record['value']);
595 $regular = array();
596 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
597 if ($alloc['type'] == 'regular')
598 $regular[] = $dottedquad;
599 if (!count ($regular) && !empty ($fallback))
600 return array ($fallback);
601 return $regular;
602 }
603
604 // Some records in the dictionary may be written as plain text or as Wiki
605 // link in the following syntax:
606 // 1. word
607 // 2. [[word URL]] // FIXME: this isn't working
608 // 3. [[word word word | URL]]
609 // This function parses the line and returns text suitable for either A
610 // (rendering <A HREF>) or O (for <OPTION>).
611 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
612 {
613 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
614 {
615 if ($strip_optgroup)
616 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
617 else
618 return $line;
619 }
620 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
621 $s = explode ('|', $line);
622 $o_value = trim ($s[0]);
623 if ($strip_optgroup)
624 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
625 $a_value = trim ($s[1]);
626 if ($which == 'a')
627 return "<a href='${a_value}'>${o_value}</a>";
628 if ($which == 'o')
629 return $o_value;
630 }
631
632 function buildVServiceName ($vsinfo = NULL)
633 {
634 if ($vsinfo == NULL)
635 {
636 showError ('NULL argument', __FUNCTION__);
637 return NULL;
638 }
639 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
640 }
641
642 function buildRSPoolName ($rspool = NULL)
643 {
644 if ($rspool == NULL)
645 {
646 showError ('NULL argument', __FUNCTION__);
647 return NULL;
648 }
649 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
650 }
651
652 // rackspace usage for a single rack
653 // (T + W + U) / (height * 3 - A)
654 function getRSUforRack ($data = NULL)
655 {
656 if ($data == NULL)
657 {
658 showError ('Invalid argument', __FUNCTION__);
659 return NULL;
660 }
661 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
662 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
663 for ($locidx = 0; $locidx < 3; $locidx++)
664 $counter[$data[$unit_no][$locidx]['state']]++;
665 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
666 }
667
668 // Same for row.
669 function getRSUforRackRow ($rowData = NULL)
670 {
671 if ($rowData === NULL)
672 {
673 showError ('Invalid argument', __FUNCTION__);
674 return NULL;
675 }
676 if (!count ($rowData))
677 return 0;
678 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
679 $total_height = 0;
680 foreach (array_keys ($rowData) as $rack_id)
681 {
682 $data = getRackData ($rack_id);
683 $total_height += $data['height'];
684 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
685 for ($locidx = 0; $locidx < 3; $locidx++)
686 $counter[$data[$unit_no][$locidx]['state']]++;
687 }
688 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
689 }
690
691 // Return a list of object IDs, which can be found in the given rackspace block.
692 function stuffInRackspace ($rackData)
693 {
694 $objects = array();
695 for ($i = $rackData['height']; $i > 0; $i--)
696 for ($locidx = 0; $locidx < 3; $locidx++)
697 if
698 (
699 $rackData[$i][$locidx]['state'] == 'T' and
700 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
701 )
702 $objects[] = $rackData[$i][$locidx]['object_id'];
703 return $objects;
704 }
705
706 // Make sure the string is always wrapped with LF characters
707 function lf_wrap ($str)
708 {
709 $ret = trim ($str, "\r\n");
710 if (!empty ($ret))
711 $ret .= "\n";
712 return $ret;
713 }
714
715 // Adopted from Mantis BTS code.
716 function string_insert_hrefs ($s)
717 {
718 if (getConfigVar ('DETECT_URLS') != 'yes')
719 return $s;
720 # Find any URL in a string and replace it by a clickable link
721 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
722 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
723 $s);
724 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
725 '<a href="mailto:\0">\0</a>',
726 $s);
727 return $s;
728 }
729
730 // Idem.
731 function email_regex_simple ()
732 {
733 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
734 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
735 }
736
737 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
738 // for the requested object_type_id.
739 function getAutoPorts ($type_id)
740 {
741 $ret = array();
742 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
743 foreach ($typemap as $equation)
744 {
745 $tmp = explode ('=', $equation);
746 if (count ($tmp) != 2)
747 continue;
748 $objtype_id = $tmp[0];
749 if ($objtype_id != $type_id)
750 continue;
751 $portlist = $tmp[1];
752 foreach (explode ('+', $portlist) as $product)
753 {
754 $tmp = explode ('*', $product);
755 if (count ($tmp) != 3)
756 continue;
757 $nports = $tmp[0];
758 $port_type = $tmp[1];
759 $format = $tmp[2];
760 for ($i = 0; $i < $nports; $i++)
761 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
762 }
763 }
764 return $ret;
765 }
766
767 // Find if a particular tag id exists on the tree, then attach the
768 // given child tag to it. If the parent tag doesn't exist, return FALSE.
769 function attachChildTag (&$tree, $parent_id, $child_id, $child_info, $threshold = 0)
770 {
771 $self = __FUNCTION__;
772 foreach (array_keys ($tree) as $tagid)
773 {
774 if ($tagid == $parent_id)
775 {
776 if (!$threshold or ($threshold and $tree[$tagid]['kidc'] + 1 < $threshold))
777 $tree[$tagid]['kids'][$child_id] = $child_info;
778 // Reset the list only once.
779 if (++$tree[$tagid]['kidc'] == $threshold)
780 $tree[$tagid]['kids'] = array();
781 return TRUE;
782 }
783 elseif ($self ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info, $threshold))
784 return TRUE;
785 }
786 return FALSE;
787 }
788
789 // Build a tree from the item list and return it. Input and output data is
790 // indexed by item id (nested items in output are recursively stored in 'kids'
791 // key, which is in turn indexed by id. Functions, which are ready to handle
792 // tree collapsion/expansion themselves, may request non-zero threshold value
793 // for smaller resulting tree.
794 function treeFromList ($mytaglist, $threshold = 0)
795 {
796 $ret = array();
797 while (count ($mytaglist) > 0)
798 {
799 $picked = FALSE;
800 foreach ($mytaglist as $tagid => $taginfo)
801 {
802 $taginfo['kidc'] = 0;
803 $taginfo['kids'] = array();
804 if ($taginfo['parent_id'] == NULL)
805 {
806 $ret[$tagid] = $taginfo;
807 $picked = TRUE;
808 unset ($mytaglist[$tagid]);
809 }
810 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo, $threshold))
811 {
812 $picked = TRUE;
813 unset ($mytaglist[$tagid]);
814 }
815 }
816 if (!$picked) // Only orphaned items on the list.
817 break;
818 }
819 return $ret;
820 }
821
822 // Build a tree from the tag list and return everything _except_ the tree.
823 function getOrphanedTags ()
824 {
825 global $taglist;
826 $mytaglist = $taglist;
827 $dummy = array();
828 while (count ($mytaglist) > 0)
829 {
830 $picked = FALSE;
831 foreach ($mytaglist as $tagid => $taginfo)
832 {
833 $taginfo['kidc'] = 0;
834 $taginfo['kids'] = array();
835 if ($taginfo['parent_id'] == NULL)
836 {
837 $dummy[$tagid] = $taginfo;
838 $picked = TRUE;
839 unset ($mytaglist[$tagid]);
840 }
841 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
842 {
843 $picked = TRUE;
844 unset ($mytaglist[$tagid]);
845 }
846 }
847 if (!$picked) // Only orphaned items on the list.
848 return $mytaglist;
849 }
850 return array();
851 }
852
853 function serializeTags ($chain, $baseurl = '')
854 {
855 $comma = '';
856 $ret = '';
857 foreach ($chain as $taginfo)
858 {
859 $ret .= $comma .
860 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
861 $taginfo['tag'] .
862 ($baseurl == '' ? '' : '</a>');
863 $comma = ', ';
864 }
865 return $ret;
866 }
867
868 // For each tag add all its parent tags onto the list. Don't expect anything
869 // except user's tags on the chain.
870 function getTagChainExpansion ($chain, $tree = NULL)
871 {
872 $self = __FUNCTION__;
873 if ($tree === NULL)
874 {
875 global $tagtree;
876 $tree = $tagtree;
877 }
878 // For each tag find its path from the root, then combine items
879 // of all paths and add them to the chain, if they aren't there yet.
880 $ret = array();
881 foreach ($tree as $taginfo1)
882 {
883 $hit = FALSE;
884 foreach ($chain as $taginfo2)
885 if ($taginfo1['id'] == $taginfo2['id'])
886 {
887 $hit = TRUE;
888 break;
889 }
890 if (count ($taginfo1['kids']) > 0)
891 {
892 $subsearch = $self ($chain, $taginfo1['kids']);
893 if (count ($subsearch))
894 {
895 $hit = TRUE;
896 $ret = array_merge ($ret, $subsearch);
897 }
898 }
899 if ($hit)
900 $ret[] = $taginfo1;
901 }
902 return $ret;
903 }
904
905 // Return the list of missing implicit tags.
906 function getImplicitTags ($oldtags)
907 {
908 $ret = array();
909 $newtags = getTagChainExpansion ($oldtags);
910 foreach ($newtags as $newtag)
911 {
912 $already_exists = FALSE;
913 foreach ($oldtags as $oldtag)
914 if ($newtag['id'] == $oldtag['id'])
915 {
916 $already_exists = TRUE;
917 break;
918 }
919 if ($already_exists)
920 continue;
921 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
922 }
923 return $ret;
924 }
925
926 // Minimize the chain: exclude all implicit tags and return the result.
927 function getExplicitTagsOnly ($chain, $tree = NULL)
928 {
929 $self = __FUNCTION__;
930 global $tagtree;
931 if ($tree === NULL)
932 $tree = $tagtree;
933 $ret = array();
934 foreach ($tree as $taginfo)
935 {
936 if (isset ($taginfo['kids']))
937 {
938 $harvest = $self ($chain, $taginfo['kids']);
939 if (count ($harvest) > 0)
940 {
941 $ret = array_merge ($ret, $harvest);
942 continue;
943 }
944 }
945 // This tag isn't implicit, test is for being explicit.
946 foreach ($chain as $testtag)
947 if ($taginfo['id'] == $testtag['id'])
948 {
949 $ret[] = $testtag;
950 break;
951 }
952 }
953 return $ret;
954 }
955
956 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
957 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
958 // a list of tag structures. Same structure (tag ID list) is returned after processing.
959 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
960 {
961 $self = __FUNCTION__;
962 global $tagtree;
963 if ($tree === NULL)
964 $tree = $tagtree;
965 $getallkids = $getall;
966 $ret = array();
967 foreach ($tree as $taginfo)
968 {
969 foreach ($idlist as $test_id)
970 if ($getall or $taginfo['id'] == $test_id)
971 {
972 $ret[] = $taginfo['id'];
973 // Once matched node makes all sub-nodes match, but don't make
974 // a mistake of matching every other node at the current level.
975 $getallkids = TRUE;
976 break;
977 }
978 if (isset ($taginfo['kids']))
979 $ret = array_merge ($ret, $self ($idlist, $taginfo['kids'], $getallkids));
980 $getallkids = FALSE;
981 }
982 return $ret;
983 }
984
985 function getUserAutoTags ($username = NULL)
986 {
987 global $remote_username, $accounts;
988 if ($username == NULL)
989 $username = $remote_username;
990 $ret = array();
991 $ret[] = array ('tag' => '$username_' . $username);
992 if (isset ($accounts[$username]['user_id']))
993 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
994 return $ret;
995 }
996
997 function loadRackObjectAutoTags ()
998 {
999 assertUIntArg ('object_id', __FUNCTION__);
1000 $object_id = $_REQUEST['object_id'];
1001 $oinfo = getObjectInfo ($object_id);
1002 $ret = array();
1003 $ret[] = array ('tag' => '$id_' . $object_id);
1004 $ret[] = array ('tag' => '$typeid_' . $oinfo['objtype_id']);
1005 $ret[] = array ('tag' => '$any_object');
1006 if (validTagName ($oinfo['name']))
1007 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
1008 return $ret;
1009 }
1010
1011 // Common code for both prefix and address tag listers.
1012 function loadFileAutoTags ()
1013 {
1014 assertUIntArg ('file_id', __FUNCTION__);
1015 $ret = array();
1016 $ret[] = array ('tag' => '$fileid_' . $_REQUEST['file_id']);
1017 $ret[] = array ('tag' => '$any_file');
1018 return $ret;
1019 }
1020
1021 function getIPv4PrefixTags ($netid)
1022 {
1023 $netinfo = getIPv4NetworkInfo ($netid);
1024 $ret = array();
1025 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $netinfo['ip']) . '-' . $netinfo['mask']);
1026 // FIXME: find and list tags for all parent networks?
1027 $ret[] = array ('tag' => '$any_ip4net');
1028 $ret[] = array ('tag' => '$any_net');
1029 return $ret;
1030 }
1031
1032 function loadIPv4PrefixAutoTags ()
1033 {
1034 assertUIntArg ('id', __FUNCTION__);
1035 return array_merge
1036 (
1037 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
1038 getIPv4PrefixTags ($_REQUEST['id'])
1039 );
1040 }
1041
1042 function loadIPv4AddressAutoTags ()
1043 {
1044 assertIPv4Arg ('ip', __FUNCTION__);
1045 return array_merge
1046 (
1047 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
1048 getIPv4PrefixTags (getIPv4AddressNetworkId ($_REQUEST['ip']))
1049 );
1050 }
1051
1052 function loadRackAutoTags ()
1053 {
1054 assertUIntArg ('rack_id', __FUNCTION__);
1055 $ret = array();
1056 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
1057 $ret[] = array ('tag' => '$any_rack');
1058 return $ret;
1059 }
1060
1061 function loadIPv4VSAutoTags ()
1062 {
1063 assertUIntArg ('vs_id', __FUNCTION__);
1064 $ret = array();
1065 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
1066 $ret[] = array ('tag' => '$any_ipv4vs');
1067 $ret[] = array ('tag' => '$any_vs');
1068 return $ret;
1069 }
1070
1071 function loadIPv4RSPoolAutoTags ()
1072 {
1073 assertUIntArg ('pool_id', __FUNCTION__);
1074 $ret = array();
1075 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1076 $ret[] = array ('tag' => '$any_ipv4rsp');
1077 $ret[] = array ('tag' => '$any_rsp');
1078 return $ret;
1079 }
1080
1081 // Check, if the given tag is present on the chain (will only work
1082 // for regular tags with tag ID set.
1083 function tagOnChain ($taginfo, $tagchain)
1084 {
1085 if (!isset ($taginfo['id']))
1086 return FALSE;
1087 foreach ($tagchain as $test)
1088 if ($test['id'] == $taginfo['id'])
1089 return TRUE;
1090 return FALSE;
1091 }
1092
1093 // Idem, but use ID list instead of chain.
1094 function tagOnIdList ($taginfo, $tagidlist)
1095 {
1096 if (!isset ($taginfo['id']))
1097 return FALSE;
1098 foreach ($tagidlist as $tagid)
1099 if ($taginfo['id'] == $tagid)
1100 return TRUE;
1101 return FALSE;
1102 }
1103
1104 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1105 // Assume, that neither of the lists contains duplicates.
1106 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1107 function tagChainCmp ($chain1, $chain2)
1108 {
1109 if (count ($chain1) != count ($chain2))
1110 return TRUE;
1111 foreach ($chain1 as $taginfo1)
1112 if (!tagOnChain ($taginfo1, $chain2))
1113 return TRUE;
1114 return FALSE;
1115 }
1116
1117 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1118 // hold all appropriate (explicit and implicit) tags respectively.
1119 // Otherwise some limited redirection is necessary (only page and tab
1120 // names are preserved, ophandler name change isn't handled).
1121 function fixContext ()
1122 {
1123 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
1124
1125 $pmap = array
1126 (
1127 'accounts' => 'userlist',
1128 'rspools' => 'ipv4rsplist',
1129 'rspool' => 'ipv4rsp',
1130 'vservices' => 'ipv4vslist',
1131 'vservice' => 'ipv4vs',
1132 );
1133 $tmap = array();
1134 $tmap['objects']['newmulti'] = 'addmore';
1135 $tmap['objects']['newobj'] = 'addmore';
1136 $tmap['object']['switchvlans'] = 'livevlans';
1137 $tmap['object']['slb'] = 'editrspvs';
1138 $tmap['object']['portfwrd'] = 'nat4';
1139 $tmap['object']['network'] = 'ipv4';
1140 if (isset ($pmap[$pageno]))
1141 redirectUser ($pmap[$pageno], $tabno);
1142 if (isset ($tmap[$pageno][$tabno]))
1143 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1144
1145 if (isset ($page[$pageno]['autotagloader']))
1146 $auto_tags = $page[$pageno]['autotagloader'] ();
1147 if
1148 (
1149 isset ($page[$pageno]['tagloader']) and
1150 isset ($page[$pageno]['bypass']) and
1151 isset ($_REQUEST[$page[$pageno]['bypass']])
1152 )
1153 {
1154 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1155 $impl_tags = getImplicitTags ($expl_tags);
1156 }
1157 }
1158
1159 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1160 // records indexed by tag IDs (tag chain).
1161 function buildTagChainFromIds ($tagidlist)
1162 {
1163 global $taglist;
1164 $ret = array();
1165 foreach (array_unique ($tagidlist) as $tag_id)
1166 if (isset ($taglist[$tag_id]))
1167 $ret[] = $taglist[$tag_id];
1168 return $ret;
1169 }
1170
1171 // Process a given tag tree and return only meaningful branches. The resulting
1172 // (sub)tree will have refcnt leaves on every last branch.
1173 function getObjectiveTagTree ($tree, $realm)
1174 {
1175 $self = __FUNCTION__;
1176 $ret = array();
1177 foreach ($tree as $taginfo)
1178 {
1179 $subsearch = array();
1180 $pick = FALSE;
1181 if (count ($taginfo['kids']))
1182 {
1183 $subsearch = $self ($taginfo['kids'], $realm);
1184 $pick = count ($subsearch) > 0;
1185 }
1186 if (isset ($taginfo['refcnt'][$realm]))
1187 $pick = TRUE;
1188 if (!$pick)
1189 continue;
1190 $ret[] = array
1191 (
1192 'id' => $taginfo['id'],
1193 'tag' => $taginfo['tag'],
1194 'parent_id' => $taginfo['parent_id'],
1195 'refcnt' => $taginfo['refcnt'],
1196 'kids' => $subsearch
1197 );
1198 }
1199 return $ret;
1200 }
1201
1202 function getTagFilter ()
1203 {
1204 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
1205 }
1206
1207 function getTagFilterStr ($tagfilter = array())
1208 {
1209 $ret = '';
1210 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
1211 $ret .= "&tagfilter[]=" . $taginfo['id'];
1212 return $ret;
1213 }
1214
1215 function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
1216 {
1217 global $root, $page, $pageno, $tabno;
1218 if ($nextpage === NULL)
1219 $nextpage = $pageno;
1220 if ($nexttab === NULL)
1221 $nexttab = $tabno;
1222 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1223 if (isset ($page[$nextpage]['bypass']))
1224 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
1225 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
1226 return $url;
1227 }
1228
1229 function buildRedirectURL ($callfunc, $status, $args = array(), $nextpage = NULL, $nexttab = NULL)
1230 {
1231 global $pageno, $tabno;
1232 if ($nextpage === NULL)
1233 $nextpage = $pageno;
1234 if ($nexttab === NULL)
1235 $nexttab = $tabno;
1236 return buildWideRedirectURL (oneLiner (getMessageCode ($callfunc, $status), $args), $nextpage, $nexttab);
1237 }
1238
1239 // Return a message log consisting of only one message.
1240 function oneLiner ($code, $args = array())
1241 {
1242 $ret = array ('v' => 2);
1243 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1244 return $ret;
1245 }
1246
1247 // Return mesage code by status code.
1248 function getMessageCode ($callfunc, $status)
1249 {
1250 global $msgcode;
1251 return $msgcode[$callfunc][$status];
1252 }
1253
1254 function validTagName ($s, $allow_autotag = FALSE)
1255 {
1256 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1257 return TRUE;
1258 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1259 return TRUE;
1260 return FALSE;
1261 }
1262
1263 function redirectUser ($p, $t)
1264 {
1265 global $page, $root;
1266 $l = "{$root}?page=${p}&tab=${t}";
1267 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1268 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1269 header ("Location: " . $l);
1270 die;
1271 }
1272
1273 function getRackCodeStats ()
1274 {
1275 global $rackCode;
1276 $defc = $grantc = 0;
1277 foreach ($rackCode as $s)
1278 switch ($s['type'])
1279 {
1280 case 'SYNT_DEFINITION':
1281 $defc++;
1282 break;
1283 case 'SYNT_GRANT':
1284 $grantc++;
1285 break;
1286 default:
1287 break;
1288 }
1289 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1290 return $ret;
1291 }
1292
1293 function getRackImageWidth ()
1294 {
1295 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1296 }
1297
1298 function getRackImageHeight ($units)
1299 {
1300 return 3 + 3 + $units * 2;
1301 }
1302
1303 // Perform substitutions and return resulting string
1304 // used solely by buildLVSConfig()
1305 function apply_macros ($macros, $subject)
1306 {
1307 $ret = $subject;
1308 foreach ($macros as $search => $replace)
1309 $ret = str_replace ($search, $replace, $ret);
1310 return $ret;
1311 }
1312
1313 function buildLVSConfig ($object_id = 0)
1314 {
1315 if ($object_id <= 0)
1316 {
1317 showError ('Invalid argument', __FUNCTION__);
1318 return;
1319 }
1320 $oInfo = getObjectInfo ($object_id);
1321 $lbconfig = getSLBConfig ($object_id);
1322 if ($lbconfig === NULL)
1323 {
1324 showError ('getSLBConfig() failed', __FUNCTION__);
1325 return;
1326 }
1327 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1328 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1329 foreach ($lbconfig as $vs_id => $vsinfo)
1330 {
1331 $newconfig .= "########################################################\n" .
1332 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1333 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1334 "########################################################\n";
1335 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1336 $macros = array
1337 (
1338 '%VIP%' => $vsinfo['vip'],
1339 '%VPORT%' => $vsinfo['vport'],
1340 '%PROTO%' => $vsinfo['proto'],
1341 '%VNAME%' => $vsinfo['vs_name'],
1342 '%RSPOOLNAME%' => $vsinfo['pool_name']
1343 );
1344 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1345 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1346 $newconfig .= apply_macros
1347 (
1348 $macros,
1349 lf_wrap ($vsinfo['vs_vsconfig']) .
1350 lf_wrap ($vsinfo['lb_vsconfig']) .
1351 lf_wrap ($vsinfo['pool_vsconfig'])
1352 );
1353 foreach ($vsinfo['rslist'] as $rs)
1354 {
1355 if (empty ($rs['rsport']))
1356 $rs['rsport'] = $vsinfo['vport'];
1357 $macros['%RSIP%'] = $rs['rsip'];
1358 $macros['%RSPORT%'] = $rs['rsport'];
1359 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1360 $newconfig .= apply_macros
1361 (
1362 $macros,
1363 lf_wrap ($vsinfo['vs_rsconfig']) .
1364 lf_wrap ($vsinfo['lb_rsconfig']) .
1365 lf_wrap ($vsinfo['pool_rsconfig']) .
1366 lf_wrap ($rs['rs_rsconfig'])
1367 );
1368 $newconfig .= "\t}\n";
1369 }
1370 $newconfig .= "}\n\n\n";
1371 }
1372 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1373 return str_replace ("\r", '', $newconfig);
1374 }
1375
1376 // Indicate occupation state of each IP address: none, ordinary or problematic.
1377 function markupIPv4AddrList (&$addrlist)
1378 {
1379 foreach (array_keys ($addrlist) as $ip_bin)
1380 {
1381 $refc = array
1382 (
1383 'shared' => 0, // virtual
1384 'virtual' => 0, // loopback
1385 'regular' => 0, // connected host
1386 'router' => 0 // connected gateway
1387 );
1388 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1389 $refc[$a['type']]++;
1390 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
1391 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1392 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
1393
1394 if ($nrealms == 1)
1395 $addrlist[$ip_bin]['class'] = 'trbusy';
1396 elseif ($nrealms > 1)
1397 $addrlist[$ip_bin]['class'] = 'trerror';
1398 else
1399 $addrlist[$ip_bin]['class'] = '';
1400 }
1401 }
1402
1403 // Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1404 function findRouters ($addrlist)
1405 {
1406 $ret = array();
1407 foreach ($addrlist as $addr)
1408 foreach ($addr['allocs'] as $alloc)
1409 if ($alloc['type'] == 'router')
1410 $ret[] = array
1411 (
1412 'id' => $alloc['object_id'],
1413 'iface' => $alloc['name'],
1414 'dname' => $alloc['object_name'],
1415 'addr' => $addr['ip']
1416 );
1417 return $ret;
1418 }
1419
1420 // Assist in tag chain sorting.
1421 function taginfoCmp ($tagA, $tagB)
1422 {
1423 return $tagA['ci'] - $tagB['ci'];
1424 }
1425
1426 // Compare networks. When sorting a tree, the records on the list will have
1427 // distinct base IP addresses.
1428 // "The comparison function must return an integer less than, equal to, or greater
1429 // than zero if the first argument is considered to be respectively less than,
1430 // equal to, or greater than the second." (c) PHP manual
1431 function IPv4NetworkCmp ($netA, $netB)
1432 {
1433 // There's a problem just substracting one u32 integer from another,
1434 // because the result may happen big enough to become a negative i32
1435 // integer itself (PHP tries to cast everything it sees to signed int)
1436 // The comparison below must treat positive and negative values of both
1437 // arguments.
1438 // Equal values give instant decision regardless of their [equal] sign.
1439 if ($netA['ip_bin'] == $netB['ip_bin'])
1440 return 0;
1441 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1442 // 0x00000001~0x7fffffff 1~2147483647
1443 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1444 // 0x80000000~0xffffffff -2147483648~-1
1445 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1446 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1447 if ($signA == $signB)
1448 {
1449 if ($netA['ip_bin'] > $netB['ip_bin'])
1450 return 1;
1451 else
1452 return -1;
1453 }
1454 else // With only one of two values being negative, it... wins!
1455 {
1456 if ($netA['ip_bin'] < $netB['ip_bin'])
1457 return 1;
1458 else
1459 return -1;
1460 }
1461 }
1462
1463 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1464 function sortTree (&$tree, $sortfunc = '')
1465 {
1466 if (empty ($sortfunc))
1467 return;
1468 $self = __FUNCTION__;
1469 usort ($tree, $sortfunc);
1470 // Don't make a mistake of directly iterating over the items of current level, because this way
1471 // the sorting will be performed on a _copy_ if each item, not the item itself.
1472 foreach (array_keys ($tree) as $tagid)
1473 $self ($tree[$tagid]['kids'], $sortfunc);
1474 }
1475
1476 function iptree_fill (&$netdata)
1477 {
1478 if (!isset ($netdata['kids']) or empty ($netdata['kids']))
1479 return;
1480 // If we really have nested prefixes, they must fit into the tree.
1481 $worktree = array
1482 (
1483 'ip_bin' => $netdata['ip_bin'],
1484 'mask' => $netdata['mask']
1485 );
1486 foreach ($netdata['kids'] as $pfx)
1487 iptree_embed ($worktree, $pfx);
1488 $netdata['kids'] = iptree_construct ($worktree);
1489 $netdata['kidc'] = count ($netdata['kids']);
1490 }
1491
1492 function iptree_construct ($node)
1493 {
1494 $self = __FUNCTION__;
1495
1496 if (!isset ($node['right']))
1497 {
1498 if (!isset ($node['ip']))
1499 {
1500 $node['ip'] = long2ip ($node['ip_bin']);
1501 $node['kids'] = array();
1502 $node['kidc'] = 0;
1503 $node['name'] = '';
1504 }
1505 return array ($node);
1506 }
1507 else
1508 return array_merge ($self ($node['left']), $self ($node['right']));
1509 }
1510
1511 function iptree_embed (&$node, $pfx)
1512 {
1513 $self = __FUNCTION__;
1514
1515 // hit?
1516 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1517 {
1518 $node = $pfx;
1519 return;
1520 }
1521 if ($node['mask'] == $pfx['mask'])
1522 {
1523 showError ('Internal error, the recurring loop lost control', __FUNCTION__);
1524 die;
1525 }
1526
1527 // split?
1528 if (!isset ($node['right']))
1529 {
1530 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
1531 $node['left']['mask'] = $node['mask'] + 1;
1532 $node['left']['ip_bin'] = $node['ip_bin'];
1533 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
1534 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] | binInvMaskFromDec ($node['left']['mask']));
1535
1536 $node['right']['mask'] = $node['mask'] + 1;
1537 $node['right']['ip_bin'] = $node['ip_bin'] + binInvMaskFromDec ($node['mask'] + 1) + 1;
1538 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
1539 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] | binInvMaskFromDec ($node['right']['mask']));
1540 }
1541
1542 // repeat!
1543 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1544 $self ($node['left'], $pfx);
1545 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1546 $self ($node['right'], $pfx);
1547 else
1548 {
1549 showError ('Internal error, cannot decide between left and right', __FUNCTION__);
1550 die;
1551 }
1552 }
1553
1554 function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
1555 {
1556 if (empty ($func))
1557 return;
1558 $self = __FUNCTION__;
1559 foreach (array_keys ($tree) as $key)
1560 {
1561 $func ($tree[$key]);
1562 if (!empty ($stopfunc) and $stopfunc ($tree[$key]))
1563 continue;
1564 $self ($tree[$key]['kids'], $func);
1565 }
1566 }
1567
1568 function loadIPv4AddrList (&$netinfo)
1569 {
1570 loadOwnIPv4Addresses ($netinfo);
1571 markupIPv4AddrList ($netinfo['addrlist']);
1572 }
1573
1574 function countOwnIPv4Addresses (&$node)
1575 {
1576 $toscan = array();
1577 $node['addrt'] = 0;
1578 $node['mask_bin'] = binMaskFromDec ($node['mask']);
1579 $node['mask_bin_inv'] = binInvMaskFromDec ($node['mask']);
1580 $node['db_first'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] & $node['mask_bin']);
1581 $node['db_last'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] | ($node['mask_bin_inv']));
1582 if (empty ($node['kids']))
1583 {
1584 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1585 $node['addrt'] = binInvMaskFromDec ($node['mask']) + 1;
1586 }
1587 else
1588 foreach ($node['kids'] as $nested)
1589 if (!isset ($nested['id'])) // spare
1590 {
1591 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1592 $node['addrt'] += binInvMaskFromDec ($nested['mask']) + 1;
1593 }
1594 // Don't do anything more, because the displaying function will load the addresses anyway.
1595 return;
1596 $node['addrc'] = count (scanIPv4Space ($toscan));
1597 }
1598
1599 function nodeIsCollapsed ($node)
1600 {
1601 return $node['symbol'] == 'node-collapsed';
1602 }
1603
1604 function loadOwnIPv4Addresses (&$node)
1605 {
1606 $toscan = array();
1607 if (empty ($node['kids']))
1608 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1609 else
1610 foreach ($node['kids'] as $nested)
1611 if (!isset ($nested['id'])) // spare
1612 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1613 $node['addrlist'] = scanIPv4Space ($toscan);
1614 $node['addrc'] = count ($node['addrlist']);
1615 }
1616
1617 function prepareIPv4Tree ($netlist, $expanded_id = 0)
1618 {
1619 $tree = treeFromList ($netlist); // medium call
1620 sortTree ($tree, 'IPv4NetworkCmp');
1621 // complement the tree before markup to make the spare networks have "symbol" set
1622 treeApplyFunc ($tree, 'iptree_fill');
1623 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
1624 // count addresses after the markup to skip computation for hidden tree nodes
1625 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
1626 return $tree;
1627 }
1628
1629 // Check all items of the tree recursively, until the requested target id is
1630 // found. Mark all items leading to this item as "expanded", collapsing all
1631 // the rest, which exceed the given threshold (if the threshold is given).
1632 function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
1633 {
1634 $self = __FUNCTION__;
1635 $ret = FALSE;
1636 foreach (array_keys ($tree) as $key)
1637 {
1638 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
1639 $below = $self ($tree[$key]['kids'], $threshold, $target);
1640 if (!$tree[$key]['kidc']) // terminal node
1641 $tree[$key]['symbol'] = 'spacer';
1642 elseif ($tree[$key]['kidc'] < $threshold)
1643 $tree[$key]['symbol'] = 'node-expanded-static';
1644 elseif ($here or $below)
1645 $tree[$key]['symbol'] = 'node-expanded';
1646 else
1647 $tree[$key]['symbol'] = 'node-collapsed';
1648 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
1649 }
1650 return $ret;
1651 }
1652
1653 // Get a tree and target entity ID on it. Return the list of IDs, which make the path
1654 // from the target entity to tree root. If such a path exists, it will consist of at
1655 // least the target ID. Otherwise an empty list will be returned. The "list" is a randomly
1656 // indexed array of values.
1657 function traceEntity ($tree, $target_id)
1658 {
1659 $self = __FUNCTION__;
1660 foreach ($tree as $node)
1661 {
1662 if ($node['id'] == $target_id) // here!
1663 return array ($target_id);
1664 $subtrace = $self ($node['kids'], $target_id); // below?
1665 if (count ($subtrace))
1666 {
1667 array_push ($subtrace, $node['id']);
1668 return $subtrace;
1669 }
1670 // next...
1671 }
1672 return array();
1673 }
1674
1675 // Convert entity name to human-readable value
1676 function formatEntityName ($name) {
1677 switch ($name)
1678 {
1679 case 'ipv4net':
1680 return 'IPv4 Network';
1681 case 'ipv4rspool':
1682 return 'IPv4 RS Pool';
1683 case 'ipv4vs':
1684 return 'IPv4 Virtual Service';
1685 case 'object':
1686 return 'Object';
1687 case 'rack':
1688 return 'Rack';
1689 case 'user':
1690 return 'User';
1691 }
1692 return 'invalid';
1693 }
1694
1695 // Take a MySQL or other generic timestamp and make it prettier
1696 function formatTimestamp ($timestamp) {
1697 return date('n/j/y g:iA', strtotime($timestamp));
1698 }
1699
1700 // Display hrefs for all of a file's parents
1701 function serializeFileLinks ($links)
1702 {
1703 global $root;
1704
1705 $comma = '';
1706 $ret = '';
1707 foreach ($links as $link_id => $li)
1708 {
1709 switch ($li['entity_type'])
1710 {
1711 case 'ipv4net':
1712 $params = "page=ipv4net&id=";
1713 break;
1714 case 'ipv4rspool':
1715 $params = "page=ipv4rspool&pool_id=";
1716 break;
1717 case 'ipv4vs':
1718 $params = "page=ipv4vs&vs_id=";
1719 break;
1720 case 'object':
1721 $params = "page=object&object_id=";
1722 break;
1723 case 'rack':
1724 $params = "page=rack&rack_id=";
1725 break;
1726 case 'user':
1727 $params = "page=user&user_id=";
1728 break;
1729 }
1730 $ret .= sprintf("%s<a href='%s?%s%s'>%s</a>", $comma, $root, $params, $li['entity_id'], $li['name']);
1731 $comma = ', ';
1732 }
1733
1734 return $ret;
1735 }
1736
1737 // Convert filesize to appropriate unit and make it human-readable
1738 function formatFileSize ($bytes) {
1739 // bytes
1740 if($bytes < 1024) // bytes
1741 return "${bytes} bytes";
1742
1743 // kilobytes
1744 if ($bytes < 1024000)
1745 return sprintf ("%.1fk", round (($bytes / 1024), 1));
1746
1747 // megabytes
1748 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
1749 }
1750
1751 // Reverse of formatFileSize, it converts human-readable value to bytes
1752 function convertToBytes ($value) {
1753 $value = trim($value);
1754 $last = strtolower($value[strlen($value)-1]);
1755 switch ($last)
1756 {
1757 case 'g':
1758 $value *= 1024;
1759 case 'm':
1760 $value *= 1024;
1761 case 'k':
1762 $value *= 1024;
1763 }
1764
1765 return $value;
1766 }
1767
1768 ?>