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