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