4 * This file is a library of computational functions for RackTables.
9 $loclist[1] = 'interior';
11 $loclist['front'] = 0;
12 $loclist['interior'] = 1;
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;
27 define ('CHAP_OBJTYPE', 1);
28 define ('CHAP_PORTTYPE', 2);
29 define ('TAGNAME_REGEXP', '/^[\p{L}0-9]([. _~-]?[\p{L}0-9])*$/u');
30 define ('AUTOTAGNAME_REGEXP', '/^\$[\p{L}0-9]([. _~-]?[\p{L}0-9])*$/u');
31 // The latter matches both SunOS and Linux-styled formats.
32 define ('RE_L2_IFCFG', '/^[0-9a-f]{1,2}(:[0-9a-f]{1,2}){5}$/i');
33 define ('RE_L2_CISCO', '/^[0-9a-f]{4}(\.[0-9a-f]{4}){2}$/i');
34 define ('RE_L2_HUAWEI', '/^[0-9a-f]{4}(-[0-9a-f]{4}){2}$/i');
35 define ('RE_L2_SOLID', '/^[0-9a-f]{12}$/i');
36 define ('RE_L2_IPCFG', '/^[0-9a-f]{2}(-[0-9a-f]{2}){5}$/i');
37 define ('RE_L2_WWN_COLON', '/^[0-9a-f]{1,2}(:[0-9a-f]{1,2}){7}$/i');
38 define ('RE_L2_WWN_HYPHEN', '/^[0-9a-f]{2}(-[0-9a-f]{2}){7}$/i');
39 define ('RE_L2_WWN_SOLID', '/^[0-9a-f]{16}$/i');
40 define ('RE_IP4_ADDR', '#^[0-9]{1,3}(\.[0-9]{1,3}){3}$#');
41 define ('RE_IP4_NET', '#^[0-9]{1,3}(\.[0-9]{1,3}){3}/[0-9]{1,2}$#');
42 define ('E_8021Q_NOERROR', 0);
43 define ('E_8021Q_VERSION_CONFLICT', 101);
44 define ('E_8021Q_PULL_REMOTE_ERROR', 102);
45 define ('E_8021Q_PUSH_REMOTE_ERROR', 103);
46 define ('E_8021Q_SYNC_DISABLED', 104);
47 define ('VLAN_MIN_ID', 1);
48 define ('VLAN_MAX_ID', 4094);
49 define ('VLAN_DFL_ID', 1);
50 define ('TAB_REMEMBER_TIMEOUT', 300);
52 // Entity type by page number mapping is 1:1 atm, but may change later.
53 $etype_by_pageno = array
55 'ipv4net' => 'ipv4net',
56 'ipv6net' => 'ipv6net',
57 'ipv4rspool' => 'ipv4rspool',
65 // Rack thumbnail image width summands: "front", "interior" and "rear" elements w/o surrounding border.
73 $virtual_obj_types = array
83 32 => '255.255.255.255',
84 31 => '255.255.255.254',
85 30 => '255.255.255.252',
86 29 => '255.255.255.248',
87 28 => '255.255.255.240',
88 27 => '255.255.255.224',
89 26 => '255.255.255.192',
90 25 => '255.255.255.128',
91 24 => '255.255.255.0',
92 23 => '255.255.254.0',
93 22 => '255.255.252.0',
94 21 => '255.255.248.0',
95 20 => '255.255.240.0',
96 19 => '255.255.224.0',
97 18 => '255.255.192.0',
98 17 => '255.255.128.0',
117 $wildcardbylen = array
139 12 => '0.15.255.255',
140 11 => '0.31.255.255',
141 10 => '0.63.255.255',
142 9 => '0.127.255.255',
143 8 => '0.255.255.255',
144 7 => '1.255.255.255',
145 6 => '3.255.255.255',
146 5 => '7.255.255.255',
147 4 => '15.255.255.255',
148 3 => '31.255.255.255',
149 2 => '63.255.255.255',
150 1 => '127.255.255.255'
155 '255.255.255.255' => 32,
156 '255.255.255.254' => 31,
157 '255.255.255.252' => 30,
158 '255.255.255.248' => 29,
159 '255.255.255.240' => 28,
160 '255.255.255.224' => 27,
161 '255.255.255.192' => 26,
162 '255.255.255.128' => 25,
163 '255.255.255.0' => 24,
164 '255.255.254.0' => 23,
165 '255.255.252.0' => 22,
166 '255.255.248.0' => 21,
167 '255.255.240.0' => 20,
168 '255.255.224.0' => 19,
169 '255.255.192.0' => 18,
170 '255.255.128.0' => 17,
190 // 802.1Q deploy queue titles
193 'sync_aging' => 'Normal, aging',
194 'resync_aging' => 'Version conflict, aging',
195 'sync_ready' => 'Normal, ready for sync',
196 'resync_ready' => 'Version conflict, ready for retry',
197 'failed' => 'Failed',
198 'disabled' => 'Sync disabled',
199 'done' => 'Up to date',
202 // This function assures that specified argument was passed
203 // and is a number greater than zero.
204 function assertUIntArg ($argname, $allow_zero = FALSE)
206 if (!isset ($_REQUEST[$argname]))
207 throw new InvalidRequestArgException($argname, '', 'parameter is missing');
208 if (!is_numeric ($_REQUEST[$argname]))
209 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a number');
210 if ($_REQUEST[$argname] < 0)
211 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is less than zero');
212 if (!$allow_zero and $_REQUEST[$argname] == 0)
213 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is zero');
216 function isInteger ($arg, $allow_zero = FALSE)
218 if (! is_numeric ($arg))
220 if (! $allow_zero and ! $arg)
225 // This function assures that specified argument was passed
226 // and is a non-empty string.
227 function assertStringArg ($argname, $ok_if_empty = FALSE)
229 if (!isset ($_REQUEST[$argname]))
230 throw new InvalidRequestArgException($argname, '', 'parameter is missing');
231 if (!is_string ($_REQUEST[$argname]))
232 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a string');
233 if (!$ok_if_empty and !strlen ($_REQUEST[$argname]))
234 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is an empty string');
237 function assertBoolArg ($argname, $ok_if_empty = FALSE)
239 if (!isset ($_REQUEST[$argname]))
240 throw new InvalidRequestArgException($argname, '', 'parameter is missing');
241 if (!is_string ($_REQUEST[$argname]) or $_REQUEST[$argname] != 'on')
242 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a string');
243 if (!$ok_if_empty and !strlen ($_REQUEST[$argname]))
244 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is an empty string');
247 // function returns IPv6Address object, null if arg is correct IPv4, or throws an exception
248 function assertIPArg ($argname, $ok_if_empty = FALSE)
250 assertStringArg ($argname, $ok_if_empty);
251 $ip = $_REQUEST[$argname];
252 if (FALSE !== strpos ($ip, ':'))
254 $v6address = new IPv6Address
;
255 $result = $v6address->parse ($ip);
260 $result = long2ip (ip2long ($ip)) === $ip;
264 throw new InvalidRequestArgException ($argname, $ip, 'parameter is not a valid IPv4 or IPv6 address');
268 function assertIPv4Arg ($argname, $ok_if_empty = FALSE)
270 assertStringArg ($argname, $ok_if_empty);
271 if (strlen ($_REQUEST[$argname]) and long2ip (ip2long ($_REQUEST[$argname])) !== $_REQUEST[$argname])
272 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a valid ipv4 address');
275 // function returns IPv6Address object, or throws an exception
276 function assertIPv6Arg ($argname, $ok_if_empty = FALSE)
278 assertStringArg ($argname, $ok_if_empty);
279 $ipv6 = new IPv6Address
;
280 if (strlen ($_REQUEST[$argname]) and ! $ok_if_empty and ! $ipv6->parse ($_REQUEST[$argname]))
281 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a valid ipv6 address');
285 function assertPCREArg ($argname)
287 assertStringArg ($argname, TRUE); // empty pattern is Ok
288 if (FALSE === preg_match ($_REQUEST[$argname], 'test'))
289 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'PCRE validation failed');
292 function isPCRE ($arg)
294 if (! isset ($arg) or FALSE === preg_match ($arg, 'test'))
299 function genericAssertion ($argname, $argtype)
305 assertStringArg ($argname);
308 assertStringArg ($argname, TRUE);
311 assertUIntArg ($argname);
314 assertUIntArg ($argname, TRUE);
317 assertIPv4Arg ($argname);
320 assertIPv6Arg ($argname);
323 assertStringArg ($argname);
325 assertStringArg ($argname, TRUE);
328 l2addressForDatabase ($sic[$argname]);
330 catch (InvalidArgException
$e)
332 throw new InvalidRequestArgException ($argname, $sic[$argname], 'malformed MAC/WWN address');
336 assertStringArg ($argname);
337 if (!validTagName ($sic[$argname]))
338 throw new InvalidRequestArgException ($argname, $sic[$argname], 'Invalid tag name');
341 assertPCREArg ($argname);
344 assertStringArg ($argname);
345 if (NULL === json_decode ($sic[$argname], TRUE))
346 throw new InvalidRequestArgException ($argname, '(omitted)', 'Invalid JSON code received from client');
349 if (! array_key_exists ($argname, $_REQUEST))
350 throw new InvalidRequestArgException ($argname, '(missing argument)');
351 if (! is_array ($_REQUEST[$argname]))
352 throw new InvalidRequestArgException ($argname, '(omitted)', 'argument is not an array');
354 case 'enum/attr_type':
355 assertStringArg ($argname);
356 if (!in_array ($sic[$argname], array ('uint', 'float', 'string', 'dict')))
357 throw new InvalidRequestArgException ($argname, $sic[$argname], 'Unknown value');
359 case 'enum/vlan_type':
360 assertStringArg ($argname);
361 // "Alien" type is not valid until the logic is fixed to implement it in full.
362 if (!in_array ($sic[$argname], array ('ondemand', 'compulsory')))
363 throw new InvalidRequestArgException ($argname, $sic[$argname], 'Unknown value');
366 assertStringArg ($argname);
367 global $ifcompatpack;
368 if (!array_key_exists ($sic[$argname], $ifcompatpack))
369 throw new InvalidRequestArgException ($argname, $sic[$argname], 'Unknown value');
372 assertStringArg ($argname);
373 if (!in_array ($sic[$argname], array ('TCP', 'UDP')))
374 throw new InvalidRequestArgException ($argname, $sic[$argname], 'Unknown value');
376 case 'enum/inet4alloc':
377 case 'enum/inet6alloc':
378 assertStringArg ($argname);
379 if (!in_array ($sic[$argname], array ('regular', 'shared', 'virtual', 'router')))
380 throw new InvalidRequestArgException ($argname, $sic[$argname], 'Unknown value');
383 if (!array_key_exists ($sic[$argname], getPortIIFOptions()))
384 throw new InvalidRequestArgException ($argname, $sic[$argname], 'Unknown value');
387 throw new InvalidArgException ('argtype', $argtype); // comes not from user's input
391 // Validate and return "bypass" value for the current context, if one is
392 // defined for it, or NULL otherwise.
393 function getBypassValue()
395 global $page, $pageno, $sic;
396 if (!array_key_exists ('bypass', $page[$pageno]))
398 if (!array_key_exists ('bypass_type', $page[$pageno]))
399 throw new RackTablesError ("Internal structure error at node '${pageno}' (bypass_type is not set)", RackTablesError
::INTERNAL
);
400 genericAssertion ($page[$pageno]['bypass'], $page[$pageno]['bypass_type']);
401 return $sic[$page[$pageno]['bypass']];
404 // Objects of some types should be explicitly shown as
405 // anonymous (labelless). This function is a single place where the
406 // decision about displayed name is made.
407 function setDisplayedName (&$cell)
409 if ($cell['name'] != '')
410 $cell['dname'] = $cell['name'];
413 $cell['atags'][] = array ('tag' => '$nameless');
414 if (considerConfiguredConstraint ($cell, 'NAMEWARN_LISTSRC'))
415 $cell['dname'] = 'ANONYMOUS ' . decodeObjectType ($cell['objtype_id'], 'o');
417 $cell['dname'] = '[' . decodeObjectType ($cell['objtype_id'], 'o') . ']';
421 // This function finds height of solid rectangle of atoms, which are all
422 // assigned to the same object. Rectangle base is defined by specified
424 function rectHeight ($rackData, $startRow, $template_idx)
427 // The first met object_id is used to match all the folowing IDs.
432 for ($locidx = 0; $locidx < 3; $locidx++
)
434 // At least one value in template is TRUE, but the following block
435 // can meet 'skipped' atoms. Let's ensure we have something after processing
437 if ($template[$template_idx][$locidx])
439 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
441 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
443 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
445 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
448 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
449 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
453 // If the first row can't offer anything, bail out.
454 if ($height == 0 and $object_id == 0)
458 while ($startRow - $height > 0);
459 # echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
460 # echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
461 # echo ") height==${height}<br>\n";
465 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
467 function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
469 global $template, $templateWidth;
471 for ($height = 0; $height < $maxheight; $height++
)
473 for ($locidx = 0; $locidx < 3; $locidx++
)
475 if ($template[$template_idx][$locidx])
477 // Add colspan/rowspan to the first row met and mark the following ones to skip.
478 // Explicitly show even single-cell spanned atoms, because rectHeight()
479 // is expeciting this data for correct calculation.
481 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
484 $colspan = $templateWidth[$template_idx];
486 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
488 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
496 // This function sets rowspan/solspan/skipped atom attributes for renderRack()
497 // What we actually have to do is to find _all_ possible rectangles for each unit
498 // and then select the widest of those with the maximal square.
499 function markAllSpans (&$rackData)
501 for ($i = $rackData['height']; $i > 0; $i--)
502 while (markBestSpan ($rackData, $i));
505 // Calculate height of 6 possible span templates (array is presorted by width
506 // descending) and mark the best (if any).
507 function markBestSpan (&$rackData, $i)
509 global $template, $templateWidth;
510 for ($j = 0; $j < 6; $j++
)
512 $height[$j] = rectHeight ($rackData, $i, $j);
513 $square[$j] = $height[$j] * $templateWidth[$j];
515 // find the widest rectangle of those with maximal height
516 $maxsquare = max ($square);
519 $best_template_index = 0;
520 for ($j = 0; $j < 6; $j++
)
521 if ($square[$j] == $maxsquare)
523 $best_template_index = $j;
524 $bestheight = $height[$j];
527 // distribute span marks
528 markSpan ($rackData, $i, $bestheight, $best_template_index);
532 // We can mount 'F' atoms and unmount our own 'T' atoms.
533 function applyObjectMountMask (&$rackData, $object_id)
535 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
536 for ($locidx = 0; $locidx < 3; $locidx++
)
537 switch ($rackData[$unit_no][$locidx]['state'])
540 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
543 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
546 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
550 // Design change means transition between 'F' and 'A' and back.
551 function applyRackDesignMask (&$rackData)
553 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
554 for ($locidx = 0; $locidx < 3; $locidx++
)
555 switch ($rackData[$unit_no][$locidx]['state'])
559 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
562 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
566 // The same for 'F' and 'U'.
567 function applyRackProblemMask (&$rackData)
569 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
570 for ($locidx = 0; $locidx < 3; $locidx++
)
571 switch ($rackData[$unit_no][$locidx]['state'])
575 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
578 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
582 // This function highlights specified object (and removes previous highlight).
583 function highlightObject (&$rackData, $object_id)
585 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
586 for ($locidx = 0; $locidx < 3; $locidx++
)
589 $rackData[$unit_no][$locidx]['state'] == 'T' and
590 $rackData[$unit_no][$locidx]['object_id'] == $object_id
592 $rackData[$unit_no][$locidx]['hl'] = 'h';
594 unset ($rackData[$unit_no][$locidx]['hl']);
597 // This function marks atoms to selected or not depending on their current state.
598 function markupAtomGrid (&$data, $checked_state)
600 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
601 for ($locidx = 0; $locidx < 3; $locidx++
)
603 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
605 if ($data[$unit_no][$locidx]['state'] == $checked_state)
606 $data[$unit_no][$locidx]['checked'] = ' checked';
608 $data[$unit_no][$locidx]['checked'] = '';
612 // This function is almost a clone of processGridForm(), but doesn't save anything to database
613 // Return value is the changed rack data.
614 // Here we assume that correct filter has already been applied, so we just
615 // set or unset checkbox inputs w/o changing atom state.
616 function mergeGridFormToRack (&$rackData)
618 $rack_id = $rackData['id'];
619 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
620 for ($locidx = 0; $locidx < 3; $locidx++
)
622 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
624 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
625 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
626 $rackData[$unit_no][$locidx]['checked'] = ' checked';
628 $rackData[$unit_no][$locidx]['checked'] = '';
632 // netmask conversion from length to number
633 function binMaskFromDec ($maskL)
635 $map_straight = array (
670 return $map_straight[$maskL];
673 // complementary value
674 function binInvMaskFromDec ($maskL)
711 return $map_compl[$maskL];
714 // This function looks up 'has_problems' flag for 'T' atoms
715 // and modifies 'hl' key. May be, this should be better done
716 // in amplifyCell(). We don't honour 'skipped' key, because
717 // the function is also used for thumb creation.
718 function markupObjectProblems (&$rackData)
720 for ($i = $rackData['height']; $i > 0; $i--)
721 for ($locidx = 0; $locidx < 3; $locidx++
)
722 if ($rackData[$i][$locidx]['state'] == 'T')
724 $object = spotEntity ('object', $rackData[$i][$locidx]['object_id']);
725 if ($object['has_problems'] == 'yes')
727 // Object can be already highlighted.
728 if (isset ($rackData[$i][$locidx]['hl']))
729 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
731 $rackData[$i][$locidx]['hl'] = 'w';
736 // Return a uniformly (010203040506 or 0102030405060708) formatted address, if it is present
737 // in the provided string, an empty string for an empty string or raise an exception.
738 function l2addressForDatabase ($string)
740 $string = strtoupper ($string);
743 case ($string == '' or preg_match (RE_L2_SOLID
, $string) or preg_match (RE_L2_WWN_SOLID
, $string)):
745 case (preg_match (RE_L2_IFCFG
, $string) or preg_match (RE_L2_WWN_COLON
, $string)):
746 // reformat output of SunOS ifconfig
748 foreach (explode (':', $string) as $byte)
749 $ret .= (strlen ($byte) == 1 ?
'0' : '') . $byte;
751 case (preg_match (RE_L2_CISCO
, $string)):
752 return str_replace ('.', '', $string);
753 case (preg_match (RE_L2_HUAWEI
, $string)):
754 return str_replace ('-', '', $string);
755 case (preg_match (RE_L2_IPCFG
, $string) or preg_match (RE_L2_WWN_HYPHEN
, $string)):
756 return str_replace ('-', '', $string);
758 throw new InvalidArgException ('$string', $string, 'malformed MAC/WWN address');
762 function l2addressFromDatabase ($string)
764 switch (strlen ($string))
767 case 16: // FireWire/Fibre Channel
768 $ret = implode (':', str_split ($string, 2));
777 // The following 2 functions return previous and next rack IDs for
778 // a given rack ID. The order of racks is the same as in renderRackspace()
780 function getPrevIDforRack ($row_id, $rack_id)
782 $rackList = listCells ('rack', $row_id);
783 doubleLink ($rackList);
784 if (isset ($rackList[$rack_id]['prev_key']))
785 return $rackList[$rack_id]['prev_key'];
789 function getNextIDforRack ($row_id, $rack_id)
791 $rackList = listCells ('rack', $row_id);
792 doubleLink ($rackList);
793 if (isset ($rackList[$rack_id]['next_key']))
794 return $rackList[$rack_id]['next_key'];
798 // This function finds previous and next array keys for each array key and
799 // modifies its argument accordingly.
800 function doubleLink (&$array)
803 foreach (array_keys ($array) as $key)
807 $array[$key]['prev_key'] = $prev_key;
808 $array[$prev_key]['next_key'] = $key;
814 function sortTokenize ($a, $b)
820 $a = preg_replace('/[^a-zA-Z0-9]/',' ',$a);
821 $a = preg_replace('/([0-9])([a-zA-Z])/','\\1 \\2',$a);
822 $a = preg_replace('/([a-zA-Z])([0-9])/','\\1 \\2',$a);
829 $b = preg_replace('/[^a-zA-Z0-9]/',' ',$b);
830 $b = preg_replace('/([0-9])([a-zA-Z])/','\\1 \\2',$b);
831 $b = preg_replace('/([a-zA-Z])([0-9])/','\\1 \\2',$b);
836 $ar = explode(' ', $a);
837 $br = explode(' ', $b);
838 for ($i=0; $i<count($ar) && $i<count($br); $i++
)
841 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
842 $ret = ($ar[$i]==$br[$i])?
0:($ar[$i]<$br[$i]?
-1:1);
844 $ret = strcasecmp($ar[$i], $br[$i]);
855 // This function returns an array of single element of object's FQDN attribute,
856 // if FQDN is set. The next choice is object's common name, if it looks like a
857 // hostname. Otherwise an array of all 'regular' IP addresses of the
858 // object is returned (which may appear 0 and more elements long).
859 function findAllEndpoints ($object_id, $fallback = '')
861 foreach (getAttrValues ($object_id) as $record)
862 if ($record['id'] == 3 && strlen ($record['value'])) // FQDN
863 return array ($record['value']);
865 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
866 if ($alloc['type'] == 'regular')
867 $regular[] = $dottedquad;
868 if (!count ($regular) && strlen ($fallback))
869 return array ($fallback);
873 // Some records in the dictionary may be written as plain text or as Wiki
874 // link in the following syntax:
876 // 2. [[word URL]] // FIXME: this isn't working
877 // 3. [[word word word | URL]]
878 // This function parses the line in $record['value'] and modifies $record:
879 // $record['o_value'] is set to be the first part of link (word word word)
880 // $record['a_value'] is the same, but with %GPASS and %GSKIP macros applied
881 // $record['href'] is set to URL if it is specified in the input value
882 function parseWikiLink (&$record)
884 if (! preg_match ('/^\[\[(.+)\]\]$/', $record['value'], $matches))
885 $record['o_value'] = $record['value'];
888 $s = explode ('|', $matches[1]);
890 $record['href'] = trim ($s[1]);
891 $record['o_value'] = trim ($s[0]);
893 $record['a_value'] = execGMarker ($record['o_value']);
896 // FIXME: should this be saved as "P-data"?
897 function execGMarker ($line)
899 return preg_replace ('/^.+%GSKIP%/', '', preg_replace ('/^(.+)%GPASS%/', '\\1 ', $line));
902 // rackspace usage for a single rack
903 // (T + W + U) / (height * 3 - A)
904 function getRSUforRack ($data)
906 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
907 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
908 for ($locidx = 0; $locidx < 3; $locidx++
)
909 $counter[$data[$unit_no][$locidx]['state']]++
;
910 return ($counter['T'] +
$counter['W'] +
$counter['U']) / ($counter['T'] +
$counter['W'] +
$counter['U'] +
$counter['F']);
914 function getRSUforRackRow ($rowData)
916 if (!count ($rowData))
918 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
920 foreach (array_keys ($rowData) as $rack_id)
922 $data = spotEntity ('rack', $rack_id);
924 $total_height +
= $data['height'];
925 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
926 for ($locidx = 0; $locidx < 3; $locidx++
)
927 $counter[$data[$unit_no][$locidx]['state']]++
;
929 return ($counter['T'] +
$counter['W'] +
$counter['U']) / ($counter['T'] +
$counter['W'] +
$counter['U'] +
$counter['F']);
932 // Make sure the string is always wrapped with LF characters
933 function lf_wrap ($str)
935 $ret = trim ($str, "\r\n");
941 // Adopted from Mantis BTS code.
942 function string_insert_hrefs ($s)
944 if (getConfigVar ('DETECT_URLS') != 'yes')
946 # Find any URL in a string and replace it by a clickable link
947 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
948 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
950 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
951 '<a href="mailto:\0">\0</a>',
957 function email_regex_simple ()
959 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
960 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
963 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
964 // for the requested object_type_id.
965 function getAutoPorts ($type_id)
968 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
969 foreach ($typemap as $equation)
971 $tmp = explode ('=', $equation);
972 if (count ($tmp) != 2)
974 $objtype_id = $tmp[0];
975 if ($objtype_id != $type_id)
978 foreach (explode ('+', $portlist) as $product)
980 $tmp = explode ('*', $product);
981 if (count ($tmp) != 3)
984 $port_type = $tmp[1];
986 for ($i = 0; $i < $nports; $i++
)
987 $ret[] = array ('type' => $port_type, 'name' => @sprintf
($format, $i));
993 // Use pre-served trace to traverse the tree, then place given node where it belongs.
994 function pokeNode (&$tree, $trace, $key, $value, $threshold = 0)
996 // This function needs the trace to be followed FIFO-way. The fastest
997 // way to do so is to use array_push() for putting values into the
998 // list and array_shift() for getting them out. This exposed up to 11%
999 // performance gain compared to other patterns of array_push/array_unshift/
1000 // array_reverse/array_pop/array_shift conjunction.
1001 $myid = array_shift ($trace);
1002 if (!count ($trace)) // reached the target
1004 if (!$threshold or ($threshold and $tree[$myid]['kidc'] +
1 < $threshold))
1005 $tree[$myid]['kids'][$key] = $value;
1006 // Reset accumulated records once, when the limit is reached, not each time
1008 if (++
$tree[$myid]['kidc'] == $threshold)
1009 $tree[$myid]['kids'] = array();
1013 $self = __FUNCTION__
;
1014 $self ($tree[$myid]['kids'], $trace, $key, $value, $threshold);
1018 // Likewise traverse the tree with the trace and return the final node.
1019 function peekNode ($tree, $trace, $target_id)
1021 $self = __FUNCTION__
;
1022 if (NULL === ($next = array_shift ($trace))) // warm
1024 foreach ($tree as $node)
1025 if (array_key_exists ('id', $node) and $node['id'] == $target_id) // hot
1030 foreach ($tree as $node)
1031 if (array_key_exists ('id', $node) and $node['id'] == $next) // warmer
1032 return $self ($node['kids'], $trace, $target_id);
1034 throw new RackTablesError ('inconsistent tree data', RackTablesError
::INTERNAL
);
1037 // Build a tree from the item list and return it. Input and output data is
1038 // indexed by item id (nested items in output are recursively stored in 'kids'
1039 // key, which is in turn indexed by id. Functions, which are ready to handle
1040 // tree collapsion/expansion themselves, may request non-zero threshold value
1041 // for smaller resulting tree.
1042 function treeFromList (&$orig_nodelist, $threshold = 0, $return_main_payload = TRUE)
1045 $nodelist = $orig_nodelist;
1046 // Array equivalent of traceEntity() function.
1048 // set kidc and kids only once
1049 foreach (array_keys ($nodelist) as $nodeid)
1051 $nodelist[$nodeid]['kidc'] = 0;
1052 $nodelist[$nodeid]['kids'] = array();
1057 foreach (array_keys ($nodelist) as $nodeid)
1059 // When adding a node to the working tree, book another
1060 // iteration, because the new item could make a way for
1061 // others onto the tree. Also remove any item added from
1062 // the input list, so iteration base shrinks.
1063 // First check if we can assign directly.
1064 if ($nodelist[$nodeid]['parent_id'] == NULL)
1066 $tree[$nodeid] = $nodelist[$nodeid];
1067 $trace[$nodeid] = array(); // Trace to root node is empty
1068 unset ($nodelist[$nodeid]);
1071 // Now look if it fits somewhere on already built tree.
1072 elseif (isset ($trace[$nodelist[$nodeid]['parent_id']]))
1074 // Trace to a node is a trace to its parent plus parent id.
1075 $trace[$nodeid] = $trace[$nodelist[$nodeid]['parent_id']];
1076 $trace[$nodeid][] = $nodelist[$nodeid]['parent_id'];
1077 pokeNode ($tree, $trace[$nodeid], $nodeid, $nodelist[$nodeid], $threshold);
1078 // path to any other node is made of all parent nodes plus the added node itself
1079 unset ($nodelist[$nodeid]);
1085 if (!$return_main_payload)
1087 // update each input node with its backtrace route
1088 foreach ($trace as $nodeid => $route)
1089 $orig_nodelist[$nodeid]['trace'] = $route;
1093 // Build a tree from the tag list and return everything _except_ the tree.
1094 // IOW, return taginfo items, which have parent_id set and pointing outside
1095 // of the "normal" tree, which originates from the root.
1096 function getOrphanedTags ()
1099 return treeFromList ($taglist, 0, FALSE);
1102 function serializeTags ($chain, $baseurl = '')
1106 foreach ($chain as $taginfo)
1109 ($baseurl == '' ?
'' : "<a href='${baseurl}cft[]=${taginfo['id']}'>") .
1111 ($baseurl == '' ?
'' : '</a>');
1117 // Return the list of missing implicit tags.
1118 function getImplicitTags ($oldtags)
1122 foreach ($oldtags as $taginfo)
1123 $tmp = array_merge ($tmp, $taglist[$taginfo['id']]['trace']);
1124 // don't call array_unique here, it is in the function we will call now
1125 return buildTagChainFromIds ($tmp);
1128 // Minimize the chain: exclude all implicit tags and return the result.
1129 // This function makes use of an external cache with a miss/hit ratio
1130 // about 3/7 (ticket:255).
1131 function getExplicitTagsOnly ($chain)
1133 global $taglist, $tagRelCache;
1135 foreach (array_keys ($chain) as $keyA) // check each A
1137 $tagidA = $chain[$keyA]['id'];
1138 // do not include A in result, if A is seen on the trace of any B!=A
1139 foreach (array_keys ($chain) as $keyB)
1141 $tagidB = $chain[$keyB]['id'];
1142 if ($tagidA == $tagidB)
1144 if (!isset ($tagRelCache[$tagidA][$tagidB]))
1145 $tagRelCache[$tagidA][$tagidB] = in_array ($tagidA, $taglist[$tagidB]['trace']);
1146 if ($tagRelCache[$tagidA][$tagidB] === TRUE) // A is ancestor of B
1147 continue 2; // skip this A
1149 $ret[] = $chain[$keyA];
1154 // Universal autotags generator, a complementing function for loadEntityTags().
1155 // Bypass key isn't strictly typed, but interpreted depending on the realm.
1156 function generateEntityAutoTags ($cell)
1159 if (! array_key_exists ('realm', $cell))
1160 throw new InvalidArgException ('cell', '(array)', 'malformed structure');
1161 switch ($cell['realm'])
1164 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
1165 $ret[] = array ('tag' => '$any_rack');
1168 $ret[] = array ('tag' => '$id_' . $cell['id']);
1169 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
1170 $ret[] = array ('tag' => '$any_object');
1171 if (validTagName ('$cn_' . $cell['name'], TRUE))
1172 $ret[] = array ('tag' => '$cn_' . $cell['name']);
1173 if (!strlen ($cell['rack_id']))
1174 $ret[] = array ('tag' => '$unmounted');
1175 if (!$cell['nports'])
1176 $ret[] = array ('tag' => '$portless');
1177 if ($cell['asset_no'] == '')
1178 $ret[] = array ('tag' => '$no_asset_tag');
1179 if ($cell['runs8021Q'])
1180 $ret[] = array ('tag' => '$runs_8021Q');
1182 // dictionary attribute autotags '$attr_X_Y'
1183 $attrs = getAttrValues($cell['id']);
1184 foreach ($attrs as $attr_id => $attr_record)
1185 if (isset ($attr_record['key']))
1186 $ret[] = array ('tag' => "\$attr_{$attr_id}_{$attr_record['key']}");
1189 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
1190 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
1191 for ($i = 8; $i < 32; $i++
)
1193 // these conditions hit 1 to 3 times per each i
1194 if ($cell['mask'] >= $i)
1195 $ret[] = array ('tag' => '$masklen_ge_' . $i);
1196 if ($cell['mask'] <= $i)
1197 $ret[] = array ('tag' => '$masklen_le_' . $i);
1198 if ($cell['mask'] == $i)
1199 $ret[] = array ('tag' => '$masklen_eq_' . $i);
1201 $ret[] = array ('tag' => '$any_ip4net');
1202 $ret[] = array ('tag' => '$any_net');
1205 $ret[] = array ('tag' => '$ip6netid_' . $cell['id']);
1206 $ret[] = array ('tag' => '$any_ip6net');
1207 $ret[] = array ('tag' => '$any_net');
1210 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
1211 $ret[] = array ('tag' => '$any_ipv4vs');
1212 $ret[] = array ('tag' => '$any_vs');
1215 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
1216 $ret[] = array ('tag' => '$any_ipv4rsp');
1217 $ret[] = array ('tag' => '$any_rsp');
1220 // {$username_XXX} autotag is generated always, but {$userid_XXX}
1221 // appears only for accounts, which exist in local database.
1222 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
1223 if (isset ($cell['user_id']))
1224 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
1227 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
1228 $ret[] = array ('tag' => '$any_file');
1231 throw new InvalidArgException ('cell', '(array)', 'this input does not belong here');
1234 // {$tagless} doesn't apply to users
1235 switch ($cell['realm'])
1244 if (!count ($cell['etags']))
1245 $ret[] = array ('tag' => '$untagged');
1253 // Check, if the given tag is present on the chain (will only work
1254 // for regular tags with tag ID set.
1255 function tagOnChain ($taginfo, $tagchain)
1257 if (!isset ($taginfo['id']))
1259 foreach ($tagchain as $test)
1260 if ($test['id'] == $taginfo['id'])
1265 function tagNameOnChain ($tagname, $tagchain)
1267 foreach ($tagchain as $test)
1268 if ($test['tag'] == $tagname)
1273 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1274 // Assume, that neither of the lists contains duplicates.
1275 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1276 function tagChainCmp ($chain1, $chain2)
1278 if (count ($chain1) != count ($chain2))
1280 foreach ($chain1 as $taginfo1)
1281 if (!tagOnChain ($taginfo1, $chain2))
1286 function redirectIfNecessary ()
1294 'accounts' => 'userlist',
1295 'rspools' => 'ipv4rsplist',
1296 'rspool' => 'ipv4rsp',
1297 'vservices' => 'ipv4vslist',
1298 'vservice' => 'ipv4vs',
1299 'objects' => 'depot',
1300 'objgroup' => 'depot',
1303 $tmap['objects']['newmulti'] = 'addmore';
1304 $tmap['objects']['newobj'] = 'addmore';
1305 $tmap['object']['switchvlans'] = 'livevlans';
1306 $tmap['object']['slb'] = 'editrspvs';
1307 $tmap['object']['portfwrd'] = 'nat4';
1308 $tmap['object']['network'] = 'ipv4';
1309 if (isset ($pmap[$pageno]))
1310 redirectUser ($pmap[$pageno], $tabno);
1311 if (isset ($tmap[$pageno][$tabno]))
1312 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1316 ! isset ($_REQUEST['tab']) and
1317 isset ($_SESSION['RTLT'][$pageno]) and
1318 getConfigVar ('SHOW_LAST_TAB') == 'yes' and
1319 permitted ($pageno, $_SESSION['RTLT'][$pageno]['tabname']) and
1320 time() - $_SESSION['RTLT'][$pageno]['time'] <= TAB_REMEMBER_TIMEOUT
1322 redirectUser ($pageno, $_SESSION['RTLT'][$pageno]['tabname']);
1324 // check if we accidentaly got on a dynamic tab that shouldn't be shown for this object
1327 isset ($trigger[$pageno][$tabno]) and
1328 !strlen (call_user_func ($trigger[$pageno][$tabno]))
1331 $_SESSION['RTLT'][$pageno]['dont_remember'] = 1;
1332 redirectUser ($pageno, 'default');
1336 function prepareNavigation()
1341 $pageno = (isset ($_REQUEST['page'])) ?
$_REQUEST['page'] : 'index';
1343 if (isset ($_REQUEST['tab']))
1344 $tabno = $_REQUEST['tab'];
1349 function fixContext ($target = NULL)
1361 if ($target !== NULL)
1363 $target_given_tags = $target['etags'];
1364 // Don't reset autochain, because auth procedures could push stuff there in.
1365 // Another important point is to ignore 'user' realm, so we don't infuse effective
1366 // context with autotags of the displayed account.
1367 if ($target['realm'] != 'user')
1368 $auto_tags = array_merge ($auto_tags, $target['atags']);
1370 elseif (array_key_exists ($pageno, $etype_by_pageno))
1372 // Each page listed in the map above requires one uint argument.
1373 $target_realm = $etype_by_pageno[$pageno];
1374 assertUIntArg ($page[$pageno]['bypass']);
1375 $target_id = $_REQUEST[$page[$pageno]['bypass']];
1376 $target = spotEntity ($target_realm, $target_id);
1377 $target_given_tags = $target['etags'];
1378 if ($target['realm'] != 'user')
1379 $auto_tags = array_merge ($auto_tags, $target['atags']);
1381 // Explicit and implicit chains should be normally empty at this point, so
1382 // overwrite the contents anyway.
1383 $expl_tags = mergeTagChains ($user_given_tags, $target_given_tags);
1384 $impl_tags = getImplicitTags ($expl_tags);
1387 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1388 // records indexed by tag IDs (tag chain).
1389 function buildTagChainFromIds ($tagidlist)
1393 foreach (array_unique ($tagidlist) as $tag_id)
1394 if (isset ($taglist[$tag_id]))
1395 $ret[] = $taglist[$tag_id];
1399 // Process a given tag tree and return only meaningful branches. The resulting
1400 // (sub)tree will have refcnt leaves on every last branch.
1401 function getObjectiveTagTree ($tree, $realm, $preselect)
1403 $self = __FUNCTION__
;
1405 foreach ($tree as $taginfo)
1407 $subsearch = $self ($taginfo['kids'], $realm, $preselect);
1408 // If the current node addresses something, add it to the result
1409 // regardless of how many sub-nodes it features.
1412 isset ($taginfo['refcnt'][$realm]) or
1413 count ($subsearch) > 1 or
1414 in_array ($taginfo['id'], $preselect)
1418 'id' => $taginfo['id'],
1419 'tag' => $taginfo['tag'],
1420 'parent_id' => $taginfo['parent_id'],
1421 'refcnt' => $taginfo['refcnt'],
1422 'kids' => $subsearch
1425 $ret = array_merge ($ret, $subsearch);
1430 // Preprocess tag tree to get only tags which can effectively reduce given filter result,
1431 // than passes shrinked tag tree to getObjectiveTagTree and return its result.
1432 // This makes sense only if andor mode is 'and', otherwise function does not modify tree.
1433 // 'Given filter' is a pair of $entity_list(filter result) and $preselect(filter data).
1434 // 'Effectively' means reduce to non-empty result.
1435 function getShrinkedTagTree($entity_list, $realm, $preselect) {
1437 if ($preselect['andor'] != 'and' ||
empty($entity_list) && $preselect['is_empty'])
1438 return getObjectiveTagTree($tagtree, $realm, $preselect['tagidlist']);
1440 $used_tags = array(); //associative, keys - tag ids, values - taginfos
1441 foreach ($entity_list as $entity)
1443 foreach ($entity['etags'] as $etag)
1444 if (! array_key_exists($etag['id'], $used_tags))
1445 $used_tags[$etag['id']] = 1;
1447 $used_tags[$etag['id']]++
;
1449 foreach ($entity['itags'] as $itag)
1450 if (! array_key_exists($itag['id'], $used_tags))
1451 $used_tags[$itag['id']] = 0;
1454 $shrinked_tree = shrinkSubtree($tagtree, $used_tags, $preselect, $realm);
1455 return getObjectiveTagTree($shrinked_tree, $realm, $preselect['tagidlist']);
1458 // deletes item from tag subtree unless it exists in $used_tags and not preselected
1459 function shrinkSubtree($tree, $used_tags, $preselect, $realm) {
1460 $self = __FUNCTION__
;
1462 foreach($tree as $i => &$item) {
1463 $item['kids'] = $self($item['kids'], $used_tags, $preselect, $realm);
1464 $item['kidc'] = count($item['kids']);
1467 ! array_key_exists($item['id'], $used_tags) &&
1468 ! in_array($item['id'], $preselect['tagidlist']) &&
1473 $item['refcnt'][$realm] = $used_tags[$item['id']];
1474 if (! $item['refcnt'][$realm])
1475 unset($item['refcnt'][$realm]);
1481 // Get taginfo record by tag name, return NULL, if record doesn't exist.
1482 function getTagByName ($target_name)
1485 foreach ($taglist as $taginfo)
1486 if ($taginfo['tag'] == $target_name)
1491 // Merge two chains, filtering dupes out. Return the resulting superset.
1492 function mergeTagChains ($chainA, $chainB)
1495 // Reindex by tag id in any case.
1497 foreach ($chainA as $tag)
1498 $ret[$tag['id']] = $tag;
1499 foreach ($chainB as $tag)
1500 if (!isset ($ret[$tag['id']]))
1501 $ret[$tag['id']] = $tag;
1505 function getCellFilter ()
1509 $staticFilter = getConfigVar ('STATIC_FILTER');
1510 if (isset ($_REQUEST['tagfilter']) and is_array ($_REQUEST['tagfilter']))
1512 $_REQUEST['cft'] = $_REQUEST['tagfilter'];
1513 unset ($_REQUEST['tagfilter']);
1515 $andor_used = FALSE;
1516 //if the page is submitted we get an andor value so we know they are trying to start a new filter or clearing the existing one.
1517 if(isset($_REQUEST['andor']))
1520 unset($_SESSION[$pageno]);
1522 if (isset ($_SESSION[$pageno]['tagfilter']) and is_array ($_SESSION[$pageno]['tagfilter']) and !(isset($_REQUEST['cft'])) and $staticFilter == 'yes')
1524 $_REQUEST['cft'] = $_SESSION[$pageno]['tagfilter'];
1526 if (isset ($_SESSION[$pageno]['cfe']) and !(isset($sic['cfe'])) and $staticFilter == 'yes')
1528 $sic['cfe'] = $_SESSION[$pageno]['cfe'];
1530 if (isset ($_SESSION[$pageno]['andor']) and !(isset($_REQUEST['andor'])) and $staticFilter == 'yes')
1532 $_REQUEST['andor'] = $_SESSION[$pageno]['andor'];
1538 'tagidlist' => array(),
1539 'tnamelist' => array(),
1540 'pnamelist' => array(),
1544 'expression' => array(),
1545 'urlextra' => '', // Just put text here and let makeHref call urlencode().
1550 case (!isset ($_REQUEST['andor'])):
1551 $andor2 = getConfigVar ('FILTER_DEFAULT_ANDOR');
1553 case ($_REQUEST['andor'] == 'and'):
1554 case ($_REQUEST['andor'] == 'or'):
1555 $_SESSION[$pageno]['andor'] = $_REQUEST['andor'];
1556 $ret['andor'] = $andor2 = $_REQUEST['andor'];
1559 showWarning ('Invalid and/or switch value in submitted form');
1563 // Both tags and predicates, which don't exist, should be
1564 // handled somehow. Discard them silently for now.
1565 if (isset ($_REQUEST['cft']) and is_array ($_REQUEST['cft']))
1567 $_SESSION[$pageno]['tagfilter'] = $_REQUEST['cft'];
1569 foreach ($_REQUEST['cft'] as $req_id)
1570 if (isset ($taglist[$req_id]))
1572 $ret['tagidlist'][] = $req_id;
1573 $ret['tnamelist'][] = $taglist[$req_id]['tag'];
1574 $andor_used = $andor_used ||
(trim($andor1) != '');
1575 $ret['text'] .= $andor1 . '{' . $taglist[$req_id]['tag'] . '}';
1576 $andor1 = ' ' . $andor2 . ' ';
1577 $ret['urlextra'] .= '&cft[]=' . $req_id;
1580 if (isset ($_REQUEST['cfp']) and is_array ($_REQUEST['cfp']))
1583 foreach ($_REQUEST['cfp'] as $req_name)
1584 if (isset ($pTable[$req_name]))
1586 $ret['pnamelist'][] = $req_name;
1587 $andor_used = $andor_used ||
(trim($andor1) != '');
1588 $ret['text'] .= $andor1 . '[' . $req_name . ']';
1589 $andor1 = ' ' . $andor2 . ' ';
1590 $ret['urlextra'] .= '&cfp[]=' . $req_name;
1593 // Extra text comes from TEXTAREA and is easily screwed by standard escaping function.
1594 if (isset ($sic['cfe']))
1596 $_SESSION[$pageno]['cfe'] = $sic['cfe'];
1597 // Only consider extra text, when it is a correct RackCode expression.
1598 $parse = spotPayload ($sic['cfe'], 'SYNT_EXPR');
1599 if ($parse['result'] == 'ACK')
1601 $ret['extratext'] = trim ($sic['cfe']);
1602 $ret['urlextra'] .= '&cfe=' . $ret['extratext'];
1605 $finaltext = array();
1606 if (strlen ($ret['text']))
1607 $finaltext[] = '(' . $ret['text'] . ')';
1608 if (strlen ($ret['extratext']))
1609 $finaltext[] = '(' . $ret['extratext'] . ')';
1610 $andor_used = $andor_used ||
(count($finaltext) > 1);
1611 $finaltext = implode (' ' . $andor2 . ' ', $finaltext);
1612 if (strlen ($finaltext))
1614 $ret['is_empty'] = FALSE;
1615 $parse = spotPayload ($finaltext, 'SYNT_EXPR');
1616 $ret['expression'] = $parse['result'] == 'ACK' ?
$parse['load'] : NULL;
1617 // It's not quite fair enough to put the blame of the whole text onto
1618 // non-empty "extra" portion of it, but it's the only user-generated portion
1619 // of it, thus the most probable cause of parse error.
1620 if (strlen ($ret['extratext']))
1621 $ret['extraclass'] = $parse['result'] == 'ACK' ?
'validation-success' : 'validation-error';
1624 $ret['andor'] = getConfigVar ('FILTER_DEFAULT_ANDOR');
1626 $ret['urlextra'] .= '&andor=' . $ret['andor'];
1630 // Return an empty message log.
1631 function emptyLog ()
1640 // Return a message log consisting of only one message.
1641 function oneLiner ($code, $args = array())
1644 $ret['m'][] = count ($args) ?
array ('c' => $code, 'a' => $args) : array ('c' => $code);
1648 // Merge message payload from two message logs given and return the result.
1649 function mergeLogs ($log1, $log2)
1652 $ret['m'] = array_merge ($log1['m'], $log2['m']);
1656 function validTagName ($s, $allow_autotag = FALSE)
1658 if (1 == preg_match (TAGNAME_REGEXP
, $s))
1660 if ($allow_autotag and 1 == preg_match (AUTOTAGNAME_REGEXP
, $s))
1665 function redirectUser ($p, $t)
1668 $l = "index.php?page=${p}&tab=${t}";
1669 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1670 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1671 if (isset ($page[$p]['bypass_tabs']))
1672 foreach ($page[$p]['bypass_tabs'] as $param_name)
1673 if (isset ($_REQUEST[$param_name]))
1674 $l .= '&' . urlencode ($param_name) . '=' . urlencode ($_REQUEST[$param_name]);
1675 header ("Location: " . $l);
1679 function getRackCodeStats ()
1682 $defc = $grantc = $modc = 0;
1683 foreach ($rackCode as $s)
1686 case 'SYNT_DEFINITION':
1700 'Definition sentences' => $defc,
1701 'Grant sentences' => $grantc,
1702 'Context mod sentences' => $modc
1707 function getRackImageWidth ()
1710 return 3 +
$rtwidth[0] +
$rtwidth[1] +
$rtwidth[2] +
3;
1713 function getRackImageHeight ($units)
1715 return 3 +
3 +
$units * 2;
1718 // Perform substitutions and return resulting string
1719 // used solely by buildLVSConfig()
1720 function apply_macros ($macros, $subject, &$error_macro_stat)
1722 // clear all text before last %RESET% macro
1723 $reset_keyword = '%RESET%';
1724 $reset_position = mb_strpos($subject, $reset_keyword, 0);
1725 if ($reset_position === FALSE)
1730 mb_substr($subject, $reset_position +
mb_strlen($reset_keyword)),
1734 foreach ($macros as $search => $replace)
1736 if (empty($replace))
1738 $replace = "<span class=\"msg_error\">$search</span>";
1740 $ret = str_replace ($search, $replace, $ret, $count);
1743 if (array_key_exists($search, $error_macro_stat))
1744 $error_macro_stat[$search] +
= $count;
1746 $error_macro_stat[$search] = $count;
1750 $ret = str_replace ($search, $replace, $ret);
1755 // throws RTBuildLVSConfigError exception if undefined macros found
1756 function buildLVSConfig ($object_id)
1758 $oInfo = spotEntity ('object', $object_id);
1759 $defaults = getSLBDefaults (TRUE);
1760 $lbconfig = getSLBConfig ($object_id);
1761 if ($lbconfig === NULL)
1763 showWarning ('getSLBConfig() failed');
1766 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1767 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1769 $error_stat = array();
1770 foreach ($lbconfig as $vs_id => $vsinfo)
1772 $newconfig .= "########################################################\n" .
1773 "# VS (id == ${vs_id}): " . (!strlen ($vsinfo['vs_name']) ?
'NO NAME' : $vsinfo['vs_name']) . "\n" .
1774 "# RS pool (id == ${vsinfo['pool_id']}): " . (!strlen ($vsinfo['pool_name']) ?
'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1775 "########################################################\n";
1776 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1779 '%VIP%' => $vsinfo['vip'],
1780 '%VPORT%' => $vsinfo['vport'],
1781 '%PROTO%' => $vsinfo['proto'],
1782 '%VNAME%' => $vsinfo['vs_name'],
1783 '%RSPOOLNAME%' => $vsinfo['pool_name'],
1784 '%PRIO%' => $vsinfo['prio']
1786 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1787 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1788 $newconfig .= lf_wrap (apply_macros
1791 lf_wrap ($defaults['vs']) .
1792 lf_wrap ($vsinfo['vs_vsconfig']) .
1793 lf_wrap ($vsinfo['lb_vsconfig']) .
1794 lf_wrap ($vsinfo['pool_vsconfig']),
1797 foreach ($vsinfo['rslist'] as $rs)
1799 if (!strlen ($rs['rsport']))
1800 $rs['rsport'] = $vsinfo['vport'];
1801 $macros['%RSIP%'] = $rs['rsip'];
1802 $macros['%RSPORT%'] = $rs['rsport'];
1803 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1804 $newconfig .= lf_wrap (apply_macros
1807 lf_wrap ($defaults['rs']) .
1808 lf_wrap ($vsinfo['vs_rsconfig']) .
1809 lf_wrap ($vsinfo['lb_rsconfig']) .
1810 lf_wrap ($vsinfo['pool_rsconfig']) .
1811 lf_wrap ($rs['rs_rsconfig']),
1814 $newconfig .= "\t}\n";
1816 $newconfig .= "}\n\n\n";
1818 if (! empty($error_stat))
1820 $error_messages = array();
1821 foreach ($error_stat as $macro => $count)
1822 $error_messages[] = "Error: macro $macro can not be empty ($count occurences)";
1823 throw new RTBuildLVSConfigError($error_messages, $newconfig, $object_id);
1826 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1827 return dos2unix ($newconfig);
1830 // Indicate occupation state of each IP address: none, ordinary or problematic.
1831 function markupIPAddrList (&$addrlist)
1833 foreach (array_keys ($addrlist) as $ip_bin)
1837 'shared' => 0, // virtual
1838 'virtual' => 0, // loopback
1839 'regular' => 0, // connected host
1840 'router' => 0 // connected gateway
1842 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1843 $refc[$a['type']]++
;
1844 $nvirtloopback = ($refc['shared'] +
$refc['virtual'] > 0) ?
1 : 0; // modulus of virtual + shared
1845 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ?
1 : 0; // only one reservation is possible ever
1846 $nrealms = $nreserved +
$nvirtloopback +
$refc['regular'] +
$refc['router']; // latter two are connected and router allocations
1849 $addrlist[$ip_bin]['class'] = 'trbusy';
1850 elseif ($nrealms > 1)
1851 $addrlist[$ip_bin]['class'] = 'trerror';
1853 $addrlist[$ip_bin]['class'] = '';
1857 // Scan the given address list (returned by scanIPv4Space/scanIPv6Space) and return a list of all routers found.
1858 function findRouters ($addrlist)
1861 foreach ($addrlist as $addr)
1862 foreach ($addr['allocs'] as $alloc)
1863 if ($alloc['type'] == 'router')
1866 'id' => $alloc['object_id'],
1867 'iface' => $alloc['name'],
1868 'dname' => $alloc['object_name'],
1869 'addr' => $addr['ip']
1874 // Assist in tag chain sorting.
1875 function taginfoCmp ($tagA, $tagB)
1877 return $tagA['ci'] - $tagB['ci'];
1880 // Compare networks. When sorting a tree, the records on the list will have
1881 // distinct base IP addresses.
1882 // "The comparison function must return an integer less than, equal to, or greater
1883 // than zero if the first argument is considered to be respectively less than,
1884 // equal to, or greater than the second." (c) PHP manual
1885 function IPv4NetworkCmp ($netA, $netB)
1887 // On 64-bit systems this function can be reduced to just this:
1888 if (PHP_INT_SIZE
== 8)
1889 return $netA['ip_bin'] - $netB['ip_bin'];
1890 // There's a problem just substracting one u32 integer from another,
1891 // because the result may happen big enough to become a negative i32
1892 // integer itself (PHP tries to cast everything it sees to signed int)
1893 // The comparison below must treat positive and negative values of both
1895 // Equal values give instant decision regardless of their [equal] sign.
1896 if ($netA['ip_bin'] == $netB['ip_bin'])
1898 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1899 // 0x00000001~0x7fffffff 1~2147483647
1900 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1901 // 0x80000000~0xffffffff -2147483648~-1
1902 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1903 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1904 if ($signA == $signB)
1906 if ($netA['ip_bin'] > $netB['ip_bin'])
1911 else // With only one of two values being negative, it... wins!
1913 if ($netA['ip_bin'] < $netB['ip_bin'])
1920 function IPv6NetworkCmp ($netA, $netB)
1922 return strcmp ($netA['ip_bin'], $netB['ip_bin']);
1925 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1926 function sortTree (&$tree, $sortfunc = '')
1928 if (!strlen ($sortfunc))
1930 $self = __FUNCTION__
;
1931 usort ($tree, $sortfunc);
1932 // Don't make a mistake of directly iterating over the items of current level, because this way
1933 // the sorting will be performed on a _copy_ if each item, not the item itself.
1934 foreach (array_keys ($tree) as $tagid)
1935 $self ($tree[$tagid]['kids'], $sortfunc);
1938 function iptree_fill (&$netdata)
1940 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
1942 // If we really have nested prefixes, they must fit into the tree.
1945 'ip_bin' => $netdata['ip_bin'],
1946 'mask' => $netdata['mask']
1948 foreach ($netdata['kids'] as $pfx)
1949 iptree_embed ($worktree, $pfx);
1950 $netdata['kids'] = iptree_construct ($worktree);
1951 $netdata['kidc'] = count ($netdata['kids']);
1954 function ipv6tree_fill (&$netdata)
1956 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
1958 // If we really have nested prefixes, they must fit into the tree.
1961 'ip_bin' => $netdata['ip_bin'],
1962 'mask' => $netdata['mask']
1964 foreach ($netdata['kids'] as $pfx)
1965 ipv6tree_embed ($worktree, $pfx);
1966 $netdata['kids'] = ipv6tree_construct ($worktree);
1967 $netdata['kidc'] = count ($netdata['kids']);
1970 function iptree_construct ($node)
1972 $self = __FUNCTION__
;
1974 if (!isset ($node['right']))
1976 if (!isset ($node['ip']))
1978 $node['ip'] = long2ip ($node['ip_bin']);
1979 $node['kids'] = array();
1983 return array ($node);
1986 return array_merge ($self ($node['left']), $self ($node['right']));
1989 function ipv6tree_construct ($node)
1991 $self = __FUNCTION__
;
1993 if (!isset ($node['right']))
1995 if (!isset ($node['ip']))
1997 $node['ip'] = $node['ip_bin']->format();
1998 $node['kids'] = array();
2002 return array ($node);
2005 return array_merge ($self ($node['left']), $self ($node['right']));
2008 function iptree_embed (&$node, $pfx)
2010 $self = __FUNCTION__
;
2013 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
2018 if ($node['mask'] == $pfx['mask'])
2019 throw new RackTablesError ('the recurring loop lost control', RackTablesError
::INTERNAL
);
2022 if (!isset ($node['right']))
2024 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
2025 $node['left']['mask'] = $node['mask'] +
1;
2026 $node['left']['ip_bin'] = $node['ip_bin'];
2027 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
2028 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] |
binInvMaskFromDec ($node['left']['mask']));
2030 $node['right']['mask'] = $node['mask'] +
1;
2031 $node['right']['ip_bin'] = $node['ip_bin'] +
binInvMaskFromDec ($node['mask'] +
1) +
1;
2032 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
2033 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] |
binInvMaskFromDec ($node['right']['mask']));
2037 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
2038 $self ($node['left'], $pfx);
2039 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
2040 $self ($node['right'], $pfx);
2042 throw new RackTablesError ('cannot decide between left and right', RackTablesError
::INTERNAL
);
2045 function ipv6tree_embed (&$node, $pfx)
2047 $self = __FUNCTION__
;
2050 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
2055 if ($node['mask'] == $pfx['mask'])
2056 throw new RackTablesError ('the recurring loop lost control', RackTablesError
::INTERNAL
);
2059 if (!isset ($node['right']))
2061 $node['left']['mask'] = $node['mask'] +
1;
2062 $node['left']['ip_bin'] = $node['ip_bin'];
2063 $node['left']['db_first'] = $node['ip_bin']->get_first_subnet_address ($node['mask'] +
1);
2064 $node['left']['db_last'] = $node['ip_bin']->get_last_subnet_address ($node['mask'] +
1);
2066 $node['right']['mask'] = $node['mask'] +
1;
2067 $node['right']['ip_bin'] = $node['ip_bin']->get_last_subnet_address ($node['mask'] +
1)->next();
2068 $node['right']['db_first'] = $node['right']['ip_bin'];
2069 $node['right']['db_last'] = $node['right']['ip_bin']->get_last_subnet_address ($node['mask'] +
1);
2073 if ($node['left']['db_first'] == $pfx['ip_bin']->get_first_subnet_address ($node['left']['mask']))
2074 $self ($node['left'], $pfx);
2075 elseif ($node['right']['db_first'] == $pfx['ip_bin']->get_first_subnet_address ($node['left']['mask']))
2076 $self ($node['right'], $pfx);
2078 throw new RackTablesError ('cannot decide between left and right', RackTablesError
::INTERNAL
);
2081 function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
2083 if (!strlen ($func))
2085 $self = __FUNCTION__
;
2086 foreach (array_keys ($tree) as $key)
2088 $func ($tree[$key]);
2089 if (strlen ($stopfunc) and $stopfunc ($tree[$key]))
2091 $self ($tree[$key]['kids'], $func);
2095 function loadIPv4AddrList (&$netinfo)
2097 loadOwnIPv4Addresses ($netinfo);
2098 markupIPAddrList ($netinfo['addrlist']);
2101 function countOwnIPv4Addresses (&$node)
2104 if (empty ($node['kids']))
2105 $node['addrt'] = binInvMaskFromDec ($node['mask']) +
1;
2107 foreach ($node['kids'] as $nested)
2108 if (!isset ($nested['id'])) // spare
2109 $node['addrt'] +
= binInvMaskFromDec ($nested['mask']) +
1;
2112 function nodeIsCollapsed ($node)
2114 return $node['symbol'] == 'node-collapsed';
2117 // implies countOwnIPv4Addresses
2118 function loadOwnIPv4Addresses (&$node)
2122 if (!isset ($node['kids']) or !count ($node['kids']))
2124 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
2125 $node['addrt'] = $node['db_last'] - $node['db_first'] +
1;
2130 foreach ($node['kids'] as $nested)
2131 if (!isset ($nested['id'])) // spare
2133 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
2134 $node['addrt'] +
= $node['db_last'] - $node['db_first'] +
1;
2137 $node['addrlist'] = scanIPv4Space ($toscan);
2138 $node['addrc'] = count ($node['addrlist']);
2141 function loadIPv6AddrList (&$netinfo)
2143 loadOwnIPv6Addresses ($netinfo);
2144 markupIPAddrList ($netinfo['addrlist']);
2147 function loadOwnIPv6Addresses (&$node)
2151 if (empty ($node['kids']))
2152 $toscan[] = array ('first' => $node['ip_bin'], 'last' => $node['ip_bin']->get_last_subnet_address ($node['mask']));
2154 foreach ($node['kids'] as $nested)
2155 if (!isset ($nested['id'])) // spare
2156 $toscan[] = array ('first' => $nested['ip_bin'], 'last' => $nested['ip_bin']->get_last_subnet_address ($nested['mask']));
2157 $node['addrlist'] = scanIPv6Space ($toscan);
2158 $node['addrc'] = count ($node['addrlist']);
2161 function prepareIPv4Tree ($netlist, $expanded_id = 0)
2163 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
2164 // so perform necessary pre-processing to make orphans belong to root. This trick
2165 // was earlier performed by getIPv4NetworkList().
2166 $netids = array_keys ($netlist);
2167 foreach ($netids as $cid)
2168 if (!in_array ($netlist[$cid]['parent_id'], $netids))
2169 $netlist[$cid]['parent_id'] = NULL;
2170 $tree = treeFromList ($netlist); // medium call
2171 sortTree ($tree, 'IPv4NetworkCmp');
2172 // complement the tree before markup to make the spare networks have "symbol" set
2173 treeApplyFunc ($tree, 'iptree_fill');
2174 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
2175 // count addresses after the markup to skip computation for hidden tree nodes
2176 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
2180 function prepareIPv6Tree ($netlist, $expanded_id = 0)
2182 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
2183 // so perform necessary pre-processing to make orphans belong to root. This trick
2184 // was earlier performed by getIPv4NetworkList().
2185 $netids = array_keys ($netlist);
2186 foreach ($netids as $cid)
2187 if (!in_array ($netlist[$cid]['parent_id'], $netids))
2188 $netlist[$cid]['parent_id'] = NULL;
2189 $tree = treeFromList ($netlist); // medium call
2190 sortTree ($tree, 'IPv6NetworkCmp');
2191 // complement the tree before markup to make the spare networks have "symbol" set
2192 treeApplyFunc ($tree, 'ipv6tree_fill');
2193 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
2197 # Traverse IPv4/IPv6 tree and return a list of all networks, which
2198 # exist in DB and don't have any sub-networks.
2199 function getTerminalNetworks ($tree)
2201 $self = __FUNCTION__
;
2203 foreach ($tree as $node)
2204 if ($node['kidc'] == 0 and isset ($node['realm']))
2207 $ret = array_merge ($ret, $self ($node['kids']));
2211 // Check all items of the tree recursively, until the requested target id is
2212 // found. Mark all items leading to this item as "expanded", collapsing all
2213 // the rest, which exceed the given threshold (if the threshold is given).
2214 function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
2216 $self = __FUNCTION__
;
2218 foreach (array_keys ($tree) as $key)
2220 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
2221 $below = $self ($tree[$key]['kids'], $threshold, $target);
2222 if (!$tree[$key]['kidc']) // terminal node
2223 $tree[$key]['symbol'] = 'spacer';
2224 elseif ($tree[$key]['kidc'] < $threshold)
2225 $tree[$key]['symbol'] = 'node-expanded-static';
2226 elseif ($here or $below)
2227 $tree[$key]['symbol'] = 'node-expanded';
2229 $tree[$key]['symbol'] = 'node-collapsed';
2230 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
2235 // Convert entity name to human-readable value
2236 function formatEntityName ($name) {
2240 return 'IPv4 Network';
2242 return 'IPv6 Network';
2244 return 'IPv4 RS Pool';
2246 return 'IPv4 Virtual Service';
2257 // Take a MySQL or other generic timestamp and make it prettier
2258 function formatTimestamp ($timestamp) {
2259 return date('n/j/y g:iA', strtotime($timestamp));
2262 // Display hrefs for all of a file's parents. If scissors are requested,
2263 // prepend cutting button to each of them.
2264 function serializeFileLinks ($links, $scissors = FALSE)
2268 foreach ($links as $link_id => $li)
2270 switch ($li['entity_type'])
2273 $params = "page=ipv4net&id=";
2276 $params = "page=ipv6net&id=";
2279 $params = "page=ipv4rspool&pool_id=";
2282 $params = "page=ipv4vs&vs_id=";
2285 $params = "page=object&object_id=";
2288 $params = "page=rack&rack_id=";
2291 $params = "page=user&user_id=";
2297 $ret .= "<a href='" . makeHrefProcess(array('op'=>'unlinkFile', 'link_id'=>$link_id)) . "'";
2298 $ret .= getImageHREF ('cut') . '</a> ';
2300 $ret .= sprintf("<a href='index.php?%s%s'>%s</a>", $params, $li['entity_id'], $li['name']);
2306 // Convert filesize to appropriate unit and make it human-readable
2307 function formatFileSize ($bytes) {
2309 if($bytes < 1024) // bytes
2310 return "${bytes} bytes";
2313 if ($bytes < 1024000)
2314 return sprintf ("%.1fk", round (($bytes / 1024), 1));
2317 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
2320 // Reverse of formatFileSize, it converts human-readable value to bytes
2321 function convertToBytes ($value) {
2322 $value = trim($value);
2323 $last = strtolower($value[strlen($value)-1]);
2337 function ip_quad2long ($ip)
2339 return sprintf("%u", ip2long($ip));
2342 function ip_long2quad ($quad)
2344 return long2ip($quad);
2347 function mkA ($text, $nextpage, $bypass = NULL, $nexttab = NULL)
2350 if (!mb_strlen ($text))
2351 throw new InvalidArgException ('text', $text);
2352 if (!array_key_exists ($nextpage, $page))
2353 throw new InvalidArgException ('nextpage', $nextpage);
2354 $args = array ('page' => $nextpage);
2355 if ($nexttab !== NULL)
2357 if (!array_key_exists ($nexttab, $tab[$nextpage]))
2358 throw new InvalidArgException ('nexttab', $nexttab);
2359 $args['tab'] = $nexttab;
2361 if (array_key_exists ('bypass', $page[$nextpage]))
2363 if ($bypass === NULL)
2364 throw new InvalidArgException ('bypass', $bypass);
2365 $args[$page[$nextpage]['bypass']] = $bypass;
2367 return '<a href="' . makeHref ($args) . '">' . $text . '</a>';
2370 function makeHref($params = array())
2372 $ret = 'index.php?';
2374 foreach($params as $key=>$value)
2378 $ret .= urlencode($key).'='.urlencode($value);
2384 function makeHrefProcess($params = array())
2386 global $pageno, $tabno;
2387 $ret = 'process.php?';
2389 if (!isset($params['page']))
2390 $params['page'] = $pageno;
2391 if (!isset($params['tab']))
2392 $params['tab'] = $tabno;
2393 foreach($params as $key=>$value)
2397 $ret .= urlencode($key).'='.urlencode($value);
2403 function makeHrefForHelper ($helper_name, $params = array())
2405 $ret = 'popup.php?helper=' . $helper_name;
2406 foreach($params as $key=>$value)
2407 $ret .= '&'.urlencode($key).'='.urlencode($value);
2411 // Process the given list of records to build data suitable for printNiftySelect()
2412 // (like it was formerly executed by printSelect()). Screen out vendors according
2413 // to VENDOR_SIEVE, if object type ID is provided. However, the OPTGROUP with already
2414 // selected OPTION is protected from being screened.
2415 function cookOptgroups ($recordList, $object_type_id = 0, $existing_value = 0)
2418 // Always keep "other" OPTGROUP at the SELECT bottom.
2420 foreach ($recordList as $dict_key => $dict_value)
2421 if (strpos ($dict_value, '%GSKIP%') !== FALSE)
2423 $tmp = explode ('%GSKIP%', $dict_value, 2);
2424 $ret[$tmp[0]][$dict_key] = $tmp[1];
2426 elseif (strpos ($dict_value, '%GPASS%') !== FALSE)
2428 $tmp = explode ('%GPASS%', $dict_value, 2);
2429 $ret[$tmp[0]][$dict_key] = $tmp[1];
2432 $therest[$dict_key] = $dict_value;
2433 if ($object_type_id != 0)
2435 $screenlist = array();
2436 foreach (explode (';', getConfigVar ('VENDOR_SIEVE')) as $sieve)
2437 if (preg_match ("/^([^@]+)(@${object_type_id})?\$/", trim ($sieve), $regs)){
2438 $screenlist[] = $regs[1];
2440 foreach (array_keys ($ret) as $vendor)
2441 if (in_array ($vendor, $screenlist))
2443 $ok_to_screen = TRUE;
2444 if ($existing_value)
2445 foreach (array_keys ($ret[$vendor]) as $recordkey)
2446 if ($recordkey == $existing_value)
2448 $ok_to_screen = FALSE;
2452 unset ($ret[$vendor]);
2455 $ret['other'] = $therest;
2459 function dos2unix ($text)
2461 return str_replace ("\r\n", "\n", $text);
2464 function unix2dos ($text)
2466 return str_replace ("\n", "\r\n", $text);
2469 function buildPredicateTable ($parsetree)
2472 foreach ($parsetree as $sentence)
2473 if ($sentence['type'] == 'SYNT_DEFINITION')
2474 $ret[$sentence['term']] = $sentence['definition'];
2475 // Now we have predicate table filled in with the latest definitions of each
2476 // particular predicate met. This isn't as chik, as on-the-fly predicate
2477 // overloading during allow/deny scan, but quite sufficient for this task.
2481 // Take a list of records and filter against given RackCode expression. Return
2482 // the original list intact, if there was no filter requested, but return an
2483 // empty list, if there was an error.
2484 function filterCellList ($list_in, $expression = array())
2486 if ($expression === NULL)
2488 if (!count ($expression))
2490 $list_out = array();
2491 foreach ($list_in as $item_key => $item_value)
2492 if (TRUE === judgeCell ($item_value, $expression))
2493 $list_out[$item_key] = $item_value;
2497 function eval_expression ($expr, $tagchain, $ptable, $silent = FALSE)
2499 $self = __FUNCTION__
;
2500 switch ($expr['type'])
2502 // Return true, if given tag is present on the tag chain.
2505 foreach ($tagchain as $tagInfo)
2506 if ($expr['load'] == $tagInfo['tag'])
2509 case 'LEX_PREDICATE': // Find given predicate in the symbol table and evaluate it.
2510 $pname = $expr['load'];
2511 if (!isset ($ptable[$pname]))
2514 showWarning ("Predicate '${pname}' is referenced before declaration");
2517 return $self ($ptable[$pname], $tagchain, $ptable);
2522 case 'SYNT_NOT_EXPR':
2523 $tmp = $self ($expr['load'], $tagchain, $ptable);
2526 elseif ($tmp === FALSE)
2530 case 'SYNT_AND_EXPR': // binary AND
2531 if (FALSE == $self ($expr['left'], $tagchain, $ptable))
2532 return FALSE; // early failure
2533 return $self ($expr['right'], $tagchain, $ptable);
2534 case 'SYNT_EXPR': // binary OR
2535 if (TRUE == $self ($expr['left'], $tagchain, $ptable))
2536 return TRUE; // early success
2537 return $self ($expr['right'], $tagchain, $ptable);
2540 showWarning ("Evaluation error, cannot process expression type '${expr['type']}'");
2546 // Tell, if the given expression is true for the given entity. Take complete record on input.
2547 function judgeCell ($cell, $expression)
2550 return eval_expression
2564 // Tell, if a constraint from config option permits given record.
2565 function considerConfiguredConstraint ($cell, $varname)
2567 if (!strlen (getConfigVar ($varname)))
2568 return TRUE; // no restriction
2570 if (!isset ($parseCache[$varname]))
2571 // getConfigVar() doesn't re-read the value from DB because of its
2572 // own cache, so there is no race condition here between two calls.
2573 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
2574 if ($parseCache[$varname]['result'] != 'ACK')
2575 return FALSE; // constraint set, but cannot be used due to compilation error
2576 return judgeCell ($cell, $parseCache[$varname]['load']);
2579 // Return list of records in the given realm, which conform to
2580 // the given RackCode expression. If the realm is unknown or text
2581 // doesn't validate as a RackCode expression, return NULL.
2582 // Otherwise (successful scan) return a list of all matched
2583 // records, even if the list is empty (array() !== NULL). If the
2584 // text is an empty string, return all found records in the given
2586 function scanRealmByText ($realm = NULL, $ftext = '')
2597 if (!strlen ($ftext = trim ($ftext)))
2601 $fparse = spotPayload ($ftext, 'SYNT_EXPR');
2602 if ($fparse['result'] != 'ACK')
2604 $fexpr = $fparse['load'];
2606 return filterCellList (listCells ($realm), $fexpr);
2608 throw new InvalidArgException ('$realm', $realm);
2613 function getIPv4VSOptions ()
2616 foreach (listCells ('ipv4vs') as $vsid => $vsinfo)
2617 $ret[$vsid] = $vsinfo['dname'] . (!strlen ($vsinfo['name']) ?
'' : " (${vsinfo['name']})");
2621 function getIPv4RSPoolOptions ()
2624 foreach (listCells ('ipv4rspool') as $pool_id => $poolInfo)
2625 $ret[$pool_id] = $poolInfo['name'];
2629 // Derive a complete cell structure from the given username regardless
2630 // if it is a local account or not.
2631 function constructUserCell ($username)
2633 if (NULL !== ($userid = getUserIDByUsername ($username)))
2634 return spotEntity ('user', $userid);
2638 'user_name' => $username,
2639 'user_realname' => '',
2643 $ret['atags'] = generateEntityAutoTags ($ret);
2647 // Let's have this debug helper here to enable debugging of process.php w/o interface.php.
2648 function dump ($var)
2650 echo '<div align=left><pre>';
2652 echo '</pre></div>';
2655 function getTagChart ($limit = 0, $realm = 'total', $special_tags = array())
2658 // first build top-N chart...
2660 foreach ($taglist as $taginfo)
2661 if (isset ($taginfo['refcnt'][$realm]))
2662 $toplist[$taginfo['id']] = $taginfo['refcnt'][$realm];
2663 arsort ($toplist, SORT_NUMERIC
);
2666 foreach (array_keys ($toplist) as $tag_id)
2668 $ret[$tag_id] = $taglist[$tag_id];
2669 if (++
$done == $limit)
2672 // ...then make sure, that every item of the special list is shown
2673 // (using the same sort order)
2675 foreach ($special_tags as $taginfo)
2676 if (!array_key_exists ($taginfo['id'], $ret))
2677 $extra[$taginfo['id']] = $taglist[$taginfo['id']]['refcnt'][$realm];
2678 arsort ($extra, SORT_NUMERIC
);
2679 foreach (array_keys ($extra) as $tag_id)
2680 $ret[] = $taglist[$tag_id];
2684 function decodeObjectType ($objtype_id, $style = 'r')
2686 static $types = array();
2687 if (!count ($types))
2690 'r' => readChapter (CHAP_OBJTYPE
),
2691 'a' => readChapter (CHAP_OBJTYPE
, 'a'),
2692 'o' => readChapter (CHAP_OBJTYPE
, 'o')
2694 return $types[$style][$objtype_id];
2697 function isolatedPermission ($p, $t, $cell)
2699 // This function is called from both "file" page and a number of other pages,
2700 // which have already fixed security context and authorized the user for it.
2701 // OTOH, it is necessary here to authorize against the current file, which
2702 // means saving the current context and building a new one.
2708 // push current context
2709 $orig_expl_tags = $expl_tags;
2710 $orig_impl_tags = $impl_tags;
2711 $orig_target_given_tags = $target_given_tags;
2712 $orig_auto_tags = $auto_tags;
2715 // remember decision
2716 $ret = permitted ($p, $t);
2718 $expl_tags = $orig_expl_tags;
2719 $impl_tags = $orig_impl_tags;
2720 $target_given_tags = $orig_target_given_tags;
2721 $auto_tags = $orig_auto_tags;
2725 function getPortListPrefs()
2728 if (0 >= ($ret['iif_pick'] = getConfigVar ('DEFAULT_PORT_IIF_ID')))
2729 $ret['iif_pick'] = 1;
2730 $ret['oif_picks'] = array();
2731 foreach (explode (';', getConfigVar ('DEFAULT_PORT_OIF_IDS')) as $tmp)
2733 $tmp = explode ('=', trim ($tmp));
2734 if (count ($tmp) == 2 and $tmp[0] > 0 and $tmp[1] > 0)
2735 $ret['oif_picks'][$tmp[0]] = $tmp[1];
2737 // enforce default value
2738 if (!array_key_exists (1, $ret['oif_picks']))
2739 $ret['oif_picks'][1] = 24;
2740 $ret['selected'] = $ret['iif_pick'] . '-' . $ret['oif_picks'][$ret['iif_pick']];
2744 // Return data for printNiftySelect() with port type options. All OIF options
2745 // for the default IIF will be shown, but only the default OIFs will be present
2746 // for each other IIFs. IIFs, for which there is no default OIF, will not
2748 // This SELECT will be used for the "add new port" form.
2749 function getNewPortTypeOptions()
2752 $prefs = getPortListPrefs();
2753 foreach (getPortInterfaceCompat() as $row)
2755 if ($row['iif_id'] == $prefs['iif_pick'])
2756 $optgroup = $row['iif_name'];
2757 elseif (array_key_exists ($row['iif_id'], $prefs['oif_picks']) and $prefs['oif_picks'][$row['iif_id']] == $row['oif_id'])
2758 $optgroup = 'other';
2761 if (!array_key_exists ($optgroup, $ret))
2762 $ret[$optgroup] = array();
2763 $ret[$optgroup][$row['iif_id'] . '-' . $row['oif_id']] = $row['oif_name'];
2768 // Return a serialized version of VLAN configuration for a port.
2769 // If a native VLAN is defined, print it first. All other VLANs
2770 // are tagged and are listed after a plus sign. When no configuration
2771 // is set for a port, return "default" string.
2772 function serializeVLANPack ($vlanport)
2774 if (!array_key_exists ('mode', $vlanport))
2776 switch ($vlanport['mode'])
2796 foreach ($vlanport['allowed'] as $vlan_id)
2797 if ($vlan_id != $vlanport['native'])
2798 $tagged[] = $vlan_id;
2800 $ret .= $vlanport['native'] ?
$vlanport['native'] : '';
2801 $tagged_bits = array();
2802 $id_from = $id_to = 0;
2803 foreach ($tagged as $next_id)
2807 if ($next_id == $id_to +
1) // merge
2813 $tagged_bits[] = $id_from == $id_to ?
$id_from : "${id_from}-${id_to}";
2815 $id_from = $id_to = $next_id; // start next pair
2819 $tagged_bits[] = $id_from == $id_to ?
$id_from : "${id_from}-${id_to}";
2820 if (count ($tagged))
2821 $ret .= '+' . implode (', ', $tagged_bits);
2822 return strlen ($ret) ?
$ret : 'default';
2825 // Decode VLAN compound key (which is a string formatted DOMAINID-VLANID) and
2826 // return the numbers as an array of two.
2827 function decodeVLANCK ($string)
2830 if (1 != preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $string, $matches))
2831 throw new InvalidArgException ('VLAN compound key', $string);
2832 return array ($matches[1], $matches[2]);
2835 // Return VLAN name formatted for HTML output (note, that input
2836 // argument comes from database unescaped).
2837 function formatVLANName ($vlaninfo, $context = 'markup long')
2842 $ret = $vlaninfo['vlan_id'];
2843 if ($vlaninfo['vlan_descr'] != '')
2844 $ret .= ' ' . niftyString ($vlaninfo['vlan_descr']);
2847 $ret = $vlaninfo['vlan_id'];
2848 if ($vlaninfo['vlan_descr'] != '')
2849 $ret .= ' <i>(' . niftyString ($vlaninfo['vlan_descr']) . ')</i>';
2852 $ret = 'VLAN' . $vlaninfo['vlan_id'];
2853 if ($vlaninfo['vlan_descr'] != '')
2854 $ret .= ' (' . niftyString ($vlaninfo['vlan_descr'], 20, FALSE) . ')';
2858 $ret .= makeHref (array ('page' => 'vlan', 'vlan_ck' => $vlaninfo['domain_id'] . '-' . $vlaninfo['vlan_id']));
2859 $ret .= '">' . formatVLANName ($vlaninfo, 'markup long') . '</a>';
2863 $ret = 'VLAN' . $vlaninfo['vlan_id'];
2864 $ret .= ' @' . niftyString ($vlaninfo['domain_descr']);
2865 if ($vlaninfo['vlan_descr'] != '')
2866 $ret .= ' <i>(' . niftyString ($vlaninfo['vlan_descr']) . ')</i>';
2871 // map interface name
2872 function ios12ShortenIfName ($ifname)
2874 $ifname = preg_replace ('@^Eth(?:ernet)?(.+)$@', 'e\\1', $ifname);
2875 $ifname = preg_replace ('@^FastEthernet(.+)$@', 'fa\\1', $ifname);
2876 $ifname = preg_replace ('@^(?:GigabitEthernet|GE)(.+)$@', 'gi\\1', $ifname);
2877 $ifname = preg_replace ('@^TenGigabitEthernet(.+)$@', 'te\\1', $ifname);
2878 $ifname = preg_replace ('@^Port-channel(.+)$@', 'po\\1', $ifname);
2879 $ifname = preg_replace ('@^(?:XGigabitEthernet|XGE)(.+)$@', 'xg\\1', $ifname);
2880 $ifname = strtolower ($ifname);
2884 function iosParseVLANString ($string)
2887 foreach (explode (',', $string) as $item)
2890 $item = trim ($item, ' ');
2891 if (preg_match ('/^([[:digit:]]+)$/', $item, $matches))
2892 $ret[] = $matches[1];
2893 elseif (preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $item, $matches))
2894 $ret = array_merge ($ret, range ($matches[1], $matches[2]));
2899 // Scan given array and return the key, which addresses the first item
2900 // with requested column set to given value (or NULL if there is none such).
2901 // Note that 0 and NULL mean completely different things and thus
2902 // require strict checking (=== and !===).
2903 function scanArrayForItem ($table, $scan_column, $scan_value)
2905 foreach ($table as $key => $row)
2906 if ($row[$scan_column] == $scan_value)
2911 // Return TRUE, if every value of A1 is present in A2 and vice versa,
2912 // regardless of each array's sort order and indexing.
2913 function array_values_same ($a1, $a2)
2915 return !count (array_diff ($a1, $a2)) and !count (array_diff ($a2, $a1));
2918 // Use the VLAN switch template to set VST role for each port of
2919 // the provided list. Return resulting list.
2920 function apply8021QOrder ($vst_id, $portlist)
2922 $vst = getVLANSwitchTemplate ($vst_id);
2923 foreach (array_keys ($portlist) as $port_name)
2925 foreach ($vst['rules'] as $rule)
2926 if (preg_match ($rule['port_pcre'], $port_name))
2928 $portlist[$port_name]['vst_role'] = $rule['port_role'];
2929 $portlist[$port_name]['wrt_vlans'] = buildVLANFilter ($rule['port_role'], $rule['wrt_vlans']);
2932 $portlist[$port_name]['vst_role'] = 'none';
2937 // return a sequence of ranges for given string form and port role
2938 function buildVLANFilter ($role, $string)
2943 case 'access': // 1-4094
2947 case 'trunk': // 2-4094
2951 $min = VLAN_MIN_ID +
1;
2957 if ($string == '') // fast track
2958 return array (array ('from' => $min, 'to' => $max));
2960 $vlanidlist = array();
2961 foreach (iosParseVLANString ($string) as $vlan_id)
2962 if ($min <= $vlan_id and $vlan_id <= $max)
2963 $vlanidlist[] = $vlan_id;
2964 return listToRanges ($vlanidlist);
2967 // pack set of integers into list of integer ranges
2968 // e.g. (1, 2, 3, 5, 6, 7, 9, 11) => ((1, 3), (5, 7), (9, 9), (11, 11))
2969 // The second argument, when it is different from 0, limits amount of
2970 // items in each generated range.
2971 function listToRanges ($vlanidlist, $limit = 0)
2976 foreach ($vlanidlist as $vlan_id)
2980 $ret[] = array ('from' => $vlan_id, 'to' => $vlan_id);
2982 $from = $to = $vlan_id;
2984 elseif ($to +
1 == $vlan_id)
2987 if ($to - $from +
1 == $limit)
2989 // cut accumulated range and start over
2990 $ret[] = array ('from' => $from, 'to' => $to);
2996 $ret[] = array ('from' => $from, 'to' => $to);
2997 $from = $to = $vlan_id;
3000 $ret[] = array ('from' => $from, 'to' => $to);
3004 // return TRUE, if given VLAN ID belongs to one of filter's ranges
3005 function matchVLANFilter ($vlan_id, $vfilter)
3007 foreach ($vfilter as $range)
3008 if ($range['from'] <= $vlan_id and $vlan_id <= $range['to'])
3013 function generate8021QDeployOps ($domain_vlanlist, $device_vlanlist, $before, $changes)
3015 // only ignore VLANs, which exist and are explicitly shown as "alien"
3016 $old_managed_vlans = array();
3017 foreach ($device_vlanlist as $vlan_id)
3020 !array_key_exists ($vlan_id, $domain_vlanlist) or
3021 $domain_vlanlist[$vlan_id]['vlan_type'] != 'alien'
3023 $old_managed_vlans[] = $vlan_id;
3024 $ports_to_do = array();
3026 foreach ($changes as $port_name => $port)
3028 $ports_to_do[$port_name] = array
3030 'old_mode' => $before[$port_name]['mode'],
3031 'old_allowed' => $before[$port_name]['allowed'],
3032 'old_native' => $before[$port_name]['native'],
3033 'new_mode' => $port['mode'],
3034 'new_allowed' => $port['allowed'],
3035 'new_native' => $port['native'],
3037 $after[$port_name] = $port;
3039 // New VLAN table is a union of:
3040 // 1. all compulsory VLANs
3041 // 2. all "current" non-alien allowed VLANs of those ports, which are left
3042 // intact (regardless if a VLAN exists in VLAN domain, but looking,
3043 // if it is present in device's own VLAN table)
3044 // 3. all "new" allowed VLANs of those ports, which we do "push" now
3045 // Like for old_managed_vlans, a VLANs is never listed, only if it
3046 // exists and belongs to "alien" type.
3047 $new_managed_vlans = array();
3049 foreach ($domain_vlanlist as $vlan_id => $vlan)
3050 if ($vlan['vlan_type'] == 'compulsory')
3051 $new_managed_vlans[] = $vlan_id;
3053 foreach ($before as $port_name => $port)
3054 if (!array_key_exists ($port_name, $changes))
3055 foreach ($port['allowed'] as $vlan_id)
3057 if (in_array ($vlan_id, $new_managed_vlans))
3061 array_key_exists ($vlan_id, $domain_vlanlist) and
3062 $domain_vlanlist[$vlan_id]['vlan_type'] == 'alien'
3065 if (in_array ($vlan_id, $device_vlanlist))
3066 $new_managed_vlans[] = $vlan_id;
3069 foreach ($changes as $port)
3070 foreach ($port['allowed'] as $vlan_id)
3073 $domain_vlanlist[$vlan_id]['vlan_type'] == 'ondemand' and
3074 !in_array ($vlan_id, $new_managed_vlans)
3076 $new_managed_vlans[] = $vlan_id;
3078 // Before removing each old VLAN as such it is necessary to unassign
3079 // ports from it (to remove VLAN from each ports' list of "allowed"
3080 // VLANs). This change in turn requires, that a port's "native"
3081 // VLAN isn't set to the one being removed from its "allowed" list.
3082 foreach ($ports_to_do as $port_name => $port)
3083 switch ($port['old_mode'] . '->' . $port['new_mode'])
3085 case 'trunk->trunk':
3086 // "old" native is set and differs from the "new" native
3087 if ($port['old_native'] and $port['old_native'] != $port['new_native'])
3090 'opcode' => 'unset native',
3091 'arg1' => $port_name,
3092 'arg2' => $port['old_native'],
3094 if (count ($tmp = array_diff ($port['old_allowed'], $port['new_allowed'])))
3097 'opcode' => 'rem allowed',
3098 'port' => $port_name,
3102 case 'access->access':
3103 if ($port['old_native'] and $port['old_native'] != $port['new_native'])
3106 'opcode' => 'unset access',
3107 'arg1' => $port_name,
3108 'arg2' => $port['old_native'],
3111 case 'access->trunk':
3114 'opcode' => 'unset access',
3115 'arg1' => $port_name,
3116 'arg2' => $port['old_native'],
3119 case 'trunk->access':
3120 if ($port['old_native'])
3123 'opcode' => 'unset native',
3124 'arg1' => $port_name,
3125 'arg2' => $port['old_native'],
3127 if (count ($port['old_allowed']))
3130 'opcode' => 'rem allowed',
3131 'port' => $port_name,
3132 'vlans' => $port['old_allowed'],
3136 throw new InvalidArgException ('ports_to_do', '(hidden)', 'error in structure');
3138 // Now it is safe to unconfigure VLANs, which still exist on device,
3139 // but are not present on the "new" list.
3140 // FIXME: put all IDs into one pseudo-command to make it easier
3141 // for translators to create/destroy VLANs in batches, where
3142 // target platform allows them to do.
3143 foreach (array_diff ($old_managed_vlans, $new_managed_vlans) as $vlan_id)
3146 'opcode' => 'destroy VLAN',