r2113 + introduce $typeid_%u autotag
[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
381// This function performs search and then calculates score for each result.
382// Given previous search results in $objects argument, it adds new results
383// to the array and updates score for existing results, if it is greater than
384// existing score.
385function mergeSearchResults (&$objects, $terms, $fieldname)
386{
387 global $dbxlink;
388 $query =
389 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
390 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
391 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
392 $count = 0;
393 foreach (explode (' ', $terms) as $term)
394 {
395 if ($count) $query .= ' or ';
396 $query .= "${fieldname} like '%$term%'";
397 $count++;
398 }
fb45e432 399 $query .= " order by ${fieldname}";
065eeb52 400 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
401// FIXME: this dead call was executed 4 times per 1 object search!
402// $typeList = getObjectTypeList();
403 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
105a3bc8 404 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
405 {
406 foreach ($clist as $cname)
407 $object[$cname] = $row[$cname];
408 $object['score'] = 0;
409 $object['dname'] = displayedName ($object);
410 unset ($object['objtype_id']);
411 foreach (explode (' ', $terms) as $term)
412 if (strstr ($object['name'], $term))
413 $object['score'] += 1;
414 unset ($object['name']);
415 if (!isset ($objects[$row['id']]))
416 $objects[$row['id']] = $object;
417 elseif ($objects[$row['id']]['score'] < $object['score'])
418 $objects[$row['id']]['score'] = $object['score'];
419 }
420 return $objects;
421}
422
ea5fc465 423function getObjectSearchResults ($terms)
e673ee24
DO
424{
425 $objects = array();
426 mergeSearchResults ($objects, $terms, 'name');
427 mergeSearchResults ($objects, $terms, 'label');
428 mergeSearchResults ($objects, $terms, 'asset_no');
429 mergeSearchResults ($objects, $terms, 'barcode');
430 if (count ($objects) == 1)
431 usort ($objects, 'search_cmpObj');
432 return $objects;
433}
434
435// This function removes all colons and dots from a string.
436function l2addressForDatabase ($string)
437{
438 if (empty ($string))
439 return 'NULL';
440 $pieces = explode (':', $string);
441 // This workaround is for SunOS ifconfig.
442 foreach ($pieces as &$byte)
443 if (strlen ($byte) == 1)
444 $byte = '0' . $byte;
445 // And this workaround is for PHP.
446 unset ($byte);
447 $string = implode ('', $pieces);
448 $pieces = explode ('.', $string);
449 $string = implode ('', $pieces);
450 $string = strtoupper ($string);
451 return "'$string'";
452}
453
454function l2addressFromDatabase ($string)
455{
456 switch (strlen ($string))
457 {
458 case 12: // Ethernet
459 case 16: // FireWire
460 $ret = implode (':', str_split ($string, 2));
461 break;
462 default:
463 $ret = $string;
464 break;
465 }
466 return $ret;
467}
468
469// The following 2 functions return previous and next rack IDs for
470// a given rack ID. The order of racks is the same as in renderRackspace()
471// or renderRow().
472function getPrevIDforRack ($row_id = 0, $rack_id = 0)
473{
474 if ($row_id <= 0 or $rack_id <= 0)
475 {
61e269b5 476 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
477 return NULL;
478 }
479 $rackList = getRacksForRow ($row_id);
480 doubleLink ($rackList);
481 if (isset ($rackList[$rack_id]['prev_key']))
482 return $rackList[$rack_id]['prev_key'];
483 return NULL;
484}
485
486function getNextIDforRack ($row_id = 0, $rack_id = 0)
487{
488 if ($row_id <= 0 or $rack_id <= 0)
489 {
61e269b5 490 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
491 return NULL;
492 }
493 $rackList = getRacksForRow ($row_id);
494 doubleLink ($rackList);
495 if (isset ($rackList[$rack_id]['next_key']))
496 return $rackList[$rack_id]['next_key'];
497 return NULL;
498}
499
500// This function finds previous and next array keys for each array key and
501// modifies its argument accordingly.
502function doubleLink (&$array)
503{
504 $prev_key = NULL;
505 foreach (array_keys ($array) as $key)
506 {
507 if ($prev_key)
508 {
509 $array[$key]['prev_key'] = $prev_key;
510 $array[$prev_key]['next_key'] = $key;
511 }
512 $prev_key = $key;
513 }
514}
515
516// After applying usort() to a rack list we will lose original array keys.
517// This function restores the keys so they are equal to rack IDs.
518function restoreRackIDs ($racks)
519{
520 $ret = array();
521 foreach ($racks as $rack)
522 $ret[$rack['id']] = $rack;
523 return $ret;
524}
525
526function sortTokenize ($a, $b)
527{
528 $aold='';
529 while ($a != $aold)
530 {
531 $aold=$a;
532 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
533 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
534 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
535 }
536
537 $bold='';
538 while ($b != $bold)
539 {
540 $bold=$b;
541 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
542 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
543 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
544 }
545
546
547
548 $ar = explode(' ', $a);
549 $br = explode(' ', $b);
550 for ($i=0; $i<count($ar) && $i<count($br); $i++)
551 {
552 $ret = 0;
553 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
554 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
555 else
556 $ret = strcasecmp($ar[$i], $br[$i]);
557 if ($ret != 0)
558 return $ret;
559 }
560 if ($i<count($ar))
561 return 1;
562 if ($i<count($br))
563 return -1;
564 return 0;
565}
566
567function sortByName ($a, $b)
568{
569 return sortTokenize($a['name'], $b['name']);
570}
571
6a3a37b2
DO
572function sortRacks ($a, $b)
573{
574 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
575}
576
e673ee24
DO
577function eq ($a, $b)
578{
579 return $a==$b;
580}
581
582function neq ($a, $b)
583{
584 return $a!=$b;
585}
586
587function countRefsOfType ($refs, $type, $eq)
588{
589 $count=0;
590 foreach ($refs as $ref)
591 {
592 if ($eq($ref['type'], $type))
593 $count++;
594 }
595 return $count;
596}
597
598function sortEmptyPorts ($a, $b)
599{
600 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
601 if ($objname_cmp == 0)
602 {
603 return sortTokenize($a['Port_name'], $b['Port_name']);
604 }
605 return $objname_cmp;
606}
607
608function sortObjectAddressesAndNames ($a, $b)
609{
610 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
611 if ($objname_cmp == 0)
612 {
79f22c3d
DO
613 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
614 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
615 $objname_cmp = sortTokenize($name_a, $name_b);
e673ee24 616 if ($objname_cmp == 0)
e673ee24 617 sortTokenize($a['ip'], $b['ip']);
e673ee24
DO
618 return $objname_cmp;
619 }
620 return $objname_cmp;
621}
622
623
624
625function sortAddresses ($a, $b)
626{
627 $name_cmp = sortTokenize($a['name'], $b['name']);
628 if ($name_cmp == 0)
629 {
630 return sortTokenize($a['ip'], $b['ip']);
631 }
632 return $name_cmp;
633}
634
635// This function expands port compat list into a matrix.
636function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
637{
638 $matrix = array();
639 // Create type matrix and markup compatible types.
640 foreach (array_keys ($portTypeList) as $type1)
641 foreach (array_keys ($portTypeList) as $type2)
642 $matrix[$type1][$type2] = FALSE;
643 foreach ($portCompatList as $pair)
644 $matrix[$pair['type1']][$pair['type2']] = TRUE;
645 return $matrix;
646}
647
648function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
649{
bb0a44e9 650 if (NULL === getIPv4AddressNetworkId ($localip))
e673ee24 651 return "$localip: Non existant ip";
bb0a44e9 652 if (NULL === getIPv4AddressNetworkId ($localip))
e673ee24 653 return "$remoteip: Non existant ip";
e673ee24
DO
654 if ( ($localport <= 0) or ($localport >= 65536) )
655 return "$localport: invaild port";
e673ee24
DO
656 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
657 return "$remoteport: invaild port";
658
9bea3a8b
DO
659 $result = useInsertBlade
660 (
661 'PortForwarding',
662 array
663 (
664 'object_id' => $object_id,
665 'localip' => "INET_ATON('${localip}')",
666 'remoteip' => "INET_ATON('$remoteip')",
667 'localport' => $localport,
668 'remoteport' => $remoteport,
669 'proto' => "'${proto}'",
670 'description' => "'${description}'",
671 )
672 );
673 if ($result)
674 return '';
675 else
676 return __FUNCTION__ . ': Failed to insert the rule.';
e673ee24
DO
677}
678
679function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
680{
681 global $dbxlink;
682
683 $query =
684 "delete from PortForwarding where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
685 $result = $dbxlink->exec ($query);
686 return '';
687}
688
689function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
690{
691 global $dbxlink;
692
693 $query =
694 "update PortForwarding set description='$description' where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
695 $result = $dbxlink->exec ($query);
696 return '';
697}
698
eeb4a5d8 699function getNATv4ForObject ($object_id)
e673ee24 700{
e673ee24
DO
701 $ret = array();
702 $ret['out'] = array();
703 $ret['in'] = array();
704 $query =
705 "select ".
eeb4a5d8 706 "proto, ".
e673ee24
DO
707 "INET_NTOA(localip) as localip, ".
708 "localport, ".
709 "INET_NTOA(remoteip) as remoteip, ".
710 "remoteport, ".
f28fbe8b
DO
711 "ipa1.name as local_addr_name, " .
712 "ipa2.name as remote_addr_name, " .
e673ee24 713 "description ".
eeb4a5d8 714 "from PortForwarding ".
f28fbe8b
DO
715 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
716 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
eeb4a5d8 717 "where object_id='$object_id' ".
e673ee24 718 "order by localip, localport, proto, remoteip, remoteport";
065eeb52 719 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 720 $count=0;
eeb4a5d8 721 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 722 {
eeb4a5d8 723 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
f28fbe8b 724 $ret['out'][$count][$cname] = $row[$cname];
e673ee24
DO
725 $count++;
726 }
eeb4a5d8
DO
727 $result->closeCursor();
728 unset ($result);
e673ee24
DO
729
730 $query =
731 "select ".
eeb4a5d8 732 "proto, ".
e673ee24
DO
733 "INET_NTOA(localip) as localip, ".
734 "localport, ".
735 "INET_NTOA(remoteip) as remoteip, ".
736 "remoteport, ".
737 "PortForwarding.object_id as object_id, ".
738 "RackObject.name as object_name, ".
739 "description ".
eeb4a5d8
DO
740 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
741 "where IPBonds.object_id='$object_id' ".
e673ee24 742 "order by remoteip, remoteport, proto, localip, localport";
065eeb52 743 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 744 $count=0;
eeb4a5d8 745 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 746 {
eeb4a5d8 747 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
f28fbe8b 748 $ret['in'][$count][$cname] = $row[$cname];
e673ee24
DO
749 $count++;
750 }
eeb4a5d8 751 $result->closeCursor();
e673ee24
DO
752
753 return $ret;
754}
755
c31cd72c 756// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
757// if FQDN is set. The next choice is object's common name, if it looks like a
758// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 759// object is returned (which may appear 0 and more elements long).
f321b50a 760function findAllEndpoints ($object_id, $fallback = '')
c31cd72c
DO
761{
762 $values = getAttrValues ($object_id);
763 foreach ($values as $record)
f321b50a 764 if ($record['name'] == 'FQDN' && !empty ($record['value']))
c31cd72c
DO
765 return array ($record['value']);
766 $addresses = getObjectAddresses ($object_id);
767 $regular = array();
768 foreach ($addresses as $idx => $address)
769 if ($address['type'] == 'regular')
fa8112d1 770 $regular[] = $address['ip'];
f321b50a
DO
771 if (!count ($regular) && !empty ($fallback))
772 return array ($fallback);
c31cd72c
DO
773 return $regular;
774}
775
83ba6670
DO
776// Some records in the dictionary may be written as plain text or as Wiki
777// link in the following syntax:
778// 1. word
779// 2. [[word URL]] // FIXME: this isn't working
780// 3. [[word word word | URL]]
781// This function parses the line and returns text suitable for either A
782// (rendering <A HREF>) or O (for <OPTION>).
24cbe8af 783function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
83ba6670 784{
010231c2 785 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af
DO
786 {
787 if ($strip_optgroup)
f0b540a3 788 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
24cbe8af
DO
789 else
790 return $line;
791 }
010231c2
DO
792 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
793 $s = explode ('|', $line);
83ba6670 794 $o_value = trim ($s[0]);
24cbe8af 795 if ($strip_optgroup)
f0b540a3 796 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
83ba6670
DO
797 $a_value = trim ($s[1]);
798 if ($which == 'a')
010231c2 799 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
800 if ($which == 'o')
801 return $o_value;
802}
803
2de490b7
DO
804function buildVServiceName ($vsinfo = NULL)
805{
806 if ($vsinfo == NULL)
807 {
808 showError ('NULL argument', __FUNCTION__);
809 return NULL;
810 }
8d790216 811 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
2de490b7
DO
812}
813
05411ccd
DO
814function buildRSPoolName ($rspool = NULL)
815{
816 if ($rspool == NULL)
817 {
818 showError ('NULL argument', __FUNCTION__);
819 return NULL;
820 }
821 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
822}
823
177b1e9b
DO
824// rackspace usage for a single rack
825// (T + W + U) / (height * 3 - A)
11df133a 826function getRSUforRack ($data = NULL)
177b1e9b 827{
11df133a 828 if ($data == NULL)
177b1e9b
DO
829 {
830 showError ('Invalid argument', __FUNCTION__);
831 return NULL;
832 }
6ffba290 833 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
834 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
835 for ($locidx = 0; $locidx < 3; $locidx++)
836 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 837 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
838}
839
11df133a
DO
840// Same for row.
841function getRSUforRackRow ($rowData = NULL)
842{
bb26a59e 843 if ($rowData === NULL)
11df133a
DO
844 {
845 showError ('Invalid argument', __FUNCTION__);
846 return NULL;
847 }
bb26a59e
DO
848 if (!count ($rowData))
849 return 0;
11df133a 850 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 851 $total_height = 0;
dfa3c075
DO
852 foreach (array_keys ($rowData) as $rack_id)
853 {
854 $data = getRackData ($rack_id);
855 $total_height += $data['height'];
11df133a
DO
856 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
857 for ($locidx = 0; $locidx < 3; $locidx++)
858 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
859 }
860 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
861}
862
f1a0477d
DO
863function getObjectCount ($rackData)
864{
865 $objects = array();
866 for ($i = $rackData['height']; $i > 0; $i--)
867 for ($locidx = 0; $locidx < 3; $locidx++)
868 if
869 (
870 $rackData[$i][$locidx]['state'] == 'T' and
871 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
872 )
873 $objects[] = $rackData[$i][$locidx]['object_id'];
874 return count ($objects);
875}
876
9af110b4
DO
877// Make sure the string is always wrapped with LF characters
878function lf_wrap ($str)
879{
880 $ret = trim ($str, "\r\n");
881 if (!empty ($ret))
882 $ret .= "\n";
883 return $ret;
884}
885
e6e7d8b3
DO
886// Adopted from Mantis BTS code.
887function string_insert_hrefs ($s)
888{
889 if (getConfigVar ('DETECT_URLS') != 'yes')
890 return $s;
891 # Find any URL in a string and replace it by a clickable link
892 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
893 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
894 $s);
895 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
896 '<a href="mailto:\0">\0</a>',
897 $s);
898 return $s;
899}
900
901// Idem.
902function email_regex_simple ()
903{
904 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
905 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
906}
907
118e4c38
DO
908// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
909// for the requested object_type_id.
910function getAutoPorts ($type_id)
911{
912 $ret = array();
913 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
914 foreach ($typemap as $equation)
915 {
916 $tmp = explode ('=', $equation);
917 if (count ($tmp) != 2)
918 continue;
919 $objtype_id = $tmp[0];
920 if ($objtype_id != $type_id)
921 continue;
922 $portlist = $tmp[1];
923 foreach (explode ('+', $portlist) as $product)
924 {
925 $tmp = explode ('*', $product);
926 if (count ($tmp) != 3)
927 continue;
928 $nports = $tmp[0];
929 $port_type = $tmp[1];
930 $format = $tmp[2];
931 for ($i = 0; $i < $nports; $i++)
932 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
933 }
934 }
935 return $ret;
936}
937
9dfd4cc9
DO
938// Find if a particular tag id exists on the tree, then attach the
939// given child tag to it. If the parent tag doesn't exist, return FALSE.
940function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
941{
942 foreach ($tree as $tagid => $taginfo)
943 {
944 if ($tagid == $parent_id)
945 {
946 $tree[$tagid]['kids'][$child_id] = $child_info;
947 return TRUE;
948 }
949 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
950 return TRUE;
951 }
952 return FALSE;
953}
954
955// Build a tree from the tag list and return it.
956function getTagTree ()
957{
20c901a7
DO
958 global $taglist;
959 $mytaglist = $taglist;
960 $ret = array();
961 while (count ($mytaglist) > 0)
9dfd4cc9
DO
962 {
963 $picked = FALSE;
20c901a7 964 foreach ($mytaglist as $tagid => $taginfo)
9dfd4cc9
DO
965 {
966 $taginfo['kids'] = array();
967 if ($taginfo['parent_id'] == NULL)
968 {
20c901a7 969 $ret[$tagid] = $taginfo;
9dfd4cc9 970 $picked = TRUE;
20c901a7 971 unset ($mytaglist[$tagid]);
9dfd4cc9 972 }
20c901a7 973 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
9dfd4cc9
DO
974 {
975 $picked = TRUE;
20c901a7 976 unset ($mytaglist[$tagid]);
9dfd4cc9
DO
977 }
978 }
979 if (!$picked) // Only orphaned items on the list.
980 break;
981 }
20c901a7 982 return $ret;
9dfd4cc9
DO
983}
984
49fb1027
DO
985// Build a tree from the tag list and return everything _except_ the tree.
986function getOrphanedTags ()
987{
988 global $taglist;
989 $mytaglist = $taglist;
990 $dummy = array();
991 while (count ($mytaglist) > 0)
992 {
993 $picked = FALSE;
994 foreach ($mytaglist as $tagid => $taginfo)
995 {
996 $taginfo['kids'] = array();
997 if ($taginfo['parent_id'] == NULL)
998 {
999 $dummy[$tagid] = $taginfo;
1000 $picked = TRUE;
1001 unset ($mytaglist[$tagid]);
1002 }
1003 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
1004 {
1005 $picked = TRUE;
1006 unset ($mytaglist[$tagid]);
1007 }
1008 }
1009 if (!$picked) // Only orphaned items on the list.
1010 return $mytaglist;
1011 }
1012 return array();
1013}
1014
6e49bd1f 1015function serializeTags ($chain, $baseurl = '')
ba93bd98
DO
1016{
1017 $comma = '';
1018 $ret = '';
6e49bd1f 1019 foreach ($chain as $taginfo)
ba93bd98 1020 {
e2ac59cf
DO
1021 $ret .= $comma .
1022 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
1023 $taginfo['tag'] .
1024 ($baseurl == '' ? '' : '</a>');
ba93bd98
DO
1025 $comma = ', ';
1026 }
1027 return $ret;
1028}
1029
6e49bd1f
DO
1030// a helper for getTagChainExpansion()
1031function traceTagChain ($tree, $chain)
ba93bd98
DO
1032{
1033 // For each tag find its path from the root, then combine items
6e49bd1f 1034 // of all paths and add them to the chain, if they aren't there yet.
ba93bd98
DO
1035 $ret = array();
1036 foreach ($tree as $taginfo1)
1037 {
1038 $hit = FALSE;
6e49bd1f 1039 foreach ($chain as $taginfo2)
ba93bd98
DO
1040 if ($taginfo1['id'] == $taginfo2['id'])
1041 {
1042 $hit = TRUE;
1043 break;
1044 }
1045 if (count ($taginfo1['kids']) > 0)
1046 {
6e49bd1f 1047 $subsearch = traceTagChain ($taginfo1['kids'], $chain);
ba93bd98
DO
1048 if (count ($subsearch))
1049 {
1050 $hit = TRUE;
1051 $ret = array_merge ($ret, $subsearch);
1052 }
1053 }
1054 if ($hit)
1055 $ret[] = $taginfo1;
1056 }
1057 return $ret;
1058}
1059
1060// For each tag add all its parent tags onto the list. Don't expect anything
6e49bd1f
DO
1061// except user's tags on the chain.
1062function getTagChainExpansion ($chain)
ba93bd98 1063{
20c901a7 1064 global $tagtree;
6e49bd1f 1065 return traceTagChain ($tagtree, $chain);
ba93bd98
DO
1066}
1067
1068// Return the list of missing implicit tags.
1069function getImplicitTags ($oldtags)
1070{
1071 $ret = array();
6e49bd1f 1072 $newtags = getTagChainExpansion ($oldtags);
ba93bd98
DO
1073 foreach ($newtags as $newtag)
1074 {
1075 $already_exists = FALSE;
1076 foreach ($oldtags as $oldtag)
1077 if ($newtag['id'] == $oldtag['id'])
1078 {
1079 $already_exists = TRUE;
1080 break;
1081 }
1082 if ($already_exists)
1083 continue;
d6089951 1084 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
ba93bd98
DO
1085 }
1086 return $ret;
1087}
1088
6e49bd1f
DO
1089// Minimize the chain: exclude all implicit tags and return the result.
1090function getExplicitTagsOnly ($chain, $tree = NULL)
ab379543 1091{
20c901a7 1092 global $tagtree;
ab379543 1093 if ($tree === NULL)
20c901a7 1094 $tree = $tagtree;
ab379543
DO
1095 $ret = array();
1096 foreach ($tree as $taginfo)
1097 {
1098 if (isset ($taginfo['kids']))
1099 {
6e49bd1f 1100 $harvest = getExplicitTagsOnly ($chain, $taginfo['kids']);
ab379543
DO
1101 if (count ($harvest) > 0)
1102 {
1103 $ret = array_merge ($ret, $harvest);
1104 continue;
1105 }
1106 }
1107 // This tag isn't implicit, test is for being explicit.
6e49bd1f 1108 foreach ($chain as $testtag)
ab379543
DO
1109 if ($taginfo['id'] == $testtag['id'])
1110 {
1111 $ret[] = $testtag;
1112 break;
1113 }
1114 }
1115 return $ret;
1116}
1117
6e49bd1f 1118// Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
74ccacff
DO
1119// Unlike other functions, this one accepts and returns a list of integer tag IDs, not
1120// a list of tag structures.
1121function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1122{
20c901a7 1123 global $tagtree;
74ccacff 1124 if ($tree === NULL)
20c901a7 1125 $tree = $tagtree;
74ccacff
DO
1126 $getallkids = $getall;
1127 $ret = array();
1128 foreach ($tree as $taginfo)
1129 {
1130 foreach ($idlist as $test_id)
1131 if ($getall or $taginfo['id'] == $test_id)
1132 {
1133 $ret[] = $taginfo['id'];
1134 // Once matched node makes all sub-nodes match, but don't make
1135 // a mistake of matching every other node at the current level.
1136 $getallkids = TRUE;
1137 break;
1138 }
1139 if (isset ($taginfo['kids']))
1140 $ret = array_merge ($ret, complementByKids ($idlist, $taginfo['kids'], $getallkids));
1141 $getallkids = FALSE;
1142 }
1143 return $ret;
1144}
1145
cce6b057
DO
1146function getUserAutoTags ($username = NULL)
1147{
1148 global $remote_username, $accounts;
1149 if ($username == NULL)
1150 $username = $remote_username;
1151 $ret = array();
1152 $ret[] = array ('tag' => '$username_' . $username);
1153 if (isset ($accounts[$username]['user_id']))
1154 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
1155 return $ret;
1156}
1157
68225375 1158function loadRackObjectAutoTags ()
ba93bd98 1159{
2c6c7645 1160 assertUIntArg ('object_id', __FUNCTION__);
2fb24351
DO
1161 $object_id = $_REQUEST['object_id'];
1162 $oinfo = getObjectInfo ($object_id);
1163 $ret = array();
0e692350 1164 $ret[] = array ('tag' => '$id_' . $object_id);
fae80c2b 1165 $ret[] = array ('tag' => '$typeid_' . $oinfo['objtype_id']);
d817ba03 1166 $ret[] = array ('tag' => '$any_object');
c396cbf4
DO
1167 if (validTagName ($oinfo['name']))
1168 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
2fb24351
DO
1169 return $ret;
1170}
1171
68225375 1172// Common code for both prefix and address tag listers.
bb0a44e9 1173function getIPv4PrefixTags ($netid)
f9bc186f 1174{
bb0a44e9 1175 $netinfo = getIPv4NetworkInfo ($netid);
f9bc186f 1176 $ret = array();
bb0a44e9 1177 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $netinfo['ip']) . '-' . $netinfo['mask']);
da958e52
DO
1178 // FIXME: find and list tags for all parent networks?
1179 $ret[] = array ('tag' => '$any_ip4net');
d817ba03 1180 $ret[] = array ('tag' => '$any_net');
41bd8c87
DO
1181 return $ret;
1182}
1183
68225375 1184function loadIPv4PrefixAutoTags ()
41bd8c87 1185{
68225375
DO
1186 assertUIntArg ('id', __FUNCTION__);
1187 return array_merge
1188 (
da958e52 1189 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
bb0a44e9 1190 getIPv4PrefixTags ($_REQUEST['id'])
68225375 1191 );
d817ba03
DO
1192}
1193
68225375 1194function loadIPv4AddressAutoTags ()
d817ba03 1195{
2c6c7645 1196 assertIPv4Arg ('ip', __FUNCTION__);
68225375
DO
1197 return array_merge
1198 (
da958e52 1199 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
bb0a44e9 1200 getIPv4PrefixTags (getIPv4AddressNetworkId ($_REQUEST['ip']))
68225375
DO
1201 );
1202}
1203
1204function loadRackAutoTags ()
1205{
1206 assertUIntArg ('rack_id', __FUNCTION__);
d817ba03 1207 $ret = array();
da958e52 1208 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
68225375 1209 $ret[] = array ('tag' => '$any_rack');
d817ba03
DO
1210 return $ret;
1211}
1212
68225375 1213function loadIPv4VSAutoTags ()
d817ba03 1214{
49fb2686 1215 assertUIntArg ('vs_id', __FUNCTION__);
d817ba03 1216 $ret = array();
0e692350 1217 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
d817ba03
DO
1218 $ret[] = array ('tag' => '$any_ipv4vs');
1219 $ret[] = array ('tag' => '$any_vs');
1220 return $ret;
1221}
1222
68225375 1223function loadIPv4RSPoolAutoTags ()
d817ba03 1224{
2c6c7645 1225 assertUIntArg ('pool_id', __FUNCTION__);
d817ba03 1226 $ret = array();
0e692350
DO
1227 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1228 $ret[] = array ('tag' => '$any_ipv4rsp');
1229 $ret[] = array ('tag' => '$any_rsp');
f9bc186f
DO
1230 return $ret;
1231}
1232
53bae67b
DO
1233// If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1234// hold all appropriate (explicit and implicit) tags respectively.
1235// Otherwise some limited redirection is necessary (only page and tab
1236// names are preserved, ophandler name change isn't handled).
da958e52
DO
1237function fixContext ()
1238{
1239 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
53bae67b
DO
1240
1241 $pmap = array
1242 (
1243 'accounts' => 'userlist',
1244 'rspools' => 'ipv4rsplist',
1245 'rspool' => 'ipv4rsp',
1246 'vservices' => 'ipv4vslist',
1247 'vservice' => 'ipv4vs',
1248 );
1249 $tmap = array();
1250 $tmap['objects']['newmulti'] = 'addmore';
1251 $tmap['objects']['newobj'] = 'addmore';
1252 $tmap['object']['switchvlans'] = 'livevlans';
1253 $tmap['object']['slb'] = 'editrspvs';
72d8ced3
DO
1254 $tmap['object']['portfwrd'] = 'nat4';
1255 $tmap['object']['network'] = 'ipv4';
53bae67b
DO
1256 if (isset ($pmap[$pageno]))
1257 redirectUser ($pmap[$pageno], $tabno);
1258 if (isset ($tmap[$pageno][$tabno]))
1259 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1260
da958e52
DO
1261 if (isset ($page[$pageno]['autotagloader']))
1262 $auto_tags = $page[$pageno]['autotagloader'] ();
1263 if
1264 (
1265 isset ($page[$pageno]['tagloader']) and
1266 isset ($page[$pageno]['bypass']) and
1267 isset ($_REQUEST[$page[$pageno]['bypass']])
1268 )
1269 {
1270 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1271 $impl_tags = getImplicitTags ($expl_tags);
1272 }
1273}
1274
6e49bd1f
DO
1275// Build a tag chain from supplied tag id list and return it.
1276function buildTagChainFromIds ($tagidlist)
ab379543 1277{
20c901a7 1278 global $taglist;
ab379543
DO
1279 $ret = array();
1280 foreach ($tagidlist as $tag_id)
1281 if (isset ($taglist[$tag_id]))
1282 $ret[] = $taglist[$tag_id];
1283 return $ret;
1284}
1285
7cc02fc1
DO
1286// Process a given tag tree and return only meaningful branches. The resulting
1287// (sub)tree will have refcnt leaves on every last branch.
1288function getObjectiveTagTree ($tree, $realm)
1289{
1290 $ret = array();
1291 foreach ($tree as $taginfo)
1292 {
1293 $subsearch = array();
1294 $pick = FALSE;
1295 if (count ($taginfo['kids']))
1296 {
1297 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1298 $pick = count ($subsearch) > 0;
1299 }
5bdc04ec 1300 if (isset ($taginfo['refcnt'][$realm]))
7cc02fc1
DO
1301 $pick = TRUE;
1302 if (!$pick)
1303 continue;
1304 $ret[] = array
1305 (
1306 'id' => $taginfo['id'],
1307 'tag' => $taginfo['tag'],
1308 'parent_id' => $taginfo['parent_id'],
1309 'refcnt' => $taginfo['refcnt'],
1310 'kids' => $subsearch
1311 );
1312 }
1313 return $ret;
1314}
1315
a0d54e7e 1316function getTagFilter ()
7cc02fc1 1317{
a0d54e7e 1318 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
7cc02fc1
DO
1319}
1320
a0d54e7e 1321function getTagFilterStr ($tagfilter = array())
932cf41f 1322{
a0d54e7e 1323 $ret = '';
6e49bd1f 1324 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
a0d54e7e
DO
1325 $ret .= "&tagfilter[]=" . $taginfo['id'];
1326 return $ret;
932cf41f 1327}
a0d54e7e 1328
baf37d01 1329function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
da958e52 1330{
46f92ff7 1331 global $root, $page, $pageno, $tabno;
baf37d01
DO
1332 if ($nextpage === NULL)
1333 $nextpage = $pageno;
1334 if ($nexttab === NULL)
1335 $nexttab = $tabno;
1336 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1337 if (isset ($page[$nextpage]['bypass']))
1338 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
0f3c6639 1339 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
da958e52
DO
1340 return $url;
1341}
1342
ebb5441d 1343function buildRedirectURL ($status, $args = array(), $nextpage = NULL, $nexttab = NULL)
46f92ff7 1344{
baf37d01
DO
1345 global $msgcode, $pageno, $tabno, $op;
1346 if ($nextpage === NULL)
1347 $nextpage = $pageno;
1348 if ($nexttab === NULL)
1349 $nexttab = $tabno;
2987fc1f
DO
1350 return buildWideRedirectURL (oneLiner ($msgcode[$pageno][$tabno][$op][$status], $args), $nextpage, $nexttab);
1351}
1352
1353// Return a message log consisting of only one message.
1354function oneLiner ($code, $args = array())
1355{
1356 $ret = array ('v' => 2);
1357 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1358 return $ret;
46f92ff7
DO
1359}
1360
9f54e6e9 1361function validTagName ($s, $allow_autotag = FALSE)
2eeeca80 1362{
9f54e6e9
DO
1363 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1364 return TRUE;
1365 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1366 return TRUE;
1367 return FALSE;
2eeeca80
DO
1368}
1369
53bae67b
DO
1370function redirectUser ($p, $t)
1371{
1372 global $page, $root;
1373 $l = "{$root}?page=${p}&tab=${t}";
1374 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1375 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1376 header ("Location: " . $l);
1377 die;
1378}
1379
9f3e5caa
DO
1380function getRackCodeStats ()
1381{
1382 global $rackCode;
1383 $defc = $grantc = 0;
1384 foreach ($rackCode as $s)
1385 switch ($s['type'])
1386 {
1387 case 'SYNT_DEFINITION':
1388 $defc++;
1389 break;
1390 case 'SYNT_GRANT':
1391 $grantc++;
1392 break;
1393 default:
1394 break;
1395 }
1396 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1397 return $ret;
1398}
1399
d5157018
DO
1400function getRackImageWidth ()
1401{
1402 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1403}
1404
1405function getRackImageHeight ($units)
1406{
1407 return 3 + 3 + $units * 2;
1408}
1409
2987fc1f
DO
1410// Perform substitutions and return resulting string
1411// used solely by buildLVSConfig()
1412function apply_macros ($macros, $subject)
1413{
1414 $ret = $subject;
1415 foreach ($macros as $search => $replace)
1416 $ret = str_replace ($search, $replace, $ret);
1417 return $ret;
1418}
1419
1420function buildLVSConfig ($object_id = 0)
1421{
1422 if ($object_id <= 0)
1423 {
1424 showError ('Invalid argument', __FUNCTION__);
1425 return;
1426 }
1427 $oInfo = getObjectInfo ($object_id);
1428 $lbconfig = getSLBConfig ($object_id);
1429 if ($lbconfig === NULL)
1430 {
1431 showError ('getSLBConfig() failed', __FUNCTION__);
1432 return;
1433 }
1434 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1435 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1436 foreach ($lbconfig as $vs_id => $vsinfo)
1437 {
1438 $newconfig .= "########################################################\n" .
1439 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1440 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1441 "########################################################\n";
1442 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1443 $macros = array
1444 (
1445 '%VIP%' => $vsinfo['vip'],
1446 '%VPORT%' => $vsinfo['vport'],
1447 '%PROTO%' => $vsinfo['proto'],
1448 '%VNAME%' => $vsinfo['vs_name'],
1449 '%RSPOOLNAME%' => $vsinfo['pool_name']
1450 );
1451 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1452 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1453 $newconfig .= apply_macros
1454 (
1455 $macros,
1456 lf_wrap ($vsinfo['vs_vsconfig']) .
1457 lf_wrap ($vsinfo['lb_vsconfig']) .
1458 lf_wrap ($vsinfo['pool_vsconfig'])
1459 );
1460 foreach ($vsinfo['rslist'] as $rs)
1461 {
1462 $macros['%RSIP%'] = $rs['rsip'];
1463 $macros['%RSPORT%'] = $rs['rsport'];
1464 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1465 $newconfig .= apply_macros
1466 (
1467 $macros,
1468 lf_wrap ($vsinfo['vs_rsconfig']) .
1469 lf_wrap ($vsinfo['lb_rsconfig']) .
1470 lf_wrap ($vsinfo['pool_rsconfig']) .
1471 lf_wrap ($rs['rs_rsconfig'])
1472 );
1473 $newconfig .= "\t}\n";
1474 }
1475 $newconfig .= "}\n\n\n";
1476 }
1477 return $newconfig;
1478}
1479
2d318652
DO
1480// Indicate occupation state of each IP address: none, ordinary or problematic.
1481function markupIPv4AddrList (&$addrlist)
1482{
1483 foreach (array_keys ($addrlist) as $ip_bin)
1484 {
1485 $singlealloc = 0;
1486 $nvirtual = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'shared', 'eq');
1487 $nloopback = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'virtual', 'eq');
1488 $nconnected = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'regular', 'eq');
1489 $nrouter = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'router', 'eq');
1490 $nsl = ($nvirtual + $nloopback > 0) ? 1 : 0;
1491 $nrsv = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0;
1492 $nrealms = $nrsv + $nsl + $nconnected + $nrouter;
1493
1494 if ($nrealms == 1)
1495 $addrlist[$ip_bin]['class'] = 'trbusy';
1496 elseif ($nrealms > 1)
1497 $addrlist[$ip_bin]['class'] = 'trerror';
1498 else
1499 $addrlist[$ip_bin]['class'] = '';
1500 }
1501}
1502
04d619d0
DO
1503// Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1504function findRouters ($addrlist)
1505{
1506 $ret = array();
1507 foreach ($addrlist as $addr)
1508 foreach ($addr['allocs'] as $alloc)
1509 if ($alloc['type'] == 'router')
1510 $ret[] = array
1511 (
1512 'id' => $alloc['object_id'],
1513 'iface' => $alloc['name'],
1514 'dname' => $alloc['object_name'],
1515 'addr' => $addr['ip']
1516 );
1517 return $ret;
1518}
1519
e673ee24 1520?>