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 // Objects of some types should be explicitly shown as
28 // anonymous (labelless). This function is a single place where the
29 // decision about displayed name is made.
30 function displayedName ($objectData)
32 if ($objectData['name'] != '')
33 return $objectData['name'];
34 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
35 return "ANONYMOUS " . $objectData['objtype_name'];
37 return "[${objectData['objtype_name']}]";
40 // This function finds height of solid rectangle of atoms, which are all
41 // assigned to the same object. Rectangle base is defined by specified
43 function rectHeight ($rackData, $startRow, $template_idx)
46 // The first met object_id is used to match all the folowing IDs.
51 for ($locidx = 0; $locidx < 3; $locidx++
)
53 // At least one value in template is TRUE, but the following block
54 // can meet 'skipped' atoms. Let's ensure we have something after processing
56 if ($template[$template_idx][$locidx])
58 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
60 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
62 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
64 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
67 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
68 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
72 // If the first row can't offer anything, bail out.
73 if ($height == 0 and $object_id == 0)
77 while ($startRow - $height > 0);
78 # echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
79 # echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
80 # echo ") height==${height}<br>\n";
84 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
86 function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
88 global $template, $templateWidth;
90 for ($height = 0; $height < $maxheight; $height++
)
92 for ($locidx = 0; $locidx < 3; $locidx++
)
94 if ($template[$template_idx][$locidx])
96 // Add colspan/rowspan to the first row met and mark the following ones to skip.
97 // Explicitly show even single-cell spanned atoms, because rectHeight()
98 // is expeciting this data for correct calculation.
100 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
103 $colspan = $templateWidth[$template_idx];
105 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
107 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
115 // This function sets rowspan/solspan/skipped atom attributes for renderRack()
116 // What we actually have to do is to find _all_ possible rectangles for each unit
117 // and then select the widest of those with the maximal square.
118 function markAllSpans (&$rackData = NULL)
120 if ($rackData == NULL)
122 showError ('Invalid rackData', __FUNCTION__
);
125 for ($i = $rackData['height']; $i > 0; $i--)
126 while (markBestSpan ($rackData, $i));
129 // Calculate height of 6 possible span templates (array is presorted by width
130 // descending) and mark the best (if any).
131 function markBestSpan (&$rackData, $i)
133 global $template, $templateWidth;
134 for ($j = 0; $j < 6; $j++
)
136 $height[$j] = rectHeight ($rackData, $i, $j);
137 $square[$j] = $height[$j] * $templateWidth[$j];
139 // find the widest rectangle of those with maximal height
140 $maxsquare = max ($square);
143 $best_template_index = 0;
144 for ($j = 0; $j < 6; $j++
)
145 if ($square[$j] == $maxsquare)
147 $best_template_index = $j;
148 $bestheight = $height[$j];
151 // distribute span marks
152 markSpan ($rackData, $i, $bestheight, $best_template_index);
156 // We can mount 'F' atoms and unmount our own 'T' atoms.
157 function applyObjectMountMask (&$rackData, $object_id)
159 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
160 for ($locidx = 0; $locidx < 3; $locidx++
)
161 switch ($rackData[$unit_no][$locidx]['state'])
164 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
167 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
170 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
174 // Design change means transition between 'F' and 'A' and back.
175 function applyRackDesignMask (&$rackData)
177 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
178 for ($locidx = 0; $locidx < 3; $locidx++
)
179 switch ($rackData[$unit_no][$locidx]['state'])
183 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
186 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
190 // The same for 'F' and 'U'.
191 function applyRackProblemMask (&$rackData)
193 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
194 for ($locidx = 0; $locidx < 3; $locidx++
)
195 switch ($rackData[$unit_no][$locidx]['state'])
199 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
202 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
206 // This mask should allow toggling 'T' and 'W' on object's rackspace.
207 function applyObjectProblemMask (&$rackData)
209 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
210 for ($locidx = 0; $locidx < 3; $locidx++
)
211 switch ($rackData[$unit_no][$locidx]['state'])
215 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
218 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
222 // This function highlights specified object (and removes previous highlight).
223 function highlightObject (&$rackData, $object_id)
225 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
226 for ($locidx = 0; $locidx < 3; $locidx++
)
229 $rackData[$unit_no][$locidx]['state'] == 'T' and
230 $rackData[$unit_no][$locidx]['object_id'] == $object_id
232 $rackData[$unit_no][$locidx]['hl'] = 'h';
234 unset ($rackData[$unit_no][$locidx]['hl']);
237 // This function marks atoms to selected or not depending on their current state.
238 function markupAtomGrid (&$data, $checked_state)
240 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
241 for ($locidx = 0; $locidx < 3; $locidx++
)
243 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
245 if ($data[$unit_no][$locidx]['state'] == $checked_state)
246 $data[$unit_no][$locidx]['checked'] = ' checked';
248 $data[$unit_no][$locidx]['checked'] = '';
252 // This function is almost a clone of processGridForm(), but doesn't save anything to database
253 // Return value is the changed rack data.
254 // Here we assume that correct filter has already been applied, so we just
255 // set or unset checkbox inputs w/o changing atom state.
256 function mergeGridFormToRack (&$rackData)
258 $rack_id = $rackData['id'];
259 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
260 for ($locidx = 0; $locidx < 3; $locidx++
)
262 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
264 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
265 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
266 $rackData[$unit_no][$locidx]['checked'] = ' checked';
268 $rackData[$unit_no][$locidx]['checked'] = '';
272 // netmask conversion from length to number
273 function binMaskFromDec ($maskL)
275 $map_straight = array (
310 return $map_straight[$maskL];
313 // complementary value
314 function binInvMaskFromDec ($maskL)
351 return $map_compl[$maskL];
354 // This function looks up 'has_problems' flag for 'T' atoms
355 // and modifies 'hl' key. May be, this should be better done
356 // in getRackData(). We don't honour 'skipped' key, because
357 // the function is also used for thumb creation.
358 function markupObjectProblems (&$rackData)
360 for ($i = $rackData['height']; $i > 0; $i--)
361 for ($locidx = 0; $locidx < 3; $locidx++
)
362 if ($rackData[$i][$locidx]['state'] == 'T')
364 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
365 if ($object['has_problems'] == 'yes')
367 // Object can be already highlighted.
368 if (isset ($rackData[$i][$locidx]['hl']))
369 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
371 $rackData[$i][$locidx]['hl'] = 'w';
376 function search_cmpObj ($a, $b)
378 return ($a['score'] > $b['score'] ?
-1 : 1);
381 function getObjectSearchResults ($terms)
384 mergeSearchResults ($objects, $terms, 'name');
385 mergeSearchResults ($objects, $terms, 'label');
386 mergeSearchResults ($objects, $terms, 'asset_no');
387 mergeSearchResults ($objects, $terms, 'barcode');
388 if (count ($objects) == 1)
389 usort ($objects, 'search_cmpObj');
393 // This function removes all colons and dots from a string.
394 function l2addressForDatabase ($string)
398 $pieces = explode (':', $string);
399 // This workaround is for SunOS ifconfig.
400 foreach ($pieces as &$byte)
401 if (strlen ($byte) == 1)
403 // And this workaround is for PHP.
405 $string = implode ('', $pieces);
406 $pieces = explode ('.', $string);
407 $string = implode ('', $pieces);
408 $string = strtoupper ($string);
412 function l2addressFromDatabase ($string)
414 switch (strlen ($string))
418 $ret = implode (':', str_split ($string, 2));
427 // The following 2 functions return previous and next rack IDs for
428 // a given rack ID. The order of racks is the same as in renderRackspace()
430 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
432 if ($row_id <= 0 or $rack_id <= 0)
434 showError ('Invalid arguments passed', __FUNCTION__
);
437 $rackList = getRacksForRow ($row_id);
438 doubleLink ($rackList);
439 if (isset ($rackList[$rack_id]['prev_key']))
440 return $rackList[$rack_id]['prev_key'];
444 function getNextIDforRack ($row_id = 0, $rack_id = 0)
446 if ($row_id <= 0 or $rack_id <= 0)
448 showError ('Invalid arguments passed', __FUNCTION__
);
451 $rackList = getRacksForRow ($row_id);
452 doubleLink ($rackList);
453 if (isset ($rackList[$rack_id]['next_key']))
454 return $rackList[$rack_id]['next_key'];
458 // This function finds previous and next array keys for each array key and
459 // modifies its argument accordingly.
460 function doubleLink (&$array)
463 foreach (array_keys ($array) as $key)
467 $array[$key]['prev_key'] = $prev_key;
468 $array[$prev_key]['next_key'] = $key;
474 // After applying usort() to a rack list we will lose original array keys.
475 // This function restores the keys so they are equal to rack IDs.
476 function restoreRackIDs ($racks)
479 foreach ($racks as $rack)
480 $ret[$rack['id']] = $rack;
484 function sortTokenize ($a, $b)
490 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
491 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
492 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
499 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
500 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
501 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
506 $ar = explode(' ', $a);
507 $br = explode(' ', $b);
508 for ($i=0; $i<count($ar) && $i<count($br); $i++
)
511 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
512 $ret = ($ar[$i]==$br[$i])?
0:($ar[$i]<$br[$i]?
-1:1);
514 $ret = strcasecmp($ar[$i], $br[$i]);
525 function sortByName ($a, $b)
527 return sortTokenize($a['name'], $b['name']);
530 function sortRacks ($a, $b)
532 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
535 function sortEmptyPorts ($a, $b)
537 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
538 if ($objname_cmp == 0)
540 return sortTokenize($a['Port_name'], $b['Port_name']);
545 function sortObjectAddressesAndNames ($a, $b)
547 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
548 if ($objname_cmp == 0)
550 $name_a = (isset ($a['port_name'])) ?
$a['port_name'] : '';
551 $name_b = (isset ($b['port_name'])) ?
$b['port_name'] : '';
552 $objname_cmp = sortTokenize($name_a, $name_b);
553 if ($objname_cmp == 0)
554 sortTokenize($a['ip'], $b['ip']);
560 function sortAddresses ($a, $b)
562 $name_cmp = sortTokenize($a['name'], $b['name']);
565 return sortTokenize($a['ip'], $b['ip']);
570 // This function expands port compat list into a matrix.
571 function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
574 // Create type matrix and markup compatible types.
575 foreach (array_keys ($portTypeList) as $type1)
576 foreach (array_keys ($portTypeList) as $type2)
577 $matrix[$type1][$type2] = FALSE;
578 foreach ($portCompatList as $pair)
579 $matrix[$pair['type1']][$pair['type2']] = TRUE;
583 // This function returns an array of single element of object's FQDN attribute,
584 // if FQDN is set. The next choice is object's common name, if it looks like a
585 // hostname. Otherwise an array of all 'regular' IP addresses of the
586 // object is returned (which may appear 0 and more elements long).
587 function findAllEndpoints ($object_id, $fallback = '')
589 $values = getAttrValues ($object_id);
590 foreach ($values as $record)
591 if ($record['name'] == 'FQDN' && !empty ($record['value']))
592 return array ($record['value']);
594 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
595 if ($alloc['type'] == 'regular')
596 $regular[] = $dottedquad;
597 if (!count ($regular) && !empty ($fallback))
598 return array ($fallback);
602 // Some records in the dictionary may be written as plain text or as Wiki
603 // link in the following syntax:
605 // 2. [[word URL]] // FIXME: this isn't working
606 // 3. [[word word word | URL]]
607 // This function parses the line and returns text suitable for either A
608 // (rendering <A HREF>) or O (for <OPTION>).
609 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
611 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
614 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
618 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
619 $s = explode ('|', $line);
620 $o_value = trim ($s[0]);
622 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
623 $a_value = trim ($s[1]);
625 return "<a href='${a_value}'>${o_value}</a>";
630 function buildVServiceName ($vsinfo = NULL)
634 showError ('NULL argument', __FUNCTION__
);
637 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
640 function buildRSPoolName ($rspool = NULL)
644 showError ('NULL argument', __FUNCTION__
);
647 return strlen ($rspool['name']) ?
$rspool['name'] : 'ANONYMOUS pool';
650 // rackspace usage for a single rack
651 // (T + W + U) / (height * 3 - A)
652 function getRSUforRack ($data = NULL)
656 showError ('Invalid argument', __FUNCTION__
);
659 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
660 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
661 for ($locidx = 0; $locidx < 3; $locidx++
)
662 $counter[$data[$unit_no][$locidx]['state']]++
;
663 return ($counter['T'] +
$counter['W'] +
$counter['U']) / ($counter['T'] +
$counter['W'] +
$counter['U'] +
$counter['F']);
667 function getRSUforRackRow ($rowData = NULL)
669 if ($rowData === NULL)
671 showError ('Invalid argument', __FUNCTION__
);
674 if (!count ($rowData))
676 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
678 foreach (array_keys ($rowData) as $rack_id)
680 $data = getRackData ($rack_id);
681 $total_height +
= $data['height'];
682 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
683 for ($locidx = 0; $locidx < 3; $locidx++
)
684 $counter[$data[$unit_no][$locidx]['state']]++
;
686 return ($counter['T'] +
$counter['W'] +
$counter['U']) / ($counter['T'] +
$counter['W'] +
$counter['U'] +
$counter['F']);
689 // Return a list of object IDs, which can be found in the given rackspace block.
690 function stuffInRackspace ($rackData)
693 for ($i = $rackData['height']; $i > 0; $i--)
694 for ($locidx = 0; $locidx < 3; $locidx++
)
697 $rackData[$i][$locidx]['state'] == 'T' and
698 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
700 $objects[] = $rackData[$i][$locidx]['object_id'];
704 // Make sure the string is always wrapped with LF characters
705 function lf_wrap ($str)
707 $ret = trim ($str, "\r\n");
713 // Adopted from Mantis BTS code.
714 function string_insert_hrefs ($s)
716 if (getConfigVar ('DETECT_URLS') != 'yes')
718 # Find any URL in a string and replace it by a clickable link
719 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
720 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
722 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
723 '<a href="mailto:\0">\0</a>',
729 function email_regex_simple ()
731 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
732 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
735 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
736 // for the requested object_type_id.
737 function getAutoPorts ($type_id)
740 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
741 foreach ($typemap as $equation)
743 $tmp = explode ('=', $equation);
744 if (count ($tmp) != 2)
746 $objtype_id = $tmp[0];
747 if ($objtype_id != $type_id)
750 foreach (explode ('+', $portlist) as $product)
752 $tmp = explode ('*', $product);
753 if (count ($tmp) != 3)
756 $port_type = $tmp[1];
758 for ($i = 0; $i < $nports; $i++
)
759 $ret[] = array ('type' => $port_type, 'name' => @sprintf
($format, $i));
765 // Find if a particular tag id exists on the tree, then attach the
766 // given child tag to it. If the parent tag doesn't exist, return FALSE.
767 function attachChildTag (&$tree, $parent_id, $child_id, $child_info, $threshold = 0)
769 $self = __FUNCTION__
;
770 foreach ($tree as $tagid => $taginfo)
772 if ($tagid == $parent_id)
774 if (!$threshold or ($threshold and $tree[$tagid]['kidc'] +
1 < $threshold))
775 $tree[$tagid]['kids'][$child_id] = $child_info;
776 // Reset the list only once.
777 if (++
$tree[$tagid]['kidc'] == $threshold)
778 $tree[$tagid]['kids'] = array();
781 elseif ($self ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info, $threshold))
787 // Build a tree from the item list and return it. Input and output data is
788 // indexed by item id (nested items in output are recursively stored in 'kids'
789 // key, which is in turn indexed by id. Functions, which are ready to handle
790 // tree collapsion/expansion themselves, may request non-zero threshold value
791 // for smaller resulting tree.
792 function treeFromList ($mytaglist, $threshold = 0)
795 while (count ($mytaglist) > 0)
798 foreach ($mytaglist as $tagid => $taginfo)
800 $taginfo['kidc'] = 0;
801 $taginfo['kids'] = array();
802 if ($taginfo['parent_id'] == NULL)
804 $ret[$tagid] = $taginfo;
806 unset ($mytaglist[$tagid]);
808 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo, $threshold))
811 unset ($mytaglist[$tagid]);
814 if (!$picked) // Only orphaned items on the list.
820 // Build a tree from the tag list and return everything _except_ the tree.
821 function getOrphanedTags ()
824 $mytaglist = $taglist;
826 while (count ($mytaglist) > 0)
829 foreach ($mytaglist as $tagid => $taginfo)
831 $taginfo['kids'] = array();
832 if ($taginfo['parent_id'] == NULL)
834 $dummy[$tagid] = $taginfo;
836 unset ($mytaglist[$tagid]);
838 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
841 unset ($mytaglist[$tagid]);
844 if (!$picked) // Only orphaned items on the list.
850 function serializeTags ($chain, $baseurl = '')
854 foreach ($chain as $taginfo)
857 ($baseurl == '' ?
'' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
859 ($baseurl == '' ?
'' : '</a>');
865 // a helper for getTagChainExpansion()
866 function traceTagChain ($tree, $chain)
868 $self = __FUNCTION__
;
869 // For each tag find its path from the root, then combine items
870 // of all paths and add them to the chain, if they aren't there yet.
872 foreach ($tree as $taginfo1)
875 foreach ($chain as $taginfo2)
876 if ($taginfo1['id'] == $taginfo2['id'])
881 if (count ($taginfo1['kids']) > 0)
883 $subsearch = $self ($taginfo1['kids'], $chain);
884 if (count ($subsearch))
887 $ret = array_merge ($ret, $subsearch);
896 // For each tag add all its parent tags onto the list. Don't expect anything
897 // except user's tags on the chain.
898 function getTagChainExpansion ($chain)
901 return traceTagChain ($tagtree, $chain);
904 // Return the list of missing implicit tags.
905 function getImplicitTags ($oldtags)
908 $newtags = getTagChainExpansion ($oldtags);
909 foreach ($newtags as $newtag)
911 $already_exists = FALSE;
912 foreach ($oldtags as $oldtag)
913 if ($newtag['id'] == $oldtag['id'])
915 $already_exists = TRUE;
920 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
925 // Minimize the chain: exclude all implicit tags and return the result.
926 function getExplicitTagsOnly ($chain, $tree = NULL)
928 $self = __FUNCTION__
;
933 foreach ($tree as $taginfo)
935 if (isset ($taginfo['kids']))
937 $harvest = $self ($chain, $taginfo['kids']);
938 if (count ($harvest) > 0)
940 $ret = array_merge ($ret, $harvest);
944 // This tag isn't implicit, test is for being explicit.
945 foreach ($chain as $testtag)
946 if ($taginfo['id'] == $testtag['id'])
955 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
956 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
957 // a list of tag structures. Same structure (tag ID list) is returned after processing.
958 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
960 $self = __FUNCTION__
;
964 $getallkids = $getall;
966 foreach ($tree as $taginfo)
968 foreach ($idlist as $test_id)
969 if ($getall or $taginfo['id'] == $test_id)
971 $ret[] = $taginfo['id'];
972 // Once matched node makes all sub-nodes match, but don't make
973 // a mistake of matching every other node at the current level.
977 if (isset ($taginfo['kids']))
978 $ret = array_merge ($ret, $self ($idlist, $taginfo['kids'], $getallkids));
984 function getUserAutoTags ($username = NULL)
986 global $remote_username, $accounts;
987 if ($username == NULL)
988 $username = $remote_username;
990 $ret[] = array ('tag' => '$username_' . $username);
991 if (isset ($accounts[$username]['user_id']))
992 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
996 function loadRackObjectAutoTags ()
998 assertUIntArg ('object_id', __FUNCTION__
);
999 $object_id = $_REQUEST['object_id'];
1000 $oinfo = getObjectInfo ($object_id);
1002 $ret[] = array ('tag' => '$id_' . $object_id);
1003 $ret[] = array ('tag' => '$typeid_' . $oinfo['objtype_id']);
1004 $ret[] = array ('tag' => '$any_object');
1005 if (validTagName ($oinfo['name']))
1006 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
1010 // Common code for both prefix and address tag listers.
1011 function getIPv4PrefixTags ($netid)
1013 $netinfo = getIPv4NetworkInfo ($netid);
1015 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $netinfo['ip']) . '-' . $netinfo['mask']);
1016 // FIXME: find and list tags for all parent networks?
1017 $ret[] = array ('tag' => '$any_ip4net');
1018 $ret[] = array ('tag' => '$any_net');
1022 function loadIPv4PrefixAutoTags ()
1024 assertUIntArg ('id', __FUNCTION__
);
1027 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
1028 getIPv4PrefixTags ($_REQUEST['id'])
1032 function loadIPv4AddressAutoTags ()
1034 assertIPv4Arg ('ip', __FUNCTION__
);
1037 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
1038 getIPv4PrefixTags (getIPv4AddressNetworkId ($_REQUEST['ip']))
1042 function loadRackAutoTags ()
1044 assertUIntArg ('rack_id', __FUNCTION__
);
1046 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
1047 $ret[] = array ('tag' => '$any_rack');
1051 function loadIPv4VSAutoTags ()
1053 assertUIntArg ('vs_id', __FUNCTION__
);
1055 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
1056 $ret[] = array ('tag' => '$any_ipv4vs');
1057 $ret[] = array ('tag' => '$any_vs');
1061 function loadIPv4RSPoolAutoTags ()
1063 assertUIntArg ('pool_id', __FUNCTION__
);
1065 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1066 $ret[] = array ('tag' => '$any_ipv4rsp');
1067 $ret[] = array ('tag' => '$any_rsp');
1071 // Check, if the given tag is present on the chain (will only work
1072 // for regular tags with tag ID set.
1073 function tagOnChain ($taginfo, $tagchain)
1075 if (!isset ($taginfo['id']))
1077 foreach ($tagchain as $test)
1078 if ($test['id'] == $taginfo['id'])
1083 // Idem, but use ID list instead of chain.
1084 function tagOnIdList ($taginfo, $tagidlist)
1086 if (!isset ($taginfo['id']))
1088 foreach ($tagidlist as $tagid)
1089 if ($taginfo['id'] == $tagid)
1094 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1095 // Assume, that neither of the lists contains duplicates.
1096 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1097 function tagChainCmp ($chain1, $chain2)
1099 if (count ($chain1) != count ($chain2))
1101 foreach ($chain1 as $taginfo1)
1102 if (!tagOnChain ($taginfo1, $chain2))
1107 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1108 // hold all appropriate (explicit and implicit) tags respectively.
1109 // Otherwise some limited redirection is necessary (only page and tab
1110 // names are preserved, ophandler name change isn't handled).
1111 function fixContext ()
1113 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
1117 'accounts' => 'userlist',
1118 'rspools' => 'ipv4rsplist',
1119 'rspool' => 'ipv4rsp',
1120 'vservices' => 'ipv4vslist',
1121 'vservice' => 'ipv4vs',
1124 $tmap['objects']['newmulti'] = 'addmore';
1125 $tmap['objects']['newobj'] = 'addmore';
1126 $tmap['object']['switchvlans'] = 'livevlans';
1127 $tmap['object']['slb'] = 'editrspvs';
1128 $tmap['object']['portfwrd'] = 'nat4';
1129 $tmap['object']['network'] = 'ipv4';
1130 if (isset ($pmap[$pageno]))
1131 redirectUser ($pmap[$pageno], $tabno);
1132 if (isset ($tmap[$pageno][$tabno]))
1133 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1135 if (isset ($page[$pageno]['autotagloader']))
1136 $auto_tags = $page[$pageno]['autotagloader'] ();
1139 isset ($page[$pageno]['tagloader']) and
1140 isset ($page[$pageno]['bypass']) and
1141 isset ($_REQUEST[$page[$pageno]['bypass']])
1144 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1145 $impl_tags = getImplicitTags ($expl_tags);
1149 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1150 // records indexed by tag IDs (tag chain).
1151 function buildTagChainFromIds ($tagidlist)
1155 foreach (array_unique ($tagidlist) as $tag_id)
1156 if (isset ($taglist[$tag_id]))
1157 $ret[] = $taglist[$tag_id];
1161 // Process a given tag tree and return only meaningful branches. The resulting
1162 // (sub)tree will have refcnt leaves on every last branch.
1163 function getObjectiveTagTree ($tree, $realm)
1165 $self = __FUNCTION__
;
1167 foreach ($tree as $taginfo)
1169 $subsearch = array();
1171 if (count ($taginfo['kids']))
1173 $subsearch = $self ($taginfo['kids'], $realm);
1174 $pick = count ($subsearch) > 0;
1176 if (isset ($taginfo['refcnt'][$realm]))
1182 'id' => $taginfo['id'],
1183 'tag' => $taginfo['tag'],
1184 'parent_id' => $taginfo['parent_id'],
1185 'refcnt' => $taginfo['refcnt'],
1186 'kids' => $subsearch
1192 function getTagFilter ()
1194 return isset ($_REQUEST['tagfilter']) ?
complementByKids ($_REQUEST['tagfilter']) : array();
1197 function getTagFilterStr ($tagfilter = array())
1200 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
1201 $ret .= "&tagfilter[]=" . $taginfo['id'];
1205 function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
1207 global $root, $page, $pageno, $tabno;
1208 if ($nextpage === NULL)
1209 $nextpage = $pageno;
1210 if ($nexttab === NULL)
1212 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1213 if (isset ($page[$nextpage]['bypass']))
1214 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
1215 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
1219 function buildRedirectURL ($status, $args = array(), $nextpage = NULL, $nexttab = NULL)
1221 global $msgcode, $pageno, $tabno, $op;
1222 if ($nextpage === NULL)
1223 $nextpage = $pageno;
1224 if ($nexttab === NULL)
1226 return buildWideRedirectURL (oneLiner ($msgcode[$pageno][$tabno][$op][$status], $args), $nextpage, $nexttab);
1229 // Return a message log consisting of only one message.
1230 function oneLiner ($code, $args = array())
1232 $ret = array ('v' => 2);
1233 $ret['m'][] = count ($args) ?
array ('c' => $code, 'a' => $args) : array ('c' => $code);
1237 // Return mesage code by status code.
1238 function getMessageCode ($status)
1240 global $pageno, $tabno, $op, $msgcode;
1241 return $msgcode[$pageno][$tabno][$op][$status];
1244 function validTagName ($s, $allow_autotag = FALSE)
1246 if (1 == mb_ereg (TAGNAME_REGEXP
, $s))
1248 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP
, $s))
1253 function redirectUser ($p, $t)
1255 global $page, $root;
1256 $l = "{$root}?page=${p}&tab=${t}";
1257 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1258 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1259 header ("Location: " . $l);
1263 function getRackCodeStats ()
1266 $defc = $grantc = 0;
1267 foreach ($rackCode as $s)
1270 case 'SYNT_DEFINITION':
1279 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1283 function getRackImageWidth ()
1285 return 3 +
getConfigVar ('rtwidth_0') +
getConfigVar ('rtwidth_1') +
getConfigVar ('rtwidth_2') +
3;
1288 function getRackImageHeight ($units)
1290 return 3 +
3 +
$units * 2;
1293 // Perform substitutions and return resulting string
1294 // used solely by buildLVSConfig()
1295 function apply_macros ($macros, $subject)
1298 foreach ($macros as $search => $replace)
1299 $ret = str_replace ($search, $replace, $ret);
1303 function buildLVSConfig ($object_id = 0)
1305 if ($object_id <= 0)
1307 showError ('Invalid argument', __FUNCTION__
);
1310 $oInfo = getObjectInfo ($object_id);
1311 $lbconfig = getSLBConfig ($object_id);
1312 if ($lbconfig === NULL)
1314 showError ('getSLBConfig() failed', __FUNCTION__
);
1317 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1318 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1319 foreach ($lbconfig as $vs_id => $vsinfo)
1321 $newconfig .= "########################################################\n" .
1322 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ?
'NO NAME' : $vsinfo['vs_name']) . "\n" .
1323 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ?
'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1324 "########################################################\n";
1325 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1328 '%VIP%' => $vsinfo['vip'],
1329 '%VPORT%' => $vsinfo['vport'],
1330 '%PROTO%' => $vsinfo['proto'],
1331 '%VNAME%' => $vsinfo['vs_name'],
1332 '%RSPOOLNAME%' => $vsinfo['pool_name']
1334 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1335 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1336 $newconfig .= apply_macros
1339 lf_wrap ($vsinfo['vs_vsconfig']) .
1340 lf_wrap ($vsinfo['lb_vsconfig']) .
1341 lf_wrap ($vsinfo['pool_vsconfig'])
1343 foreach ($vsinfo['rslist'] as $rs)
1345 if (empty ($rs['rsport']))
1346 $rs['rsport'] = $vsinfo['vport'];
1347 $macros['%RSIP%'] = $rs['rsip'];
1348 $macros['%RSPORT%'] = $rs['rsport'];
1349 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1350 $newconfig .= apply_macros
1353 lf_wrap ($vsinfo['vs_rsconfig']) .
1354 lf_wrap ($vsinfo['lb_rsconfig']) .
1355 lf_wrap ($vsinfo['pool_rsconfig']) .
1356 lf_wrap ($rs['rs_rsconfig'])
1358 $newconfig .= "\t}\n";
1360 $newconfig .= "}\n\n\n";
1362 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1363 return str_replace ("\r", '', $newconfig);
1366 // Indicate occupation state of each IP address: none, ordinary or problematic.
1367 function markupIPv4AddrList (&$addrlist)
1369 foreach (array_keys ($addrlist) as $ip_bin)
1373 'shared' => 0, // virtual
1374 'virtual' => 0, // loopback
1375 'regular' => 0, // connected host
1376 'router' => 0 // connected gateway
1378 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1379 $refc[$a['type']]++
;
1380 $nvirtloopback = ($refc['shared'] +
$refc['virtual'] > 0) ?
1 : 0; // modulus of virtual + shared
1381 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ?
1 : 0; // only one reservation is possible ever
1382 $nrealms = $nreserved +
$nvirtloopback +
$refc['regular'] +
$refc['router']; // latter two are connected and router allocations
1385 $addrlist[$ip_bin]['class'] = 'trbusy';
1386 elseif ($nrealms > 1)
1387 $addrlist[$ip_bin]['class'] = 'trerror';
1389 $addrlist[$ip_bin]['class'] = '';
1393 // Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1394 function findRouters ($addrlist)
1397 foreach ($addrlist as $addr)
1398 foreach ($addr['allocs'] as $alloc)
1399 if ($alloc['type'] == 'router')
1402 'id' => $alloc['object_id'],
1403 'iface' => $alloc['name'],
1404 'dname' => $alloc['object_name'],
1405 'addr' => $addr['ip']
1410 // Assist in tag chain sorting.
1411 function taginfoCmp ($tagA, $tagB)
1413 return $tagA['ci'] - $tagB['ci'];
1416 // Compare networks. When sorting a tree, the records on the list will have
1417 // distinct base IP addresses.
1418 function IPv4NetworkCmp ($netA, $netB)
1420 return bccomp ("${netA['db_first']}", "${netB['db_first']}");
1423 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1424 function sortTree (&$tree, $sortfunc = '')
1426 if (empty ($sortfunc))
1428 $self = __FUNCTION__
;
1429 usort ($tree, $sortfunc);
1430 // Don't make a mistake of directly iterating over the items of current level, because this way
1431 // the sorting will be performed on a _copy_ if each item, not the item itself.
1432 foreach (array_keys ($tree) as $tagid)
1433 $self ($tree[$tagid]['kids'], $sortfunc);
1436 function iptree_fill (&$netdata)
1438 if (!isset ($netdata['kids']) or empty ($netdata['kids']))
1440 // If we relly have nested prefixes, they must fit into the tree.
1443 'ip_bin' => $netdata['ip_bin'],
1444 'mask' => $netdata['mask']
1446 foreach ($netdata['kids'] as $pfx)
1447 iptree_embed ($worktree, $pfx);
1448 $netdata['kids'] = iptree_construct ($worktree);
1449 $netdata['kidc'] = count ($netdata['kids']);
1452 function iptree_construct ($node)
1454 $self = __FUNCTION__
;
1456 if (!isset ($node['right']))
1458 if (!isset ($node['ip']))
1460 $node['ip'] = long2ip ($node['ip_bin']);
1461 $node['kids'] = array();
1464 return array ($node);
1467 return array_merge ($self ($node['left']), $self ($node['right']));
1470 function iptree_embed (&$node, $pfx)
1472 $self = __FUNCTION__
;
1475 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1480 if ($node['mask'] == $pfx['mask'])
1482 showError ('Internal error, the recurring loop lost control', __FUNCTION__
);
1487 if (!isset ($node['right']))
1489 $node['right']['mask'] = $node['left']['mask'] = $node['mask'] +
1;
1490 $node['left']['ip_bin'] = $node['ip_bin'];
1491 $node['right']['ip_bin'] = $node['ip_bin'] +
binInvMaskFromDec ($node['mask'] +
1) +
1;
1495 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1496 $self ($node['left'], $pfx);
1497 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1498 $self ($node['right'], $pfx);
1501 showError ('Internal error, cannot decide between left and right', __FUNCTION__
);
1506 function treeApplyFunc (&$tree, $func)
1510 $self = __FUNCTION__
;
1511 foreach (array_keys ($tree) as $key)
1513 $func ($tree[$key]);
1514 $self ($tree[$key]['kids'], $func);