r2357 - implement previews for files
[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{
e673ee24 396 $string = strtoupper ($string);
05771508
DO
397 switch (TRUE)
398 {
399 case ($string == '' or preg_match (RE_L2_SOLID, $string)):
400 return $string;
401 case (preg_match (RE_L2_IFCFG, $string)):
402 $pieces = explode (':', $string);
403 // This workaround is for SunOS ifconfig.
404 foreach ($pieces as &$byte)
405 if (strlen ($byte) == 1)
406 $byte = '0' . $byte;
407 // And this workaround is for PHP.
408 unset ($byte);
409 return implode ('', $pieces);
410 case (preg_match (RE_L2_CISCO, $string)):
411 return implode ('', explode ('.', $string));
412 default:
413 return NULL;
414 }
e673ee24
DO
415}
416
417function l2addressFromDatabase ($string)
418{
419 switch (strlen ($string))
420 {
421 case 12: // Ethernet
422 case 16: // FireWire
423 $ret = implode (':', str_split ($string, 2));
424 break;
425 default:
426 $ret = $string;
427 break;
428 }
429 return $ret;
430}
431
432// The following 2 functions return previous and next rack IDs for
433// a given rack ID. The order of racks is the same as in renderRackspace()
434// or renderRow().
435function getPrevIDforRack ($row_id = 0, $rack_id = 0)
436{
437 if ($row_id <= 0 or $rack_id <= 0)
438 {
61e269b5 439 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
440 return NULL;
441 }
442 $rackList = getRacksForRow ($row_id);
443 doubleLink ($rackList);
444 if (isset ($rackList[$rack_id]['prev_key']))
445 return $rackList[$rack_id]['prev_key'];
446 return NULL;
447}
448
449function getNextIDforRack ($row_id = 0, $rack_id = 0)
450{
451 if ($row_id <= 0 or $rack_id <= 0)
452 {
61e269b5 453 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
454 return NULL;
455 }
456 $rackList = getRacksForRow ($row_id);
457 doubleLink ($rackList);
458 if (isset ($rackList[$rack_id]['next_key']))
459 return $rackList[$rack_id]['next_key'];
460 return NULL;
461}
462
463// This function finds previous and next array keys for each array key and
464// modifies its argument accordingly.
465function doubleLink (&$array)
466{
467 $prev_key = NULL;
468 foreach (array_keys ($array) as $key)
469 {
470 if ($prev_key)
471 {
472 $array[$key]['prev_key'] = $prev_key;
473 $array[$prev_key]['next_key'] = $key;
474 }
475 $prev_key = $key;
476 }
477}
478
e673ee24
DO
479function sortTokenize ($a, $b)
480{
481 $aold='';
482 while ($a != $aold)
483 {
484 $aold=$a;
485 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
486 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
487 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
488 }
489
490 $bold='';
491 while ($b != $bold)
492 {
493 $bold=$b;
494 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
495 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
496 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
497 }
498
499
500
501 $ar = explode(' ', $a);
502 $br = explode(' ', $b);
503 for ($i=0; $i<count($ar) && $i<count($br); $i++)
504 {
505 $ret = 0;
506 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
507 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
508 else
509 $ret = strcasecmp($ar[$i], $br[$i]);
510 if ($ret != 0)
511 return $ret;
512 }
513 if ($i<count($ar))
514 return 1;
515 if ($i<count($br))
516 return -1;
517 return 0;
518}
519
520function sortByName ($a, $b)
521{
522 return sortTokenize($a['name'], $b['name']);
523}
524
e673ee24
DO
525function sortEmptyPorts ($a, $b)
526{
527 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
528 if ($objname_cmp == 0)
529 {
530 return sortTokenize($a['Port_name'], $b['Port_name']);
531 }
532 return $objname_cmp;
533}
534
535function sortObjectAddressesAndNames ($a, $b)
536{
537 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
538 if ($objname_cmp == 0)
539 {
79f22c3d
DO
540 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
541 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
542 $objname_cmp = sortTokenize($name_a, $name_b);
e673ee24 543 if ($objname_cmp == 0)
e673ee24 544 sortTokenize($a['ip'], $b['ip']);
e673ee24
DO
545 return $objname_cmp;
546 }
547 return $objname_cmp;
548}
549
e673ee24
DO
550function sortAddresses ($a, $b)
551{
552 $name_cmp = sortTokenize($a['name'], $b['name']);
553 if ($name_cmp == 0)
554 {
555 return sortTokenize($a['ip'], $b['ip']);
556 }
557 return $name_cmp;
558}
559
560// This function expands port compat list into a matrix.
561function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
562{
563 $matrix = array();
564 // Create type matrix and markup compatible types.
565 foreach (array_keys ($portTypeList) as $type1)
566 foreach (array_keys ($portTypeList) as $type2)
567 $matrix[$type1][$type2] = FALSE;
568 foreach ($portCompatList as $pair)
569 $matrix[$pair['type1']][$pair['type2']] = TRUE;
570 return $matrix;
571}
572
c31cd72c 573// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
574// if FQDN is set. The next choice is object's common name, if it looks like a
575// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 576// object is returned (which may appear 0 and more elements long).
f321b50a 577function findAllEndpoints ($object_id, $fallback = '')
c31cd72c
DO
578{
579 $values = getAttrValues ($object_id);
580 foreach ($values as $record)
f321b50a 581 if ($record['name'] == 'FQDN' && !empty ($record['value']))
c31cd72c 582 return array ($record['value']);
c31cd72c 583 $regular = array();
85970da2
DO
584 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
585 if ($alloc['type'] == 'regular')
586 $regular[] = $dottedquad;
f321b50a
DO
587 if (!count ($regular) && !empty ($fallback))
588 return array ($fallback);
c31cd72c
DO
589 return $regular;
590}
591
83ba6670
DO
592// Some records in the dictionary may be written as plain text or as Wiki
593// link in the following syntax:
594// 1. word
595// 2. [[word URL]] // FIXME: this isn't working
596// 3. [[word word word | URL]]
597// This function parses the line and returns text suitable for either A
598// (rendering <A HREF>) or O (for <OPTION>).
24cbe8af 599function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
83ba6670 600{
010231c2 601 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af
DO
602 {
603 if ($strip_optgroup)
f0b540a3 604 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
24cbe8af
DO
605 else
606 return $line;
607 }
010231c2
DO
608 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
609 $s = explode ('|', $line);
83ba6670 610 $o_value = trim ($s[0]);
24cbe8af 611 if ($strip_optgroup)
f0b540a3 612 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
83ba6670
DO
613 $a_value = trim ($s[1]);
614 if ($which == 'a')
010231c2 615 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
616 if ($which == 'o')
617 return $o_value;
618}
619
2de490b7
DO
620function buildVServiceName ($vsinfo = NULL)
621{
622 if ($vsinfo == NULL)
623 {
624 showError ('NULL argument', __FUNCTION__);
625 return NULL;
626 }
8d790216 627 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
2de490b7
DO
628}
629
05411ccd
DO
630function buildRSPoolName ($rspool = NULL)
631{
632 if ($rspool == NULL)
633 {
634 showError ('NULL argument', __FUNCTION__);
635 return NULL;
636 }
637 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
638}
639
177b1e9b
DO
640// rackspace usage for a single rack
641// (T + W + U) / (height * 3 - A)
11df133a 642function getRSUforRack ($data = NULL)
177b1e9b 643{
11df133a 644 if ($data == NULL)
177b1e9b
DO
645 {
646 showError ('Invalid argument', __FUNCTION__);
647 return NULL;
648 }
6ffba290 649 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
650 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
651 for ($locidx = 0; $locidx < 3; $locidx++)
652 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 653 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
654}
655
11df133a
DO
656// Same for row.
657function getRSUforRackRow ($rowData = NULL)
658{
bb26a59e 659 if ($rowData === NULL)
11df133a
DO
660 {
661 showError ('Invalid argument', __FUNCTION__);
662 return NULL;
663 }
bb26a59e
DO
664 if (!count ($rowData))
665 return 0;
11df133a 666 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 667 $total_height = 0;
dfa3c075
DO
668 foreach (array_keys ($rowData) as $rack_id)
669 {
670 $data = getRackData ($rack_id);
671 $total_height += $data['height'];
11df133a
DO
672 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
673 for ($locidx = 0; $locidx < 3; $locidx++)
674 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
675 }
676 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
677}
678
abef7149
DO
679// Return a list of object IDs, which can be found in the given rackspace block.
680function stuffInRackspace ($rackData)
f1a0477d
DO
681{
682 $objects = array();
683 for ($i = $rackData['height']; $i > 0; $i--)
684 for ($locidx = 0; $locidx < 3; $locidx++)
685 if
686 (
687 $rackData[$i][$locidx]['state'] == 'T' and
688 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
689 )
690 $objects[] = $rackData[$i][$locidx]['object_id'];
abef7149 691 return $objects;
f1a0477d
DO
692}
693
9af110b4
DO
694// Make sure the string is always wrapped with LF characters
695function lf_wrap ($str)
696{
697 $ret = trim ($str, "\r\n");
698 if (!empty ($ret))
699 $ret .= "\n";
700 return $ret;
701}
702
e6e7d8b3
DO
703// Adopted from Mantis BTS code.
704function string_insert_hrefs ($s)
705{
706 if (getConfigVar ('DETECT_URLS') != 'yes')
707 return $s;
708 # Find any URL in a string and replace it by a clickable link
709 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
710 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
711 $s);
712 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
713 '<a href="mailto:\0">\0</a>',
714 $s);
715 return $s;
716}
717
718// Idem.
719function email_regex_simple ()
720{
721 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
722 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
723}
724
118e4c38
DO
725// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
726// for the requested object_type_id.
727function getAutoPorts ($type_id)
728{
729 $ret = array();
730 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
731 foreach ($typemap as $equation)
732 {
733 $tmp = explode ('=', $equation);
734 if (count ($tmp) != 2)
735 continue;
736 $objtype_id = $tmp[0];
737 if ($objtype_id != $type_id)
738 continue;
739 $portlist = $tmp[1];
740 foreach (explode ('+', $portlist) as $product)
741 {
742 $tmp = explode ('*', $product);
743 if (count ($tmp) != 3)
744 continue;
745 $nports = $tmp[0];
746 $port_type = $tmp[1];
747 $format = $tmp[2];
748 for ($i = 0; $i < $nports; $i++)
749 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
750 }
751 }
752 return $ret;
753}
754
9dfd4cc9
DO
755// Find if a particular tag id exists on the tree, then attach the
756// given child tag to it. If the parent tag doesn't exist, return FALSE.
51b6651a 757function attachChildTag (&$tree, $parent_id, $child_id, $child_info, $threshold = 0)
9dfd4cc9 758{
51b6651a 759 $self = __FUNCTION__;
048b53b9 760 foreach (array_keys ($tree) as $tagid)
9dfd4cc9
DO
761 {
762 if ($tagid == $parent_id)
763 {
51b6651a
DO
764 if (!$threshold or ($threshold and $tree[$tagid]['kidc'] + 1 < $threshold))
765 $tree[$tagid]['kids'][$child_id] = $child_info;
766 // Reset the list only once.
767 if (++$tree[$tagid]['kidc'] == $threshold)
768 $tree[$tagid]['kids'] = array();
9dfd4cc9
DO
769 return TRUE;
770 }
51b6651a 771 elseif ($self ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info, $threshold))
9dfd4cc9
DO
772 return TRUE;
773 }
774 return FALSE;
775}
776
d65353ad
DO
777// Build a tree from the item list and return it. Input and output data is
778// indexed by item id (nested items in output are recursively stored in 'kids'
51b6651a
DO
779// key, which is in turn indexed by id. Functions, which are ready to handle
780// tree collapsion/expansion themselves, may request non-zero threshold value
781// for smaller resulting tree.
782function treeFromList ($mytaglist, $threshold = 0)
d65353ad 783{
20c901a7
DO
784 $ret = array();
785 while (count ($mytaglist) > 0)
9dfd4cc9
DO
786 {
787 $picked = FALSE;
20c901a7 788 foreach ($mytaglist as $tagid => $taginfo)
9dfd4cc9 789 {
51b6651a 790 $taginfo['kidc'] = 0;
9dfd4cc9
DO
791 $taginfo['kids'] = array();
792 if ($taginfo['parent_id'] == NULL)
793 {
20c901a7 794 $ret[$tagid] = $taginfo;
9dfd4cc9 795 $picked = TRUE;
20c901a7 796 unset ($mytaglist[$tagid]);
9dfd4cc9 797 }
51b6651a 798 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo, $threshold))
9dfd4cc9
DO
799 {
800 $picked = TRUE;
20c901a7 801 unset ($mytaglist[$tagid]);
9dfd4cc9
DO
802 }
803 }
804 if (!$picked) // Only orphaned items on the list.
805 break;
806 }
20c901a7 807 return $ret;
9dfd4cc9
DO
808}
809
49fb1027
DO
810// Build a tree from the tag list and return everything _except_ the tree.
811function getOrphanedTags ()
812{
813 global $taglist;
814 $mytaglist = $taglist;
815 $dummy = array();
816 while (count ($mytaglist) > 0)
817 {
818 $picked = FALSE;
819 foreach ($mytaglist as $tagid => $taginfo)
820 {
4f92bb6d 821 $taginfo['kidc'] = 0;
49fb1027
DO
822 $taginfo['kids'] = array();
823 if ($taginfo['parent_id'] == NULL)
824 {
825 $dummy[$tagid] = $taginfo;
826 $picked = TRUE;
827 unset ($mytaglist[$tagid]);
828 }
829 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
830 {
831 $picked = TRUE;
832 unset ($mytaglist[$tagid]);
833 }
834 }
835 if (!$picked) // Only orphaned items on the list.
836 return $mytaglist;
837 }
838 return array();
839}
840
6e49bd1f 841function serializeTags ($chain, $baseurl = '')
ba93bd98
DO
842{
843 $comma = '';
844 $ret = '';
6e49bd1f 845 foreach ($chain as $taginfo)
ba93bd98 846 {
e2ac59cf
DO
847 $ret .= $comma .
848 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
849 $taginfo['tag'] .
850 ($baseurl == '' ? '' : '</a>');
ba93bd98
DO
851 $comma = ', ';
852 }
853 return $ret;
854}
855
3b81cb98
DO
856// For each tag add all its parent tags onto the list. Don't expect anything
857// except user's tags on the chain.
858function getTagChainExpansion ($chain, $tree = NULL)
ba93bd98 859{
51b6651a 860 $self = __FUNCTION__;
3b81cb98
DO
861 if ($tree === NULL)
862 {
863 global $tagtree;
864 $tree = $tagtree;
865 }
ba93bd98 866 // For each tag find its path from the root, then combine items
6e49bd1f 867 // of all paths and add them to the chain, if they aren't there yet.
ba93bd98
DO
868 $ret = array();
869 foreach ($tree as $taginfo1)
870 {
871 $hit = FALSE;
6e49bd1f 872 foreach ($chain as $taginfo2)
ba93bd98
DO
873 if ($taginfo1['id'] == $taginfo2['id'])
874 {
875 $hit = TRUE;
876 break;
877 }
878 if (count ($taginfo1['kids']) > 0)
879 {
3b81cb98 880 $subsearch = $self ($chain, $taginfo1['kids']);
ba93bd98
DO
881 if (count ($subsearch))
882 {
883 $hit = TRUE;
884 $ret = array_merge ($ret, $subsearch);
885 }
886 }
887 if ($hit)
888 $ret[] = $taginfo1;
889 }
890 return $ret;
891}
892
ba93bd98
DO
893// Return the list of missing implicit tags.
894function getImplicitTags ($oldtags)
895{
896 $ret = array();
6e49bd1f 897 $newtags = getTagChainExpansion ($oldtags);
ba93bd98
DO
898 foreach ($newtags as $newtag)
899 {
900 $already_exists = FALSE;
901 foreach ($oldtags as $oldtag)
902 if ($newtag['id'] == $oldtag['id'])
903 {
904 $already_exists = TRUE;
905 break;
906 }
907 if ($already_exists)
908 continue;
d6089951 909 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
ba93bd98
DO
910 }
911 return $ret;
912}
913
6e49bd1f
DO
914// Minimize the chain: exclude all implicit tags and return the result.
915function getExplicitTagsOnly ($chain, $tree = NULL)
ab379543 916{
51b6651a 917 $self = __FUNCTION__;
20c901a7 918 global $tagtree;
ab379543 919 if ($tree === NULL)
20c901a7 920 $tree = $tagtree;
ab379543
DO
921 $ret = array();
922 foreach ($tree as $taginfo)
923 {
924 if (isset ($taginfo['kids']))
925 {
51b6651a 926 $harvest = $self ($chain, $taginfo['kids']);
ab379543
DO
927 if (count ($harvest) > 0)
928 {
929 $ret = array_merge ($ret, $harvest);
930 continue;
931 }
932 }
933 // This tag isn't implicit, test is for being explicit.
6e49bd1f 934 foreach ($chain as $testtag)
ab379543
DO
935 if ($taginfo['id'] == $testtag['id'])
936 {
937 $ret[] = $testtag;
938 break;
939 }
940 }
941 return $ret;
942}
943
6e49bd1f 944// Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
74ccacff 945// Unlike other functions, this one accepts and returns a list of integer tag IDs, not
e07bb730 946// a list of tag structures. Same structure (tag ID list) is returned after processing.
74ccacff
DO
947function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
948{
51b6651a 949 $self = __FUNCTION__;
20c901a7 950 global $tagtree;
74ccacff 951 if ($tree === NULL)
20c901a7 952 $tree = $tagtree;
74ccacff
DO
953 $getallkids = $getall;
954 $ret = array();
955 foreach ($tree as $taginfo)
956 {
957 foreach ($idlist as $test_id)
958 if ($getall or $taginfo['id'] == $test_id)
959 {
960 $ret[] = $taginfo['id'];
961 // Once matched node makes all sub-nodes match, but don't make
962 // a mistake of matching every other node at the current level.
963 $getallkids = TRUE;
964 break;
965 }
966 if (isset ($taginfo['kids']))
51b6651a 967 $ret = array_merge ($ret, $self ($idlist, $taginfo['kids'], $getallkids));
74ccacff
DO
968 $getallkids = FALSE;
969 }
970 return $ret;
971}
972
cce6b057
DO
973function getUserAutoTags ($username = NULL)
974{
975 global $remote_username, $accounts;
976 if ($username == NULL)
977 $username = $remote_username;
978 $ret = array();
979 $ret[] = array ('tag' => '$username_' . $username);
980 if (isset ($accounts[$username]['user_id']))
981 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
982 return $ret;
983}
984
68225375 985function loadRackObjectAutoTags ()
ba93bd98 986{
2c6c7645 987 assertUIntArg ('object_id', __FUNCTION__);
2fb24351
DO
988 $object_id = $_REQUEST['object_id'];
989 $oinfo = getObjectInfo ($object_id);
990 $ret = array();
0e692350 991 $ret[] = array ('tag' => '$id_' . $object_id);
fae80c2b 992 $ret[] = array ('tag' => '$typeid_' . $oinfo['objtype_id']);
d817ba03 993 $ret[] = array ('tag' => '$any_object');
c396cbf4
DO
994 if (validTagName ($oinfo['name']))
995 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
2fb24351
DO
996 return $ret;
997}
998
68225375 999// Common code for both prefix and address tag listers.
e1ae3fb4
AD
1000function loadFileAutoTags ()
1001{
1002 assertUIntArg ('file_id', __FUNCTION__);
1003 $ret = array();
1004 $ret[] = array ('tag' => '$fileid_' . $_REQUEST['file_id']);
1005 $ret[] = array ('tag' => '$any_file');
1006 return $ret;
1007}
1008
bb0a44e9 1009function getIPv4PrefixTags ($netid)
f9bc186f 1010{
bb0a44e9 1011 $netinfo = getIPv4NetworkInfo ($netid);
f9bc186f 1012 $ret = array();
bb0a44e9 1013 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $netinfo['ip']) . '-' . $netinfo['mask']);
da958e52
DO
1014 // FIXME: find and list tags for all parent networks?
1015 $ret[] = array ('tag' => '$any_ip4net');
d817ba03 1016 $ret[] = array ('tag' => '$any_net');
41bd8c87
DO
1017 return $ret;
1018}
1019
68225375 1020function loadIPv4PrefixAutoTags ()
41bd8c87 1021{
68225375
DO
1022 assertUIntArg ('id', __FUNCTION__);
1023 return array_merge
1024 (
da958e52 1025 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
bb0a44e9 1026 getIPv4PrefixTags ($_REQUEST['id'])
68225375 1027 );
d817ba03
DO
1028}
1029
68225375 1030function loadIPv4AddressAutoTags ()
d817ba03 1031{
2c6c7645 1032 assertIPv4Arg ('ip', __FUNCTION__);
68225375
DO
1033 return array_merge
1034 (
da958e52 1035 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
bb0a44e9 1036 getIPv4PrefixTags (getIPv4AddressNetworkId ($_REQUEST['ip']))
68225375
DO
1037 );
1038}
1039
1040function loadRackAutoTags ()
1041{
1042 assertUIntArg ('rack_id', __FUNCTION__);
d817ba03 1043 $ret = array();
da958e52 1044 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
68225375 1045 $ret[] = array ('tag' => '$any_rack');
d817ba03
DO
1046 return $ret;
1047}
1048
68225375 1049function loadIPv4VSAutoTags ()
d817ba03 1050{
49fb2686 1051 assertUIntArg ('vs_id', __FUNCTION__);
d817ba03 1052 $ret = array();
0e692350 1053 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
d817ba03
DO
1054 $ret[] = array ('tag' => '$any_ipv4vs');
1055 $ret[] = array ('tag' => '$any_vs');
1056 return $ret;
1057}
1058
68225375 1059function loadIPv4RSPoolAutoTags ()
d817ba03 1060{
2c6c7645 1061 assertUIntArg ('pool_id', __FUNCTION__);
d817ba03 1062 $ret = array();
0e692350
DO
1063 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1064 $ret[] = array ('tag' => '$any_ipv4rsp');
1065 $ret[] = array ('tag' => '$any_rsp');
f9bc186f
DO
1066 return $ret;
1067}
1068
abef7149
DO
1069// Check, if the given tag is present on the chain (will only work
1070// for regular tags with tag ID set.
1071function tagOnChain ($taginfo, $tagchain)
1072{
1073 if (!isset ($taginfo['id']))
1074 return FALSE;
1075 foreach ($tagchain as $test)
1076 if ($test['id'] == $taginfo['id'])
1077 return TRUE;
1078 return FALSE;
1079}
1080
1081// Idem, but use ID list instead of chain.
1082function tagOnIdList ($taginfo, $tagidlist)
1083{
1084 if (!isset ($taginfo['id']))
1085 return FALSE;
1086 foreach ($tagidlist as $tagid)
61a61189 1087 if ($taginfo['id'] == $tagid)
abef7149
DO
1088 return TRUE;
1089 return FALSE;
1090}
1091
1092// Return TRUE, if two tags chains differ (order of tags doesn't matter).
1093// Assume, that neither of the lists contains duplicates.
1094// FIXME: a faster, than O(x^2) method is possible for this calculation.
1095function tagChainCmp ($chain1, $chain2)
1096{
1097 if (count ($chain1) != count ($chain2))
1098 return TRUE;
1099 foreach ($chain1 as $taginfo1)
1100 if (!tagOnChain ($taginfo1, $chain2))
1101 return TRUE;
1102 return FALSE;
1103}
1104
53bae67b
DO
1105// If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1106// hold all appropriate (explicit and implicit) tags respectively.
1107// Otherwise some limited redirection is necessary (only page and tab
1108// names are preserved, ophandler name change isn't handled).
da958e52
DO
1109function fixContext ()
1110{
1111 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
53bae67b
DO
1112
1113 $pmap = array
1114 (
1115 'accounts' => 'userlist',
1116 'rspools' => 'ipv4rsplist',
1117 'rspool' => 'ipv4rsp',
1118 'vservices' => 'ipv4vslist',
1119 'vservice' => 'ipv4vs',
1120 );
1121 $tmap = array();
1122 $tmap['objects']['newmulti'] = 'addmore';
1123 $tmap['objects']['newobj'] = 'addmore';
1124 $tmap['object']['switchvlans'] = 'livevlans';
1125 $tmap['object']['slb'] = 'editrspvs';
72d8ced3
DO
1126 $tmap['object']['portfwrd'] = 'nat4';
1127 $tmap['object']['network'] = 'ipv4';
53bae67b
DO
1128 if (isset ($pmap[$pageno]))
1129 redirectUser ($pmap[$pageno], $tabno);
1130 if (isset ($tmap[$pageno][$tabno]))
1131 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1132
da958e52
DO
1133 if (isset ($page[$pageno]['autotagloader']))
1134 $auto_tags = $page[$pageno]['autotagloader'] ();
1135 if
1136 (
1137 isset ($page[$pageno]['tagloader']) and
1138 isset ($page[$pageno]['bypass']) and
1139 isset ($_REQUEST[$page[$pageno]['bypass']])
1140 )
1141 {
1142 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1143 $impl_tags = getImplicitTags ($expl_tags);
1144 }
1145}
1146
abef7149
DO
1147// Take a list of user-supplied tag IDs to build a list of valid taginfo
1148// records indexed by tag IDs (tag chain).
6e49bd1f 1149function buildTagChainFromIds ($tagidlist)
ab379543 1150{
20c901a7 1151 global $taglist;
ab379543 1152 $ret = array();
abef7149 1153 foreach (array_unique ($tagidlist) as $tag_id)
ab379543
DO
1154 if (isset ($taglist[$tag_id]))
1155 $ret[] = $taglist[$tag_id];
1156 return $ret;
1157}
1158
7cc02fc1
DO
1159// Process a given tag tree and return only meaningful branches. The resulting
1160// (sub)tree will have refcnt leaves on every last branch.
1161function getObjectiveTagTree ($tree, $realm)
1162{
51b6651a 1163 $self = __FUNCTION__;
7cc02fc1
DO
1164 $ret = array();
1165 foreach ($tree as $taginfo)
1166 {
1167 $subsearch = array();
1168 $pick = FALSE;
1169 if (count ($taginfo['kids']))
1170 {
51b6651a 1171 $subsearch = $self ($taginfo['kids'], $realm);
7cc02fc1
DO
1172 $pick = count ($subsearch) > 0;
1173 }
5bdc04ec 1174 if (isset ($taginfo['refcnt'][$realm]))
7cc02fc1
DO
1175 $pick = TRUE;
1176 if (!$pick)
1177 continue;
1178 $ret[] = array
1179 (
1180 'id' => $taginfo['id'],
1181 'tag' => $taginfo['tag'],
1182 'parent_id' => $taginfo['parent_id'],
1183 'refcnt' => $taginfo['refcnt'],
1184 'kids' => $subsearch
1185 );
1186 }
1187 return $ret;
1188}
1189
a0d54e7e 1190function getTagFilter ()
7cc02fc1 1191{
a0d54e7e 1192 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
7cc02fc1
DO
1193}
1194
a0d54e7e 1195function getTagFilterStr ($tagfilter = array())
932cf41f 1196{
a0d54e7e 1197 $ret = '';
6e49bd1f 1198 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
a0d54e7e
DO
1199 $ret .= "&tagfilter[]=" . $taginfo['id'];
1200 return $ret;
932cf41f 1201}
a0d54e7e 1202
baf37d01 1203function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
da958e52 1204{
46f92ff7 1205 global $root, $page, $pageno, $tabno;
baf37d01
DO
1206 if ($nextpage === NULL)
1207 $nextpage = $pageno;
1208 if ($nexttab === NULL)
1209 $nexttab = $tabno;
1210 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1211 if (isset ($page[$nextpage]['bypass']))
1212 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
0f3c6639 1213 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
da958e52
DO
1214 return $url;
1215}
1216
135080d8 1217function buildRedirectURL ($callfunc, $status, $args = array(), $nextpage = NULL, $nexttab = NULL)
46f92ff7 1218{
7647f857 1219 global $pageno, $tabno;
baf37d01
DO
1220 if ($nextpage === NULL)
1221 $nextpage = $pageno;
1222 if ($nexttab === NULL)
1223 $nexttab = $tabno;
135080d8 1224 return buildWideRedirectURL (oneLiner (getMessageCode ($callfunc, $status), $args), $nextpage, $nexttab);
2987fc1f
DO
1225}
1226
1227// Return a message log consisting of only one message.
1228function oneLiner ($code, $args = array())
1229{
1230 $ret = array ('v' => 2);
1231 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1232 return $ret;
46f92ff7
DO
1233}
1234
f19c75d6 1235// Return mesage code by status code.
135080d8 1236function getMessageCode ($callfunc, $status)
f19c75d6 1237{
135080d8
DO
1238 global $msgcode;
1239 return $msgcode[$callfunc][$status];
f19c75d6
DO
1240}
1241
9f54e6e9 1242function validTagName ($s, $allow_autotag = FALSE)
2eeeca80 1243{
9f54e6e9
DO
1244 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1245 return TRUE;
1246 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1247 return TRUE;
1248 return FALSE;
2eeeca80
DO
1249}
1250
53bae67b
DO
1251function redirectUser ($p, $t)
1252{
1253 global $page, $root;
1254 $l = "{$root}?page=${p}&tab=${t}";
1255 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1256 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1257 header ("Location: " . $l);
1258 die;
1259}
1260
9f3e5caa
DO
1261function getRackCodeStats ()
1262{
1263 global $rackCode;
1264 $defc = $grantc = 0;
1265 foreach ($rackCode as $s)
1266 switch ($s['type'])
1267 {
1268 case 'SYNT_DEFINITION':
1269 $defc++;
1270 break;
1271 case 'SYNT_GRANT':
1272 $grantc++;
1273 break;
1274 default:
1275 break;
1276 }
1277 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1278 return $ret;
1279}
1280
d5157018
DO
1281function getRackImageWidth ()
1282{
1283 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1284}
1285
1286function getRackImageHeight ($units)
1287{
1288 return 3 + 3 + $units * 2;
1289}
1290
2987fc1f
DO
1291// Perform substitutions and return resulting string
1292// used solely by buildLVSConfig()
1293function apply_macros ($macros, $subject)
1294{
1295 $ret = $subject;
1296 foreach ($macros as $search => $replace)
1297 $ret = str_replace ($search, $replace, $ret);
1298 return $ret;
1299}
1300
1301function buildLVSConfig ($object_id = 0)
1302{
1303 if ($object_id <= 0)
1304 {
1305 showError ('Invalid argument', __FUNCTION__);
1306 return;
1307 }
1308 $oInfo = getObjectInfo ($object_id);
1309 $lbconfig = getSLBConfig ($object_id);
1310 if ($lbconfig === NULL)
1311 {
1312 showError ('getSLBConfig() failed', __FUNCTION__);
1313 return;
1314 }
1315 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1316 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1317 foreach ($lbconfig as $vs_id => $vsinfo)
1318 {
1319 $newconfig .= "########################################################\n" .
1320 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1321 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1322 "########################################################\n";
1323 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1324 $macros = array
1325 (
1326 '%VIP%' => $vsinfo['vip'],
1327 '%VPORT%' => $vsinfo['vport'],
1328 '%PROTO%' => $vsinfo['proto'],
1329 '%VNAME%' => $vsinfo['vs_name'],
1330 '%RSPOOLNAME%' => $vsinfo['pool_name']
1331 );
1332 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1333 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1334 $newconfig .= apply_macros
1335 (
1336 $macros,
1337 lf_wrap ($vsinfo['vs_vsconfig']) .
1338 lf_wrap ($vsinfo['lb_vsconfig']) .
1339 lf_wrap ($vsinfo['pool_vsconfig'])
1340 );
1341 foreach ($vsinfo['rslist'] as $rs)
1342 {
79a9edb4
DO
1343 if (empty ($rs['rsport']))
1344 $rs['rsport'] = $vsinfo['vport'];
2987fc1f
DO
1345 $macros['%RSIP%'] = $rs['rsip'];
1346 $macros['%RSPORT%'] = $rs['rsport'];
1347 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1348 $newconfig .= apply_macros
1349 (
1350 $macros,
1351 lf_wrap ($vsinfo['vs_rsconfig']) .
1352 lf_wrap ($vsinfo['lb_rsconfig']) .
1353 lf_wrap ($vsinfo['pool_rsconfig']) .
1354 lf_wrap ($rs['rs_rsconfig'])
1355 );
1356 $newconfig .= "\t}\n";
1357 }
1358 $newconfig .= "}\n\n\n";
1359 }
3dd72e34
DO
1360 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1361 return str_replace ("\r", '', $newconfig);
2987fc1f
DO
1362}
1363
2d318652
DO
1364// Indicate occupation state of each IP address: none, ordinary or problematic.
1365function markupIPv4AddrList (&$addrlist)
1366{
1367 foreach (array_keys ($addrlist) as $ip_bin)
1368 {
d983f70a
DO
1369 $refc = array
1370 (
00c5d8cb
DO
1371 'shared' => 0, // virtual
1372 'virtual' => 0, // loopback
1373 'regular' => 0, // connected host
1374 'router' => 0 // connected gateway
d983f70a
DO
1375 );
1376 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1377 $refc[$a['type']]++;
00c5d8cb 1378 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
d983f70a
DO
1379 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1380 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
2d318652
DO
1381
1382 if ($nrealms == 1)
1383 $addrlist[$ip_bin]['class'] = 'trbusy';
1384 elseif ($nrealms > 1)
1385 $addrlist[$ip_bin]['class'] = 'trerror';
1386 else
1387 $addrlist[$ip_bin]['class'] = '';
1388 }
1389}
1390
04d619d0
DO
1391// Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1392function findRouters ($addrlist)
1393{
1394 $ret = array();
1395 foreach ($addrlist as $addr)
1396 foreach ($addr['allocs'] as $alloc)
1397 if ($alloc['type'] == 'router')
1398 $ret[] = array
1399 (
1400 'id' => $alloc['object_id'],
1401 'iface' => $alloc['name'],
1402 'dname' => $alloc['object_name'],
1403 'addr' => $addr['ip']
1404 );
1405 return $ret;
1406}
1407
fb7a4967
DO
1408// Assist in tag chain sorting.
1409function taginfoCmp ($tagA, $tagB)
1410{
1411 return $tagA['ci'] - $tagB['ci'];
1412}
1413
1327d9dd
DO
1414// Compare networks. When sorting a tree, the records on the list will have
1415// distinct base IP addresses.
3444ecf2
DO
1416// "The comparison function must return an integer less than, equal to, or greater
1417// than zero if the first argument is considered to be respectively less than,
1418// equal to, or greater than the second." (c) PHP manual
1327d9dd
DO
1419function IPv4NetworkCmp ($netA, $netB)
1420{
2d75c30b
DO
1421 // There's a problem just substracting one u32 integer from another,
1422 // because the result may happen big enough to become a negative i32
1423 // integer itself (PHP tries to cast everything it sees to signed int)
3444ecf2
DO
1424 // The comparison below must treat positive and negative values of both
1425 // arguments.
1426 // Equal values give instant decision regardless of their [equal] sign.
1427 if ($netA['ip_bin'] == $netB['ip_bin'])
2d75c30b 1428 return 0;
3444ecf2
DO
1429 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1430 // 0x00000001~0x7fffffff 1~2147483647
1431 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1432 // 0x80000000~0xffffffff -2147483648~-1
1433 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1434 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1435 if ($signA == $signB)
1436 {
1437 if ($netA['ip_bin'] > $netB['ip_bin'])
1438 return 1;
1439 else
1440 return -1;
1441 }
1442 else // With only one of two values being negative, it... wins!
1443 {
1444 if ($netA['ip_bin'] < $netB['ip_bin'])
1445 return 1;
1446 else
1447 return -1;
1448 }
1327d9dd
DO
1449}
1450
fb7a4967 1451// Modify the given tag tree so, that each level's items are sorted alphabetically.
1327d9dd 1452function sortTree (&$tree, $sortfunc = '')
fb7a4967 1453{
1327d9dd
DO
1454 if (empty ($sortfunc))
1455 return;
51b6651a 1456 $self = __FUNCTION__;
1327d9dd 1457 usort ($tree, $sortfunc);
fb7a4967
DO
1458 // Don't make a mistake of directly iterating over the items of current level, because this way
1459 // the sorting will be performed on a _copy_ if each item, not the item itself.
1460 foreach (array_keys ($tree) as $tagid)
51b6651a 1461 $self ($tree[$tagid]['kids'], $sortfunc);
fb7a4967
DO
1462}
1463
0137d53c
DO
1464function iptree_fill (&$netdata)
1465{
1466 if (!isset ($netdata['kids']) or empty ($netdata['kids']))
1467 return;
a987ff52 1468 // If we really have nested prefixes, they must fit into the tree.
0137d53c
DO
1469 $worktree = array
1470 (
1471 'ip_bin' => $netdata['ip_bin'],
1472 'mask' => $netdata['mask']
1473 );
1474 foreach ($netdata['kids'] as $pfx)
1475 iptree_embed ($worktree, $pfx);
1476 $netdata['kids'] = iptree_construct ($worktree);
1477 $netdata['kidc'] = count ($netdata['kids']);
1478}
1479
1480function iptree_construct ($node)
1481{
1482 $self = __FUNCTION__;
1483
1484 if (!isset ($node['right']))
1485 {
1486 if (!isset ($node['ip']))
1487 {
1488 $node['ip'] = long2ip ($node['ip_bin']);
1489 $node['kids'] = array();
fec0c8da 1490 $node['kidc'] = 0;
0137d53c
DO
1491 $node['name'] = '';
1492 }
1493 return array ($node);
1494 }
1495 else
1496 return array_merge ($self ($node['left']), $self ($node['right']));
1497}
1498
1499function iptree_embed (&$node, $pfx)
1500{
1501 $self = __FUNCTION__;
1502
1503 // hit?
1504 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1505 {
1506 $node = $pfx;
1507 return;
1508 }
1509 if ($node['mask'] == $pfx['mask'])
1510 {
1511 showError ('Internal error, the recurring loop lost control', __FUNCTION__);
1512 die;
1513 }
1514
1515 // split?
1516 if (!isset ($node['right']))
1517 {
a987ff52
DO
1518 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
1519 $node['left']['mask'] = $node['mask'] + 1;
0137d53c 1520 $node['left']['ip_bin'] = $node['ip_bin'];
a987ff52
DO
1521 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
1522 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] | binInvMaskFromDec ($node['left']['mask']));
1523
1524 $node['right']['mask'] = $node['mask'] + 1;
0137d53c 1525 $node['right']['ip_bin'] = $node['ip_bin'] + binInvMaskFromDec ($node['mask'] + 1) + 1;
a987ff52
DO
1526 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
1527 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] | binInvMaskFromDec ($node['right']['mask']));
0137d53c
DO
1528 }
1529
1530 // repeat!
1531 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1532 $self ($node['left'], $pfx);
1533 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1534 $self ($node['right'], $pfx);
1535 else
1536 {
1537 showError ('Internal error, cannot decide between left and right', __FUNCTION__);
1538 die;
1539 }
1540}
1541
3b81cb98 1542function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
0137d53c
DO
1543{
1544 if (empty ($func))
1545 return;
1546 $self = __FUNCTION__;
1547 foreach (array_keys ($tree) as $key)
1548 {
1549 $func ($tree[$key]);
c3315231
DO
1550 if (!empty ($stopfunc) and $stopfunc ($tree[$key]))
1551 continue;
0137d53c
DO
1552 $self ($tree[$key]['kids'], $func);
1553 }
1554}
1555
a987ff52
DO
1556function loadIPv4AddrList (&$netinfo)
1557{
1558 loadOwnIPv4Addresses ($netinfo);
1559 markupIPv4AddrList ($netinfo['addrlist']);
1560}
b18d26dc 1561
b6b87070 1562function countOwnIPv4Addresses (&$node)
b18d26dc 1563{
b6b87070 1564 $toscan = array();
737a3f72 1565 $node['addrt'] = 0;
4d0dbd87
DO
1566 $node['mask_bin'] = binMaskFromDec ($node['mask']);
1567 $node['mask_bin_inv'] = binInvMaskFromDec ($node['mask']);
1568 $node['db_first'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] & $node['mask_bin']);
1569 $node['db_last'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] | ($node['mask_bin_inv']));
b6b87070 1570 if (empty ($node['kids']))
737a3f72 1571 {
f7414fa5 1572 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
737a3f72
DO
1573 $node['addrt'] = binInvMaskFromDec ($node['mask']) + 1;
1574 }
b18d26dc 1575 else
b6b87070 1576 foreach ($node['kids'] as $nested)
b18d26dc 1577 if (!isset ($nested['id'])) // spare
737a3f72 1578 {
f7414fa5 1579 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
737a3f72
DO
1580 $node['addrt'] += binInvMaskFromDec ($nested['mask']) + 1;
1581 }
4d0dbd87
DO
1582 // Don't do anything more, because the displaying function will load the addresses anyway.
1583 return;
f7414fa5 1584 $node['addrc'] = count (scanIPv4Space ($toscan));
b6b87070
DO
1585}
1586
c3315231
DO
1587function nodeIsCollapsed ($node)
1588{
1589 return $node['symbol'] == 'node-collapsed';
1590}
1591
b6b87070
DO
1592function loadOwnIPv4Addresses (&$node)
1593{
1594 $toscan = array();
1595 if (empty ($node['kids']))
f7414fa5 1596 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
b6b87070
DO
1597 else
1598 foreach ($node['kids'] as $nested)
1599 if (!isset ($nested['id'])) // spare
f7414fa5
DO
1600 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1601 $node['addrlist'] = scanIPv4Space ($toscan);
b6b87070 1602 $node['addrc'] = count ($node['addrlist']);
b18d26dc
DO
1603}
1604
fec0c8da
DO
1605function prepareIPv4Tree ($netlist, $expanded_id = 0)
1606{
1607 $tree = treeFromList ($netlist); // medium call
1608 sortTree ($tree, 'IPv4NetworkCmp');
fec0c8da 1609 // complement the tree before markup to make the spare networks have "symbol" set
c3315231
DO
1610 treeApplyFunc ($tree, 'iptree_fill');
1611 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
1612 // count addresses after the markup to skip computation for hidden tree nodes
1613 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
fec0c8da
DO
1614 return $tree;
1615}
1616
1617// Check all items of the tree recursively, until the requested target id is
1618// found. Mark all items leading to this item as "expanded", collapsing all
1619// the rest, which exceed the given threshold (if the threshold is given).
1620function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
1621{
1622 $self = __FUNCTION__;
1623 $ret = FALSE;
1624 foreach (array_keys ($tree) as $key)
1625 {
5388794d 1626 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
fec0c8da
DO
1627 $below = $self ($tree[$key]['kids'], $threshold, $target);
1628 if (!$tree[$key]['kidc']) // terminal node
1629 $tree[$key]['symbol'] = 'spacer';
1630 elseif ($tree[$key]['kidc'] < $threshold)
1631 $tree[$key]['symbol'] = 'node-expanded-static';
1632 elseif ($here or $below)
1633 $tree[$key]['symbol'] = 'node-expanded';
1634 else
1635 $tree[$key]['symbol'] = 'node-collapsed';
1636 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
1637 }
1638 return $ret;
1639}
1640
3b81cb98
DO
1641// Get a tree and target entity ID on it. Return the list of IDs, which make the path
1642// from the target entity to tree root. If such a path exists, it will consist of at
1643// least the target ID. Otherwise an empty list will be returned. The "list" is a randomly
1644// indexed array of values.
1645function traceEntity ($tree, $target_id)
1646{
1647 $self = __FUNCTION__;
1648 foreach ($tree as $node)
1649 {
1650 if ($node['id'] == $target_id) // here!
1651 return array ($target_id);
1652 $subtrace = $self ($node['kids'], $target_id); // below?
1653 if (count ($subtrace))
1654 {
1655 array_push ($subtrace, $node['id']);
1656 return $subtrace;
1657 }
1658 // next...
1659 }
1660 return array();
1661}
1662
e1ae3fb4
AD
1663// Convert entity name to human-readable value
1664function formatEntityName ($name) {
1665 switch ($name)
1666 {
1667 case 'ipv4net':
1668 return 'IPv4 Network';
1669 case 'ipv4rspool':
1670 return 'IPv4 RS Pool';
1671 case 'ipv4vs':
1672 return 'IPv4 Virtual Service';
1673 case 'object':
1674 return 'Object';
1675 case 'rack':
1676 return 'Rack';
1677 case 'user':
1678 return 'User';
1679 }
1680 return 'invalid';
1681}
1682
1683// Take a MySQL or other generic timestamp and make it prettier
1684function formatTimestamp ($timestamp) {
1685 return date('n/j/y g:iA', strtotime($timestamp));
1686}
1687
1688// Display hrefs for all of a file's parents
1689function serializeFileLinks ($links)
1690{
1691 global $root;
1692
1693 $comma = '';
1694 $ret = '';
1695 foreach ($links as $link_id => $li)
1696 {
1697 switch ($li['entity_type'])
1698 {
1699 case 'ipv4net':
1700 $params = "page=ipv4net&id=";
1701 break;
1702 case 'ipv4rspool':
1703 $params = "page=ipv4rspool&pool_id=";
1704 break;
1705 case 'ipv4vs':
1706 $params = "page=ipv4vs&vs_id=";
1707 break;
1708 case 'object':
1709 $params = "page=object&object_id=";
1710 break;
1711 case 'rack':
1712 $params = "page=rack&rack_id=";
1713 break;
1714 case 'user':
1715 $params = "page=user&user_id=";
1716 break;
1717 }
1718 $ret .= sprintf("%s<a href='%s?%s%s'>%s</a>", $comma, $root, $params, $li['entity_id'], $li['name']);
1719 $comma = ', ';
1720 }
1721
1722 return $ret;
1723}
1724
1725// Convert filesize to appropriate unit and make it human-readable
1726function formatFileSize ($bytes) {
1727 // bytes
1728 if($bytes < 1024) // bytes
1729 return "${bytes} bytes";
1730
1731 // kilobytes
1732 if ($bytes < 1024000)
1733 return sprintf ("%.1fk", round (($bytes / 1024), 1));
1734
1735 // megabytes
1736 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
1737}
1738
1739// Reverse of formatFileSize, it converts human-readable value to bytes
1740function convertToBytes ($value) {
1741 $value = trim($value);
1742 $last = strtolower($value[strlen($value)-1]);
1743 switch ($last)
1744 {
1745 case 'g':
1746 $value *= 1024;
1747 case 'm':
1748 $value *= 1024;
1749 case 'k':
1750 $value *= 1024;
1751 }
1752
1753 return $value;
1754}
1755
e673ee24 1756?>