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 // Entity type by page number mapping is 1:1 atm, but may change later.
28 $etype_by_pageno = array
30 'ipv4net' => 'ipv4net',
31 'ipv4rspool' => 'ipv4rspool',
39 // Objects of some types should be explicitly shown as
40 // anonymous (labelless). This function is a single place where the
41 // decision about displayed name is made.
42 function displayedName ($objectData)
44 if ($objectData['name'] != '')
45 return $objectData['name'];
46 // handle transition of argument type
47 if (isset ($objectData['realm']))
49 if (considerConfiguredConstraint ($objectData, 'NAMEWARN_LISTSRC'))
50 return "ANONYMOUS " . $objectData['objtype_name'];
52 return "[${objectData['objtype_name']}]";
56 if (considerConfiguredConstraint (spotEntity ('object', $objectData['id']), 'NAMEWARN_LISTSRC'))
57 return "ANONYMOUS " . $objectData['objtype_name'];
59 return "[${objectData['objtype_name']}]";
63 // This function finds height of solid rectangle of atoms, which are all
64 // assigned to the same object. Rectangle base is defined by specified
66 function rectHeight ($rackData, $startRow, $template_idx)
69 // The first met object_id is used to match all the folowing IDs.
74 for ($locidx = 0; $locidx < 3; $locidx++
)
76 // At least one value in template is TRUE, but the following block
77 // can meet 'skipped' atoms. Let's ensure we have something after processing
79 if ($template[$template_idx][$locidx])
81 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
83 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
85 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
87 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
90 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
91 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
95 // If the first row can't offer anything, bail out.
96 if ($height == 0 and $object_id == 0)
100 while ($startRow - $height > 0);
101 # echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
102 # echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
103 # echo ") height==${height}<br>\n";
107 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
109 function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
111 global $template, $templateWidth;
113 for ($height = 0; $height < $maxheight; $height++
)
115 for ($locidx = 0; $locidx < 3; $locidx++
)
117 if ($template[$template_idx][$locidx])
119 // Add colspan/rowspan to the first row met and mark the following ones to skip.
120 // Explicitly show even single-cell spanned atoms, because rectHeight()
121 // is expeciting this data for correct calculation.
123 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
126 $colspan = $templateWidth[$template_idx];
128 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
130 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
138 // This function sets rowspan/solspan/skipped atom attributes for renderRack()
139 // What we actually have to do is to find _all_ possible rectangles for each unit
140 // and then select the widest of those with the maximal square.
141 function markAllSpans (&$rackData = NULL)
143 if ($rackData == NULL)
145 showError ('Invalid rackData', __FUNCTION__
);
148 for ($i = $rackData['height']; $i > 0; $i--)
149 while (markBestSpan ($rackData, $i));
152 // Calculate height of 6 possible span templates (array is presorted by width
153 // descending) and mark the best (if any).
154 function markBestSpan (&$rackData, $i)
156 global $template, $templateWidth;
157 for ($j = 0; $j < 6; $j++
)
159 $height[$j] = rectHeight ($rackData, $i, $j);
160 $square[$j] = $height[$j] * $templateWidth[$j];
162 // find the widest rectangle of those with maximal height
163 $maxsquare = max ($square);
166 $best_template_index = 0;
167 for ($j = 0; $j < 6; $j++
)
168 if ($square[$j] == $maxsquare)
170 $best_template_index = $j;
171 $bestheight = $height[$j];
174 // distribute span marks
175 markSpan ($rackData, $i, $bestheight, $best_template_index);
179 // We can mount 'F' atoms and unmount our own 'T' atoms.
180 function applyObjectMountMask (&$rackData, $object_id)
182 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
183 for ($locidx = 0; $locidx < 3; $locidx++
)
184 switch ($rackData[$unit_no][$locidx]['state'])
187 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
190 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
193 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
197 // Design change means transition between 'F' and 'A' and back.
198 function applyRackDesignMask (&$rackData)
200 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
201 for ($locidx = 0; $locidx < 3; $locidx++
)
202 switch ($rackData[$unit_no][$locidx]['state'])
206 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
209 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
213 // The same for 'F' and 'U'.
214 function applyRackProblemMask (&$rackData)
216 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
217 for ($locidx = 0; $locidx < 3; $locidx++
)
218 switch ($rackData[$unit_no][$locidx]['state'])
222 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
225 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
229 // This function highlights specified object (and removes previous highlight).
230 function highlightObject (&$rackData, $object_id)
232 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
233 for ($locidx = 0; $locidx < 3; $locidx++
)
236 $rackData[$unit_no][$locidx]['state'] == 'T' and
237 $rackData[$unit_no][$locidx]['object_id'] == $object_id
239 $rackData[$unit_no][$locidx]['hl'] = 'h';
241 unset ($rackData[$unit_no][$locidx]['hl']);
244 // This function marks atoms to selected or not depending on their current state.
245 function markupAtomGrid (&$data, $checked_state)
247 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
248 for ($locidx = 0; $locidx < 3; $locidx++
)
250 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
252 if ($data[$unit_no][$locidx]['state'] == $checked_state)
253 $data[$unit_no][$locidx]['checked'] = ' checked';
255 $data[$unit_no][$locidx]['checked'] = '';
259 // This function is almost a clone of processGridForm(), but doesn't save anything to database
260 // Return value is the changed rack data.
261 // Here we assume that correct filter has already been applied, so we just
262 // set or unset checkbox inputs w/o changing atom state.
263 function mergeGridFormToRack (&$rackData)
265 $rack_id = $rackData['id'];
266 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
267 for ($locidx = 0; $locidx < 3; $locidx++
)
269 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
271 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
272 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
273 $rackData[$unit_no][$locidx]['checked'] = ' checked';
275 $rackData[$unit_no][$locidx]['checked'] = '';
279 // netmask conversion from length to number
280 function binMaskFromDec ($maskL)
282 $map_straight = array (
317 return $map_straight[$maskL];
320 // complementary value
321 function binInvMaskFromDec ($maskL)
358 return $map_compl[$maskL];
361 // This function looks up 'has_problems' flag for 'T' atoms
362 // and modifies 'hl' key. May be, this should be better done
363 // in amplifyCell(). We don't honour 'skipped' key, because
364 // the function is also used for thumb creation.
365 function markupObjectProblems (&$rackData)
367 for ($i = $rackData['height']; $i > 0; $i--)
368 for ($locidx = 0; $locidx < 3; $locidx++
)
369 if ($rackData[$i][$locidx]['state'] == 'T')
371 $object = spotEntity ('object', $rackData[$i][$locidx]['object_id']);
372 if ($object['has_problems'] == 'yes')
374 // Object can be already highlighted.
375 if (isset ($rackData[$i][$locidx]['hl']))
376 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
378 $rackData[$i][$locidx]['hl'] = 'w';
383 function search_cmpObj ($a, $b)
385 return ($a['score'] > $b['score'] ?
-1 : 1);
388 function getObjectSearchResults ($terms)
391 mergeSearchResults ($objects, $terms, 'name');
392 mergeSearchResults ($objects, $terms, 'label');
393 mergeSearchResults ($objects, $terms, 'asset_no');
394 mergeSearchResults ($objects, $terms, 'barcode');
395 if (count ($objects) == 1)
396 usort ($objects, 'search_cmpObj');
400 // This function removes all colons and dots from a string.
401 function l2addressForDatabase ($string)
403 $string = strtoupper ($string);
406 case ($string == '' or preg_match (RE_L2_SOLID
, $string)):
408 case (preg_match (RE_L2_IFCFG
, $string)):
409 $pieces = explode (':', $string);
410 // This workaround is for SunOS ifconfig.
411 foreach ($pieces as &$byte)
412 if (strlen ($byte) == 1)
414 // And this workaround is for PHP.
416 return implode ('', $pieces);
417 case (preg_match (RE_L2_CISCO
, $string)):
418 return implode ('', explode ('.', $string));
419 case (preg_match (RE_L2_IPCFG
, $string)):
420 return implode ('', explode ('-', $string));
426 function l2addressFromDatabase ($string)
428 switch (strlen ($string))
432 $ret = implode (':', str_split ($string, 2));
441 // The following 2 functions return previous and next rack IDs for
442 // a given rack ID. The order of racks is the same as in renderRackspace()
444 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
446 if ($row_id <= 0 or $rack_id <= 0)
448 showError ('Invalid arguments passed', __FUNCTION__
);
451 $rackList = listCells ('rack', $row_id);
452 doubleLink ($rackList);
453 if (isset ($rackList[$rack_id]['prev_key']))
454 return $rackList[$rack_id]['prev_key'];
458 function getNextIDforRack ($row_id = 0, $rack_id = 0)
460 if ($row_id <= 0 or $rack_id <= 0)
462 showError ('Invalid arguments passed', __FUNCTION__
);
465 $rackList = listCells ('rack', $row_id);
466 doubleLink ($rackList);
467 if (isset ($rackList[$rack_id]['next_key']))
468 return $rackList[$rack_id]['next_key'];
472 // This function finds previous and next array keys for each array key and
473 // modifies its argument accordingly.
474 function doubleLink (&$array)
477 foreach (array_keys ($array) as $key)
481 $array[$key]['prev_key'] = $prev_key;
482 $array[$prev_key]['next_key'] = $key;
488 function sortTokenize ($a, $b)
494 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
495 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
496 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
503 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
504 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
505 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
510 $ar = explode(' ', $a);
511 $br = explode(' ', $b);
512 for ($i=0; $i<count($ar) && $i<count($br); $i++
)
515 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
516 $ret = ($ar[$i]==$br[$i])?
0:($ar[$i]<$br[$i]?
-1:1);
518 $ret = strcasecmp($ar[$i], $br[$i]);
529 function sortByName ($a, $b)
531 return sortTokenize($a['name'], $b['name']);
534 function sortEmptyPorts ($a, $b)
536 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
537 if ($objname_cmp == 0)
539 return sortTokenize($a['Port_name'], $b['Port_name']);
544 function sortObjectAddressesAndNames ($a, $b)
546 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
547 if ($objname_cmp == 0)
549 $name_a = (isset ($a['port_name'])) ?
$a['port_name'] : '';
550 $name_b = (isset ($b['port_name'])) ?
$b['port_name'] : '';
551 $objname_cmp = sortTokenize($name_a, $name_b);
552 if ($objname_cmp == 0)
553 sortTokenize($a['ip'], $b['ip']);
559 function sortAddresses ($a, $b)
561 $name_cmp = sortTokenize($a['name'], $b['name']);
564 return sortTokenize($a['ip'], $b['ip']);
569 // This function expands port compat list into a matrix.
570 function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
573 // Create type matrix and markup compatible types.
574 foreach (array_keys ($portTypeList) as $type1)
575 foreach (array_keys ($portTypeList) as $type2)
576 $matrix[$type1][$type2] = FALSE;
577 foreach ($portCompatList as $pair)
578 $matrix[$pair['type1']][$pair['type2']] = TRUE;
582 // This function returns an array of single element of object's FQDN attribute,
583 // if FQDN is set. The next choice is object's common name, if it looks like a
584 // hostname. Otherwise an array of all 'regular' IP addresses of the
585 // object is returned (which may appear 0 and more elements long).
586 function findAllEndpoints ($object_id, $fallback = '')
588 $values = getAttrValues ($object_id);
589 foreach ($values as $record)
590 if ($record['name'] == 'FQDN' && strlen ($record['value']))
591 return array ($record['value']);
593 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
594 if ($alloc['type'] == 'regular')
595 $regular[] = $dottedquad;
596 if (!count ($regular) && strlen ($fallback))
597 return array ($fallback);
601 // Some records in the dictionary may be written as plain text or as Wiki
602 // link in the following syntax:
604 // 2. [[word URL]] // FIXME: this isn't working
605 // 3. [[word word word | URL]]
606 // This function parses the line and returns text suitable for either A
607 // (rendering <A HREF>) or O (for <OPTION>).
608 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
610 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
613 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
617 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
618 $s = explode ('|', $line);
619 $o_value = trim ($s[0]);
621 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
622 $a_value = trim ($s[1]);
624 return "<a href='${a_value}'>${o_value}</a>";
629 // FIXME: only renderIPv4Address() is using this function, consider
631 function buildVServiceName ($vsinfo = NULL)
635 showError ('NULL argument', __FUNCTION__
);
638 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
641 // rackspace usage for a single rack
642 // (T + W + U) / (height * 3 - A)
643 function getRSUforRack ($data = NULL)
647 showError ('Invalid argument', __FUNCTION__
);
650 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
651 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
652 for ($locidx = 0; $locidx < 3; $locidx++
)
653 $counter[$data[$unit_no][$locidx]['state']]++
;
654 return ($counter['T'] +
$counter['W'] +
$counter['U']) / ($counter['T'] +
$counter['W'] +
$counter['U'] +
$counter['F']);
658 function getRSUforRackRow ($rowData = NULL)
660 if ($rowData === NULL)
662 showError ('Invalid argument', __FUNCTION__
);
665 if (!count ($rowData))
667 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
669 foreach (array_keys ($rowData) as $rack_id)
671 $data = spotEntity ('rack', $rack_id);
673 $total_height +
= $data['height'];
674 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
675 for ($locidx = 0; $locidx < 3; $locidx++
)
676 $counter[$data[$unit_no][$locidx]['state']]++
;
678 return ($counter['T'] +
$counter['W'] +
$counter['U']) / ($counter['T'] +
$counter['W'] +
$counter['U'] +
$counter['F']);
681 // Make sure the string is always wrapped with LF characters
682 function lf_wrap ($str)
684 $ret = trim ($str, "\r\n");
690 // Adopted from Mantis BTS code.
691 function string_insert_hrefs ($s)
693 if (getConfigVar ('DETECT_URLS') != 'yes')
695 # Find any URL in a string and replace it by a clickable link
696 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
697 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
699 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
700 '<a href="mailto:\0">\0</a>',
706 function email_regex_simple ()
708 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
709 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
712 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
713 // for the requested object_type_id.
714 function getAutoPorts ($type_id)
717 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
718 foreach ($typemap as $equation)
720 $tmp = explode ('=', $equation);
721 if (count ($tmp) != 2)
723 $objtype_id = $tmp[0];
724 if ($objtype_id != $type_id)
727 foreach (explode ('+', $portlist) as $product)
729 $tmp = explode ('*', $product);
730 if (count ($tmp) != 3)
733 $port_type = $tmp[1];
735 for ($i = 0; $i < $nports; $i++
)
736 $ret[] = array ('type' => $port_type, 'name' => @sprintf
($format, $i));
742 // Use pre-served trace to traverse the tree, then place given node where it belongs.
743 function pokeNode (&$tree, $trace, $key, $value, $threshold = 0)
745 // This function needs the trace to be followed FIFO-way. The fastest
746 // way to do so is to use array_push() for putting values into the
747 // list and array_shift() for getting them out. This exposed up to 11%
748 // performance gain compared to other patterns of array_push/array_unshift/
749 // array_reverse/array_pop/array_shift conjunction.
750 $myid = array_shift ($trace);
751 if (!count ($trace)) // reached the target
753 if (!$threshold or ($threshold and $tree[$myid]['kidc'] +
1 < $threshold))
754 $tree[$myid]['kids'][$key] = $value;
755 // Reset accumulated records once, when the limit is reached, not each time
757 if (++
$tree[$myid]['kidc'] == $threshold)
758 $tree[$myid]['kids'] = array();
762 $self = __FUNCTION__
;
763 $self ($tree[$myid]['kids'], $trace, $key, $value, $threshold);
767 // Build a tree from the item list and return it. Input and output data is
768 // indexed by item id (nested items in output are recursively stored in 'kids'
769 // key, which is in turn indexed by id. Functions, which are ready to handle
770 // tree collapsion/expansion themselves, may request non-zero threshold value
771 // for smaller resulting tree.
772 function treeFromList ($nodelist, $threshold = 0, $return_main_payload = TRUE)
775 // Array equivalent of traceEntity() function.
777 // set kidc and kids only once
778 foreach (array_keys ($nodelist) as $nodeid)
780 $nodelist[$nodeid]['kidc'] = 0;
781 $nodelist[$nodeid]['kids'] = array();
786 foreach (array_keys ($nodelist) as $nodeid)
788 // When adding a node to the working tree, book another
789 // iteration, because the new item could make a way for
790 // others onto the tree. Also remove any item added from
791 // the input list, so iteration base shrinks.
792 // First check if we can assign directly.
793 if ($nodelist[$nodeid]['parent_id'] == NULL)
795 $tree[$nodeid] = $nodelist[$nodeid];
796 $trace[$nodeid] = array(); // Trace to root node is empty
797 unset ($nodelist[$nodeid]);
800 // Now look if it fits somewhere on already built tree.
801 elseif (isset ($trace[$nodelist[$nodeid]['parent_id']]))
803 // Trace to a node is a trace to its parent plus parent id.
804 $trace[$nodeid] = $trace[$nodelist[$nodeid]['parent_id']];
805 $trace[$nodeid][] = $nodelist[$nodeid]['parent_id'];
806 pokeNode ($tree, $trace[$nodeid], $nodeid, $nodelist[$nodeid], $threshold);
807 // path to any other node is made of all parent nodes plus the added node itself
808 unset ($nodelist[$nodeid]);
814 if ($return_main_payload)
820 // Build a tree from the tag list and return everything _except_ the tree.
821 // IOW, return taginfo items, which have parent_id set and pointing outside
822 // of the "normal" tree, which originates from the root.
823 function getOrphanedTags ()
826 return treeFromList ($taglist, 0, FALSE);
829 function serializeTags ($chain, $baseurl = '')
833 foreach ($chain as $taginfo)
836 ($baseurl == '' ?
'' : "<a href='${baseurl}cft[]=${taginfo['id']}'>") .
838 ($baseurl == '' ?
'' : '</a>');
844 // For each tag add all its parent tags onto the list. Don't expect anything
845 // except user's tags on the chain.
846 function getTagChainExpansion ($chain, $tree = NULL)
848 $self = __FUNCTION__
;
854 // For each tag find its path from the root, then combine items
855 // of all paths and add them to the chain, if they aren't there yet.
857 foreach ($tree as $taginfo1)
860 foreach ($chain as $taginfo2)
861 if ($taginfo1['id'] == $taginfo2['id'])
866 if (count ($taginfo1['kids']) > 0)
868 $subsearch = $self ($chain, $taginfo1['kids']);
869 if (count ($subsearch))
872 $ret = array_merge ($ret, $subsearch);
881 // Return the list of missing implicit tags.
882 function getImplicitTags ($oldtags)
885 $newtags = getTagChainExpansion ($oldtags);
886 foreach ($newtags as $newtag)
888 $already_exists = FALSE;
889 foreach ($oldtags as $oldtag)
890 if ($newtag['id'] == $oldtag['id'])
892 $already_exists = TRUE;
897 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
902 // Minimize the chain: exclude all implicit tags and return the result.
903 function getExplicitTagsOnly ($chain, $tree = NULL)
905 $self = __FUNCTION__
;
910 foreach ($tree as $taginfo)
912 if (isset ($taginfo['kids']))
914 $harvest = $self ($chain, $taginfo['kids']);
915 if (count ($harvest) > 0)
917 $ret = array_merge ($ret, $harvest);
921 // This tag isn't implicit, test is for being explicit.
922 foreach ($chain as $testtag)
923 if ($taginfo['id'] == $testtag['id'])
932 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
933 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
934 // a list of tag structures. Same structure (tag ID list) is returned after processing.
935 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
937 $self = __FUNCTION__
;
941 $getallkids = $getall;
943 foreach ($tree as $taginfo)
945 foreach ($idlist as $test_id)
946 if ($getall or $taginfo['id'] == $test_id)
948 $ret[] = $taginfo['id'];
949 // Once matched node makes all sub-nodes match, but don't make
950 // a mistake of matching every other node at the current level.
954 if (isset ($taginfo['kids']))
955 $ret = array_merge ($ret, $self ($idlist, $taginfo['kids'], $getallkids));
961 // Universal autotags generator, a complementing function for loadEntityTags().
962 // Bypass key isn't strictly typed, but interpreted depending on the realm.
963 function generateEntityAutoTags ($cell)
966 switch ($cell['realm'])
969 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
970 $ret[] = array ('tag' => '$any_rack');
972 case 'object': // during transition bypass is already the whole structure
973 $ret[] = array ('tag' => '$id_' . $cell['id']);
974 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
975 $ret[] = array ('tag' => '$any_object');
976 if (validTagName ('$cn_' . $cell['name']))
977 $ret[] = array ('tag' => '$cn_' . $cell['name']);
978 if (!strlen ($cell['rack_id']))
979 $ret[] = array ('tag' => '$unmounted');
981 case 'ipv4net': // during transition bypass is already the whole structure
982 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
983 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
984 $ret[] = array ('tag' => '$any_ip4net');
985 $ret[] = array ('tag' => '$any_net');
988 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
989 $ret[] = array ('tag' => '$any_ipv4vs');
990 $ret[] = array ('tag' => '$any_vs');
993 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
994 $ret[] = array ('tag' => '$any_ipv4rsp');
995 $ret[] = array ('tag' => '$any_rsp');
998 // {$username_XXX} autotag is generated always, but {$userid_XXX}
999 // appears only for accounts, which exist in local database.
1000 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
1001 if (isset ($cell['user_id']))
1002 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
1005 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
1006 $ret[] = array ('tag' => '$any_file');
1014 // Check, if the given tag is present on the chain (will only work
1015 // for regular tags with tag ID set.
1016 function tagOnChain ($taginfo, $tagchain)
1018 if (!isset ($taginfo['id']))
1020 foreach ($tagchain as $test)
1021 if ($test['id'] == $taginfo['id'])
1026 function tagNameOnChain ($tagname, $tagchain)
1028 foreach ($tagchain as $test)
1029 if ($test['tag'] == $tagname)
1034 // Idem, but use ID list instead of chain.
1035 function tagOnIdList ($taginfo, $tagidlist)
1037 if (!isset ($taginfo['id']))
1039 foreach ($tagidlist as $tagid)
1040 if ($taginfo['id'] == $tagid)
1045 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1046 // Assume, that neither of the lists contains duplicates.
1047 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1048 function tagChainCmp ($chain1, $chain2)
1050 if (count ($chain1) != count ($chain2))
1052 foreach ($chain1 as $taginfo1)
1053 if (!tagOnChain ($taginfo1, $chain2))
1058 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1059 // hold all appropriate (explicit and implicit) tags respectively.
1060 // Otherwise some limited redirection is necessary (only page and tab
1061 // names are preserved, ophandler name change isn't handled).
1062 function fixContext ()
1077 'accounts' => 'userlist',
1078 'rspools' => 'ipv4rsplist',
1079 'rspool' => 'ipv4rsp',
1080 'vservices' => 'ipv4vslist',
1081 'vservice' => 'ipv4vs',
1082 'objects' => 'depot',
1083 'objgroup' => 'depot',
1086 $tmap['objects']['newmulti'] = 'addmore';
1087 $tmap['objects']['newobj'] = 'addmore';
1088 $tmap['object']['switchvlans'] = 'livevlans';
1089 $tmap['object']['slb'] = 'editrspvs';
1090 $tmap['object']['portfwrd'] = 'nat4';
1091 $tmap['object']['network'] = 'ipv4';
1092 if (isset ($pmap[$pageno]))
1093 redirectUser ($pmap[$pageno], $tabno);
1094 if (isset ($tmap[$pageno][$tabno]))
1095 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1097 if (isset ($etype_by_pageno[$pageno]))
1099 // Each page listed in the map above requires one uint argument.
1100 assertUIntArg ($page[$pageno]['bypass'], __FUNCTION__
);
1101 $target = spotEntity ($etype_by_pageno[$pageno], $_REQUEST[$page[$pageno]['bypass']]);
1102 $target_given_tags = $target['etags'];
1103 // Don't reset autochain, because auth procedures could push stuff there in.
1104 // Another important point is to ignore 'user' realm, so we don't infuse effective
1105 // context with autotags of the displayed account.
1106 if ($pageno != 'user')
1107 $auto_tags = array_merge ($auto_tags, $target['atags']);
1109 // Explicit and implicit chains should be normally empty at this point, so
1110 // overwrite the contents anyway.
1111 $expl_tags = mergeTagChains ($user_given_tags, $target_given_tags);
1112 $impl_tags = getImplicitTags ($expl_tags);
1115 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1116 // records indexed by tag IDs (tag chain).
1117 function buildTagChainFromIds ($tagidlist)
1121 foreach (array_unique ($tagidlist) as $tag_id)
1122 if (isset ($taglist[$tag_id]))
1123 $ret[] = $taglist[$tag_id];
1127 // Process a given tag tree and return only meaningful branches. The resulting
1128 // (sub)tree will have refcnt leaves on every last branch.
1129 function getObjectiveTagTree ($tree, $realm)
1131 $self = __FUNCTION__
;
1133 foreach ($tree as $taginfo)
1135 $subsearch = array();
1137 if (count ($taginfo['kids']))
1139 $subsearch = $self ($taginfo['kids'], $realm);
1140 $pick = count ($subsearch) > 0;
1142 if (isset ($taginfo['refcnt'][$realm]))
1148 'id' => $taginfo['id'],
1149 'tag' => $taginfo['tag'],
1150 'parent_id' => $taginfo['parent_id'],
1151 'refcnt' => $taginfo['refcnt'],
1152 'kids' => $subsearch
1158 // Get taginfo record by tag name, return NULL, if record doesn't exist.
1159 function getTagByName ($target_name)
1162 foreach ($taglist as $taginfo)
1163 if ($taginfo['tag'] == $target_name)
1168 // Merge two chains, filtering dupes out. Return the resulting superset.
1169 function mergeTagChains ($chainA, $chainB)
1172 // Reindex by tag id in any case.
1174 foreach ($chainA as $tag)
1175 $ret[$tag['id']] = $tag;
1176 foreach ($chainB as $tag)
1177 if (!isset ($ret[$tag['id']]))
1178 $ret[$tag['id']] = $tag;
1182 function getCellFilter ()
1185 if (isset ($_REQUEST['tagfilter']) and is_array ($_REQUEST['tagfilter']))
1187 $_REQUEST['cft'] = $_REQUEST['tagfilter'];
1188 unset ($_REQUEST['tagfilter']);
1192 'tagidlist' => array(),
1193 'tnamelist' => array(),
1194 'pnamelist' => array(),
1198 'expression' => array(),
1199 'urlextra' => '', // Just put text here and let makeHref call urlencode().
1203 case (!isset ($_REQUEST['andor'])):
1204 $andor2 = getConfigVar ('FILTER_DEFAULT_ANDOR');
1206 case ($_REQUEST['andor'] == 'and'):
1207 case ($_REQUEST['andor'] == 'or'):
1208 $ret['andor'] = $andor2 = $_REQUEST['andor'];
1209 $ret['urlextra'] .= '&andor=' . $ret['andor'];
1212 showError ('Invalid and/or switch value in submitted form', __FUNCTION__
);
1216 // Both tags and predicates, which don't exist, should be
1217 // handled somehow. Discard them silently for now.
1218 if (isset ($_REQUEST['cft']) and is_array ($_REQUEST['cft']))
1221 foreach ($_REQUEST['cft'] as $req_id)
1222 if (isset ($taglist[$req_id]))
1224 $ret['tagidlist'][] = $req_id;
1225 $ret['tnamelist'][] = $taglist[$req_id]['tag'];
1226 $ret['text'] .= $andor1 . '{' . $taglist[$req_id]['tag'] . '}';
1227 $andor1 = ' ' . $andor2 . ' ';
1228 $ret['urlextra'] .= '&cft[]=' . $req_id;
1231 if (isset ($_REQUEST['cfp']) and is_array ($_REQUEST['cfp']))
1234 foreach ($_REQUEST['cfp'] as $req_name)
1235 if (isset ($pTable[$req_name]))
1237 $ret['pnamelist'][] = $req_name;
1238 $ret['text'] .= $andor1 . '[' . $req_name . ']';
1239 $andor1 = ' ' . $andor2 . ' ';
1240 $ret['urlextra'] .= '&cfp[]=' . $req_name;
1243 // Extra text comes from TEXTAREA and is easily screwed by standard escaping function.
1244 if (isset ($sic['cfe']))
1246 // Only consider extra text, when it is a correct RackCode expression.
1247 $parse = spotPayload ($sic['cfe'], 'SYNT_EXPR');
1248 if ($parse['result'] == 'ACK')
1250 $ret['extratext'] = trim ($sic['cfe']);
1251 $ret['urlextra'] .= '&cfe=' . $ret['extratext'];
1254 $finaltext = array();
1255 if (strlen ($ret['text']))
1256 $finaltext[] = '(' . $ret['text'] . ')';
1257 if (strlen ($ret['extratext']))
1258 $finaltext[] = '(' . $ret['extratext'] . ')';
1259 $finaltext = implode (' ' . $andor2 . ' ', $finaltext);
1260 if (strlen ($finaltext))
1262 $parse = spotPayload ($finaltext, 'SYNT_EXPR');
1263 $ret['expression'] = $parse['result'] == 'ACK' ?
$parse['load'] : NULL;
1264 // It's not quite fair enough to put the blame of the whole text onto
1265 // non-empty "extra" portion of it, but it's the only user-generated portion
1266 // of it, thus the most probable cause of parse error.
1267 if (strlen ($ret['extratext']))
1268 $ret['extraclass'] = $parse['result'] == 'ACK' ?
'validation-success' : 'validation-error';
1273 // Return an empty message log.
1274 function emptyLog ()
1283 // Return a message log consisting of only one message.
1284 function oneLiner ($code, $args = array())
1287 $ret['m'][] = count ($args) ?
array ('c' => $code, 'a' => $args) : array ('c' => $code);
1291 // Merge message payload from two message logs given and return the result.
1292 function mergeLogs ($log1, $log2)
1295 $ret['m'] = array_merge ($log1['m'], $log2['m']);
1299 function validTagName ($s, $allow_autotag = FALSE)
1301 if (1 == mb_ereg (TAGNAME_REGEXP
, $s))
1303 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP
, $s))
1308 function redirectUser ($p, $t)
1310 global $page, $root;
1311 $l = "{$root}?page=${p}&tab=${t}";
1312 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1313 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1314 header ("Location: " . $l);
1318 function getRackCodeStats ()
1321 $defc = $grantc = $modc = 0;
1322 foreach ($rackCode as $s)
1325 case 'SYNT_DEFINITION':
1339 'Definition sentences' => $defc,
1340 'Grant sentences' => $grantc,
1341 'Context mod sentences' => $modc
1346 function getRackImageWidth ()
1349 return 3 +
$rtwidth[0] +
$rtwidth[1] +
$rtwidth[2] +
3;
1352 function getRackImageHeight ($units)
1354 return 3 +
3 +
$units * 2;
1357 // Perform substitutions and return resulting string
1358 // used solely by buildLVSConfig()
1359 function apply_macros ($macros, $subject)
1362 foreach ($macros as $search => $replace)
1363 $ret = str_replace ($search, $replace, $ret);
1367 function buildLVSConfig ($object_id = 0)
1369 if ($object_id <= 0)
1371 showError ('Invalid argument', __FUNCTION__
);
1374 $oInfo = spotEntity ('object', $object_id);
1375 $lbconfig = getSLBConfig ($object_id);
1376 if ($lbconfig === NULL)
1378 showError ('getSLBConfig() failed', __FUNCTION__
);
1381 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1382 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1383 foreach ($lbconfig as $vs_id => $vsinfo)
1385 $newconfig .= "########################################################\n" .
1386 "# VS (id == ${vs_id}): " . (!strlen ($vsinfo['vs_name']) ?
'NO NAME' : $vsinfo['vs_name']) . "\n" .
1387 "# RS pool (id == ${vsinfo['pool_id']}): " . (!strlen ($vsinfo['pool_name']) ?
'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1388 "########################################################\n";
1389 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1392 '%VIP%' => $vsinfo['vip'],
1393 '%VPORT%' => $vsinfo['vport'],
1394 '%PROTO%' => $vsinfo['proto'],
1395 '%VNAME%' => $vsinfo['vs_name'],
1396 '%RSPOOLNAME%' => $vsinfo['pool_name']
1398 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1399 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1400 $newconfig .= apply_macros
1403 lf_wrap ($vsinfo['vs_vsconfig']) .
1404 lf_wrap ($vsinfo['lb_vsconfig']) .
1405 lf_wrap ($vsinfo['pool_vsconfig'])
1407 foreach ($vsinfo['rslist'] as $rs)
1409 if (!strlen ($rs['rsport']))
1410 $rs['rsport'] = $vsinfo['vport'];
1411 $macros['%RSIP%'] = $rs['rsip'];
1412 $macros['%RSPORT%'] = $rs['rsport'];
1413 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1414 $newconfig .= apply_macros
1417 lf_wrap ($vsinfo['vs_rsconfig']) .
1418 lf_wrap ($vsinfo['lb_rsconfig']) .
1419 lf_wrap ($vsinfo['pool_rsconfig']) .
1420 lf_wrap ($rs['rs_rsconfig'])
1422 $newconfig .= "\t}\n";
1424 $newconfig .= "}\n\n\n";
1426 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1427 return str_replace ("\r", '', $newconfig);
1430 // Indicate occupation state of each IP address: none, ordinary or problematic.
1431 function markupIPv4AddrList (&$addrlist)
1433 foreach (array_keys ($addrlist) as $ip_bin)
1437 'shared' => 0, // virtual
1438 'virtual' => 0, // loopback
1439 'regular' => 0, // connected host
1440 'router' => 0 // connected gateway
1442 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1443 $refc[$a['type']]++
;
1444 $nvirtloopback = ($refc['shared'] +
$refc['virtual'] > 0) ?
1 : 0; // modulus of virtual + shared
1445 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ?
1 : 0; // only one reservation is possible ever
1446 $nrealms = $nreserved +
$nvirtloopback +
$refc['regular'] +
$refc['router']; // latter two are connected and router allocations
1449 $addrlist[$ip_bin]['class'] = 'trbusy';
1450 elseif ($nrealms > 1)
1451 $addrlist[$ip_bin]['class'] = 'trerror';
1453 $addrlist[$ip_bin]['class'] = '';
1457 // Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1458 function findRouters ($addrlist)
1461 foreach ($addrlist as $addr)
1462 foreach ($addr['allocs'] as $alloc)
1463 if ($alloc['type'] == 'router')
1466 'id' => $alloc['object_id'],
1467 'iface' => $alloc['name'],
1468 'dname' => $alloc['object_name'],
1469 'addr' => $addr['ip']
1474 // Assist in tag chain sorting.
1475 function taginfoCmp ($tagA, $tagB)
1477 return $tagA['ci'] - $tagB['ci'];
1480 // Compare networks. When sorting a tree, the records on the list will have
1481 // distinct base IP addresses.
1482 // "The comparison function must return an integer less than, equal to, or greater
1483 // than zero if the first argument is considered to be respectively less than,
1484 // equal to, or greater than the second." (c) PHP manual
1485 function IPv4NetworkCmp ($netA, $netB)
1487 // There's a problem just substracting one u32 integer from another,
1488 // because the result may happen big enough to become a negative i32
1489 // integer itself (PHP tries to cast everything it sees to signed int)
1490 // The comparison below must treat positive and negative values of both
1492 // Equal values give instant decision regardless of their [equal] sign.
1493 if ($netA['ip_bin'] == $netB['ip_bin'])
1495 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1496 // 0x00000001~0x7fffffff 1~2147483647
1497 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1498 // 0x80000000~0xffffffff -2147483648~-1
1499 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1500 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1501 if ($signA == $signB)
1503 if ($netA['ip_bin'] > $netB['ip_bin'])
1508 else // With only one of two values being negative, it... wins!
1510 if ($netA['ip_bin'] < $netB['ip_bin'])
1517 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1518 function sortTree (&$tree, $sortfunc = '')
1520 if (!strlen ($sortfunc))
1522 $self = __FUNCTION__
;
1523 usort ($tree, $sortfunc);
1524 // Don't make a mistake of directly iterating over the items of current level, because this way
1525 // the sorting will be performed on a _copy_ if each item, not the item itself.
1526 foreach (array_keys ($tree) as $tagid)
1527 $self ($tree[$tagid]['kids'], $sortfunc);
1530 function iptree_fill (&$netdata)
1532 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
1534 // If we really have nested prefixes, they must fit into the tree.
1537 'ip_bin' => $netdata['ip_bin'],
1538 'mask' => $netdata['mask']
1540 foreach ($netdata['kids'] as $pfx)
1541 iptree_embed ($worktree, $pfx);
1542 $netdata['kids'] = iptree_construct ($worktree);
1543 $netdata['kidc'] = count ($netdata['kids']);
1546 function iptree_construct ($node)
1548 $self = __FUNCTION__
;
1550 if (!isset ($node['right']))
1552 if (!isset ($node['ip']))
1554 $node['ip'] = long2ip ($node['ip_bin']);
1555 $node['kids'] = array();
1559 return array ($node);
1562 return array_merge ($self ($node['left']), $self ($node['right']));
1565 function iptree_embed (&$node, $pfx)
1567 $self = __FUNCTION__
;
1570 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1575 if ($node['mask'] == $pfx['mask'])
1577 showError ('Internal error, the recurring loop lost control', __FUNCTION__
);
1582 if (!isset ($node['right']))
1584 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
1585 $node['left']['mask'] = $node['mask'] +
1;
1586 $node['left']['ip_bin'] = $node['ip_bin'];
1587 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
1588 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] |
binInvMaskFromDec ($node['left']['mask']));
1590 $node['right']['mask'] = $node['mask'] +
1;
1591 $node['right']['ip_bin'] = $node['ip_bin'] +
binInvMaskFromDec ($node['mask'] +
1) +
1;
1592 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
1593 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] |
binInvMaskFromDec ($node['right']['mask']));
1597 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1598 $self ($node['left'], $pfx);
1599 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1600 $self ($node['right'], $pfx);
1603 showError ('Internal error, cannot decide between left and right', __FUNCTION__
);
1608 function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
1610 if (!strlen ($func))
1612 $self = __FUNCTION__
;
1613 foreach (array_keys ($tree) as $key)
1615 $func ($tree[$key]);
1616 if (strlen ($stopfunc) and $stopfunc ($tree[$key]))
1618 $self ($tree[$key]['kids'], $func);
1622 function loadIPv4AddrList (&$netinfo)
1624 loadOwnIPv4Addresses ($netinfo);
1625 markupIPv4AddrList ($netinfo['addrlist']);
1628 function countOwnIPv4Addresses (&$node)
1632 $node['mask_bin'] = binMaskFromDec ($node['mask']);
1633 $node['mask_bin_inv'] = binInvMaskFromDec ($node['mask']);
1634 $node['db_first'] = sprintf ('%u', 0x00000000 +
$node['ip_bin'] & $node['mask_bin']);
1635 $node['db_last'] = sprintf ('%u', 0x00000000 +
$node['ip_bin'] |
($node['mask_bin_inv']));
1636 if (!count ($node['kids']))
1638 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1639 $node['addrt'] = binInvMaskFromDec ($node['mask']) +
1;
1642 foreach ($node['kids'] as $nested)
1643 if (!isset ($nested['id'])) // spare
1645 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1646 $node['addrt'] +
= binInvMaskFromDec ($nested['mask']) +
1;
1648 // Don't do anything more, because the displaying function will load the addresses anyway.
1650 $node['addrc'] = count (scanIPv4Space ($toscan));
1653 function nodeIsCollapsed ($node)
1655 return $node['symbol'] == 'node-collapsed';
1658 function loadOwnIPv4Addresses (&$node)
1661 if (!isset ($node['kids']) or !count ($node['kids']))
1662 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1664 foreach ($node['kids'] as $nested)
1665 if (!isset ($nested['id'])) // spare
1666 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1667 $node['addrlist'] = scanIPv4Space ($toscan);
1668 $node['addrc'] = count ($node['addrlist']);
1671 function prepareIPv4Tree ($netlist, $expanded_id = 0)
1673 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
1674 // so perform necessary pre-processing to make orphans belong to root. This trick
1675 // was earlier performed by getIPv4NetworkList().
1676 $netids = array_keys ($netlist);
1677 foreach ($netids as $cid)
1678 if (!in_array ($netlist[$cid]['parent_id'], $netids))
1679 $netlist[$cid]['parent_id'] = NULL;
1680 $tree = treeFromList ($netlist); // medium call
1681 sortTree ($tree, 'IPv4NetworkCmp');
1682 // complement the tree before markup to make the spare networks have "symbol" set
1683 treeApplyFunc ($tree, 'iptree_fill');
1684 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
1685 // count addresses after the markup to skip computation for hidden tree nodes
1686 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
1690 // Check all items of the tree recursively, until the requested target id is
1691 // found. Mark all items leading to this item as "expanded", collapsing all
1692 // the rest, which exceed the given threshold (if the threshold is given).
1693 function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
1695 $self = __FUNCTION__
;
1697 foreach (array_keys ($tree) as $key)
1699 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
1700 $below = $self ($tree[$key]['kids'], $threshold, $target);
1701 if (!$tree[$key]['kidc']) // terminal node
1702 $tree[$key]['symbol'] = 'spacer';
1703 elseif ($tree[$key]['kidc'] < $threshold)
1704 $tree[$key]['symbol'] = 'node-expanded-static';
1705 elseif ($here or $below)
1706 $tree[$key]['symbol'] = 'node-expanded';
1708 $tree[$key]['symbol'] = 'node-collapsed';
1709 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
1714 // Convert entity name to human-readable value
1715 function formatEntityName ($name) {
1719 return 'IPv4 Network';
1721 return 'IPv4 RS Pool';
1723 return 'IPv4 Virtual Service';
1734 // Take a MySQL or other generic timestamp and make it prettier
1735 function formatTimestamp ($timestamp) {
1736 return date('n/j/y g:iA', strtotime($timestamp));
1739 // Display hrefs for all of a file's parents. If scissors are requested,
1740 // prepend cutting button to each of them.
1741 function serializeFileLinks ($links, $scissors = FALSE)
1747 foreach ($links as $link_id => $li)
1749 switch ($li['entity_type'])
1752 $params = "page=ipv4net&id=";
1755 $params = "page=ipv4rspool&pool_id=";
1758 $params = "page=ipv4vs&vs_id=";
1761 $params = "page=object&object_id=";
1764 $params = "page=rack&rack_id=";
1767 $params = "page=user&user_id=";
1773 $ret .= "<a href='" . makeHrefProcess(array('op'=>'unlinkFile', 'link_id'=>$link_id)) . "'";
1774 $ret .= getImageHREF ('cut') . '</a> ';
1776 $ret .= sprintf("<a href='%s?%s%s'>%s</a>", $root, $params, $li['entity_id'], $li['name']);
1782 // Convert filesize to appropriate unit and make it human-readable
1783 function formatFileSize ($bytes) {
1785 if($bytes < 1024) // bytes
1786 return "${bytes} bytes";
1789 if ($bytes < 1024000)
1790 return sprintf ("%.1fk", round (($bytes / 1024), 1));
1793 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
1796 // Reverse of formatFileSize, it converts human-readable value to bytes
1797 function convertToBytes ($value) {
1798 $value = trim($value);
1799 $last = strtolower($value[strlen($value)-1]);
1813 function ip_quad2long ($ip)
1815 return sprintf("%u", ip2long($ip));
1818 function ip_long2quad ($quad)
1820 return long2ip($quad);
1823 function makeHref($params = array())
1825 global $head_revision, $numeric_revision, $root;
1828 if (!isset($params['r']) and ($numeric_revision != $head_revision))
1830 $params['r'] = $numeric_revision;
1832 foreach($params as $key=>$value)
1836 $ret .= urlencode($key).'='.urlencode($value);
1842 function makeHrefProcess($params = array())
1844 global $head_revision, $numeric_revision, $root, $pageno, $tabno;
1845 $ret = $root.'process.php'.'?';
1847 if ($numeric_revision != $head_revision)
1849 error_log("Can't make a process link when not in head revision");
1852 if (!isset($params['page']))
1853 $params['page'] = $pageno;
1854 if (!isset($params['tab']))
1855 $params['tab'] = $tabno;
1856 foreach($params as $key=>$value)
1860 $ret .= urlencode($key).'='.urlencode($value);
1866 function makeHrefForHelper ($helper_name, $params = array())
1868 global $head_revision, $numeric_revision, $root;
1869 $ret = $root.'popup.php'.'?helper='.$helper_name;
1870 if ($numeric_revision != $head_revision)
1872 error_log("Can't make a process link when not in head revision");
1875 foreach($params as $key=>$value)
1876 $ret .= '&'.urlencode($key).'='.urlencode($value);
1880 // Process the given list of records to build data suitable for printNiftySelect()
1881 // (like it was formerly executed by printSelect()). Screen out vendors according
1882 // to VENDOR_SIEVE, if object type ID is provided. However, the OPTGROUP with already
1883 // selected OPTION is protected from being screened.
1884 function cookOptgroups ($recordList, $object_type_id = 0, $existing_value = 0)
1887 // Always keep "other" OPTGROUP at the SELECT bottom.
1889 foreach ($recordList as $dict_key => $dict_value)
1890 if (strpos ($dict_value, '%GSKIP%') !== FALSE)
1892 $tmp = explode ('%GSKIP%', $dict_value, 2);
1893 $ret[$tmp[0]][$dict_key] = $tmp[1];
1895 elseif (strpos ($dict_value, '%GPASS%') !== FALSE)
1897 $tmp = explode ('%GPASS%', $dict_value, 2);
1898 $ret[$tmp[0]][$dict_key] = $tmp[1];
1901 $therest[$dict_key] = $dict_value;
1902 if ($object_type_id != 0)
1904 $screenlist = array();
1905 foreach (explode (';', getConfigVar ('VENDOR_SIEVE')) as $sieve)
1906 if (FALSE !== mb_ereg ("^([^@]+)(@${object_type_id})?\$", trim ($sieve), $regs))
1907 $screenlist[] = $regs[1];
1908 foreach (array_keys ($ret) as $vendor)
1909 if (in_array ($vendor, $screenlist))
1911 $ok_to_screen = TRUE;
1912 if ($existing_value)
1913 foreach (array_keys ($ret[$vendor]) as $recordkey)
1914 if ($recordkey == $existing_value)
1916 $ok_to_screen = FALSE;
1920 unset ($ret[$vendor]);
1923 $ret['other'] = $therest;
1927 function dos2unix ($text)
1929 return str_replace ("\r\n", "\n", $text);
1932 function buildPredicateTable ($parsetree)
1935 foreach ($parsetree as $sentence)
1936 if ($sentence['type'] == 'SYNT_DEFINITION')
1937 $ret[$sentence['term']] = $sentence['definition'];
1938 // Now we have predicate table filled in with the latest definitions of each
1939 // particular predicate met. This isn't as chik, as on-the-fly predicate
1940 // overloading during allow/deny scan, but quite sufficient for this task.
1944 // Take a list of records and filter against given RackCode expression. Return
1945 // the original list intact, if there was no filter requested, but return an
1946 // empty list, if there was an error.
1947 function filterCellList ($list_in, $expression = array())
1949 if ($expression === NULL)
1951 if (!count ($expression))
1953 $list_out = array();
1954 foreach ($list_in as $item_key => $item_value)
1955 if (TRUE === judgeCell ($item_value, $expression))
1956 $list_out[$item_key] = $item_value;
1960 // Tell, if the given expression is true for the given entity. Take complete record on input.
1961 function judgeCell ($cell, $expression)
1964 return eval_expression
1978 // Tell, if a constraint from config option permits given record.
1979 function considerConfiguredConstraint ($cell, $varname)
1981 if (!strlen (getConfigVar ($varname)))
1982 return TRUE; // no restriction
1984 if (!isset ($parseCache[$varname]))
1985 // getConfigVar() doesn't re-read the value from DB because of its
1986 // own cache, so there is no race condition here between two calls.
1987 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
1988 if ($parseCache[$varname]['result'] != 'ACK')
1989 return FALSE; // constraint set, but cannot be used due to compilation error
1990 return judgeCell ($cell, $parseCache[$varname]['load']);
1993 // Return list of records in the given realm, which conform to
1994 // the given RackCode expression. If the realm is unknown or text
1995 // doesn't validate as a RackCode expression, return NULL.
1996 // Otherwise (successful scan) return a list of all matched
1997 // records, even if the list is empty (array() !== NULL). If the
1998 // text is an empty string, return all found records in the given
2000 function scanRealmByText ($realm = NULL, $ftext = '')
2010 if (!strlen ($ftext = trim ($ftext)))
2014 $fparse = spotPayload ($ftext, 'SYNT_EXPR');
2015 if ($fparse['result'] != 'ACK')
2017 $fexpr = $fparse['load'];
2019 return filterCellList (listCells ($realm), $fexpr);
2026 function getIPv4VSOptions ()
2029 foreach (listCells ('ipv4vs') as $vsid => $vsinfo)
2030 $ret[$vsid] = $vsinfo['dname'] . (!strlen ($vsinfo['name']) ?
'' : " (${vsinfo['name']})");
2034 function getIPv4RSPoolOptions ()
2037 foreach (listCells ('ipv4rspool') as $pool_id => $poolInfo)
2038 $ret[$pool_id] = $poolInfo['name'];
2042 // Derive a complete cell structure from the given username regardless
2043 // if it is a local account or not.
2044 function constructUserCell ($username)
2046 if (NULL !== ($userid = getUserIDByUsername ($username)))
2047 return spotEntity ('user', $userid);
2051 'user_name' => $username,
2052 'user_realname' => '',