r2136 - really fix produceTagsForLastRecord()
[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 765 return array ($record['value']);
c31cd72c 766 $regular = array();
85970da2
DO
767 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
768 if ($alloc['type'] == 'regular')
769 $regular[] = $dottedquad;
f321b50a
DO
770 if (!count ($regular) && !empty ($fallback))
771 return array ($fallback);
c31cd72c
DO
772 return $regular;
773}
774
83ba6670
DO
775// Some records in the dictionary may be written as plain text or as Wiki
776// link in the following syntax:
777// 1. word
778// 2. [[word URL]] // FIXME: this isn't working
779// 3. [[word word word | URL]]
780// This function parses the line and returns text suitable for either A
781// (rendering <A HREF>) or O (for <OPTION>).
24cbe8af 782function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
83ba6670 783{
010231c2 784 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af
DO
785 {
786 if ($strip_optgroup)
f0b540a3 787 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
24cbe8af
DO
788 else
789 return $line;
790 }
010231c2
DO
791 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
792 $s = explode ('|', $line);
83ba6670 793 $o_value = trim ($s[0]);
24cbe8af 794 if ($strip_optgroup)
f0b540a3 795 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
83ba6670
DO
796 $a_value = trim ($s[1]);
797 if ($which == 'a')
010231c2 798 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
799 if ($which == 'o')
800 return $o_value;
801}
802
2de490b7
DO
803function buildVServiceName ($vsinfo = NULL)
804{
805 if ($vsinfo == NULL)
806 {
807 showError ('NULL argument', __FUNCTION__);
808 return NULL;
809 }
8d790216 810 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
2de490b7
DO
811}
812
05411ccd
DO
813function buildRSPoolName ($rspool = NULL)
814{
815 if ($rspool == NULL)
816 {
817 showError ('NULL argument', __FUNCTION__);
818 return NULL;
819 }
820 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
821}
822
177b1e9b
DO
823// rackspace usage for a single rack
824// (T + W + U) / (height * 3 - A)
11df133a 825function getRSUforRack ($data = NULL)
177b1e9b 826{
11df133a 827 if ($data == NULL)
177b1e9b
DO
828 {
829 showError ('Invalid argument', __FUNCTION__);
830 return NULL;
831 }
6ffba290 832 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
833 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
834 for ($locidx = 0; $locidx < 3; $locidx++)
835 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 836 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
837}
838
11df133a
DO
839// Same for row.
840function getRSUforRackRow ($rowData = NULL)
841{
bb26a59e 842 if ($rowData === NULL)
11df133a
DO
843 {
844 showError ('Invalid argument', __FUNCTION__);
845 return NULL;
846 }
bb26a59e
DO
847 if (!count ($rowData))
848 return 0;
11df133a 849 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 850 $total_height = 0;
dfa3c075
DO
851 foreach (array_keys ($rowData) as $rack_id)
852 {
853 $data = getRackData ($rack_id);
854 $total_height += $data['height'];
11df133a
DO
855 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
856 for ($locidx = 0; $locidx < 3; $locidx++)
857 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
858 }
859 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
860}
861
f1a0477d
DO
862function getObjectCount ($rackData)
863{
864 $objects = array();
865 for ($i = $rackData['height']; $i > 0; $i--)
866 for ($locidx = 0; $locidx < 3; $locidx++)
867 if
868 (
869 $rackData[$i][$locidx]['state'] == 'T' and
870 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
871 )
872 $objects[] = $rackData[$i][$locidx]['object_id'];
873 return count ($objects);
874}
875
9af110b4
DO
876// Make sure the string is always wrapped with LF characters
877function lf_wrap ($str)
878{
879 $ret = trim ($str, "\r\n");
880 if (!empty ($ret))
881 $ret .= "\n";
882 return $ret;
883}
884
e6e7d8b3
DO
885// Adopted from Mantis BTS code.
886function string_insert_hrefs ($s)
887{
888 if (getConfigVar ('DETECT_URLS') != 'yes')
889 return $s;
890 # Find any URL in a string and replace it by a clickable link
891 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
892 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
893 $s);
894 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
895 '<a href="mailto:\0">\0</a>',
896 $s);
897 return $s;
898}
899
900// Idem.
901function email_regex_simple ()
902{
903 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
904 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
905}
906
118e4c38
DO
907// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
908// for the requested object_type_id.
909function getAutoPorts ($type_id)
910{
911 $ret = array();
912 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
913 foreach ($typemap as $equation)
914 {
915 $tmp = explode ('=', $equation);
916 if (count ($tmp) != 2)
917 continue;
918 $objtype_id = $tmp[0];
919 if ($objtype_id != $type_id)
920 continue;
921 $portlist = $tmp[1];
922 foreach (explode ('+', $portlist) as $product)
923 {
924 $tmp = explode ('*', $product);
925 if (count ($tmp) != 3)
926 continue;
927 $nports = $tmp[0];
928 $port_type = $tmp[1];
929 $format = $tmp[2];
930 for ($i = 0; $i < $nports; $i++)
931 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
932 }
933 }
934 return $ret;
935}
936
9dfd4cc9
DO
937// Find if a particular tag id exists on the tree, then attach the
938// given child tag to it. If the parent tag doesn't exist, return FALSE.
939function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
940{
941 foreach ($tree as $tagid => $taginfo)
942 {
943 if ($tagid == $parent_id)
944 {
945 $tree[$tagid]['kids'][$child_id] = $child_info;
946 return TRUE;
947 }
948 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
949 return TRUE;
950 }
951 return FALSE;
952}
953
954// Build a tree from the tag list and return it.
955function getTagTree ()
956{
20c901a7
DO
957 global $taglist;
958 $mytaglist = $taglist;
959 $ret = array();
960 while (count ($mytaglist) > 0)
9dfd4cc9
DO
961 {
962 $picked = FALSE;
20c901a7 963 foreach ($mytaglist as $tagid => $taginfo)
9dfd4cc9
DO
964 {
965 $taginfo['kids'] = array();
966 if ($taginfo['parent_id'] == NULL)
967 {
20c901a7 968 $ret[$tagid] = $taginfo;
9dfd4cc9 969 $picked = TRUE;
20c901a7 970 unset ($mytaglist[$tagid]);
9dfd4cc9 971 }
20c901a7 972 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
9dfd4cc9
DO
973 {
974 $picked = TRUE;
20c901a7 975 unset ($mytaglist[$tagid]);
9dfd4cc9
DO
976 }
977 }
978 if (!$picked) // Only orphaned items on the list.
979 break;
980 }
20c901a7 981 return $ret;
9dfd4cc9
DO
982}
983
49fb1027
DO
984// Build a tree from the tag list and return everything _except_ the tree.
985function getOrphanedTags ()
986{
987 global $taglist;
988 $mytaglist = $taglist;
989 $dummy = array();
990 while (count ($mytaglist) > 0)
991 {
992 $picked = FALSE;
993 foreach ($mytaglist as $tagid => $taginfo)
994 {
995 $taginfo['kids'] = array();
996 if ($taginfo['parent_id'] == NULL)
997 {
998 $dummy[$tagid] = $taginfo;
999 $picked = TRUE;
1000 unset ($mytaglist[$tagid]);
1001 }
1002 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
1003 {
1004 $picked = TRUE;
1005 unset ($mytaglist[$tagid]);
1006 }
1007 }
1008 if (!$picked) // Only orphaned items on the list.
1009 return $mytaglist;
1010 }
1011 return array();
1012}
1013
6e49bd1f 1014function serializeTags ($chain, $baseurl = '')
ba93bd98
DO
1015{
1016 $comma = '';
1017 $ret = '';
6e49bd1f 1018 foreach ($chain as $taginfo)
ba93bd98 1019 {
e2ac59cf
DO
1020 $ret .= $comma .
1021 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
1022 $taginfo['tag'] .
1023 ($baseurl == '' ? '' : '</a>');
ba93bd98
DO
1024 $comma = ', ';
1025 }
1026 return $ret;
1027}
1028
6e49bd1f
DO
1029// a helper for getTagChainExpansion()
1030function traceTagChain ($tree, $chain)
ba93bd98
DO
1031{
1032 // For each tag find its path from the root, then combine items
6e49bd1f 1033 // of all paths and add them to the chain, if they aren't there yet.
ba93bd98
DO
1034 $ret = array();
1035 foreach ($tree as $taginfo1)
1036 {
1037 $hit = FALSE;
6e49bd1f 1038 foreach ($chain as $taginfo2)
ba93bd98
DO
1039 if ($taginfo1['id'] == $taginfo2['id'])
1040 {
1041 $hit = TRUE;
1042 break;
1043 }
1044 if (count ($taginfo1['kids']) > 0)
1045 {
6e49bd1f 1046 $subsearch = traceTagChain ($taginfo1['kids'], $chain);
ba93bd98
DO
1047 if (count ($subsearch))
1048 {
1049 $hit = TRUE;
1050 $ret = array_merge ($ret, $subsearch);
1051 }
1052 }
1053 if ($hit)
1054 $ret[] = $taginfo1;
1055 }
1056 return $ret;
1057}
1058
1059// For each tag add all its parent tags onto the list. Don't expect anything
6e49bd1f
DO
1060// except user's tags on the chain.
1061function getTagChainExpansion ($chain)
ba93bd98 1062{
20c901a7 1063 global $tagtree;
6e49bd1f 1064 return traceTagChain ($tagtree, $chain);
ba93bd98
DO
1065}
1066
1067// Return the list of missing implicit tags.
1068function getImplicitTags ($oldtags)
1069{
1070 $ret = array();
6e49bd1f 1071 $newtags = getTagChainExpansion ($oldtags);
ba93bd98
DO
1072 foreach ($newtags as $newtag)
1073 {
1074 $already_exists = FALSE;
1075 foreach ($oldtags as $oldtag)
1076 if ($newtag['id'] == $oldtag['id'])
1077 {
1078 $already_exists = TRUE;
1079 break;
1080 }
1081 if ($already_exists)
1082 continue;
d6089951 1083 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
ba93bd98
DO
1084 }
1085 return $ret;
1086}
1087
6e49bd1f
DO
1088// Minimize the chain: exclude all implicit tags and return the result.
1089function getExplicitTagsOnly ($chain, $tree = NULL)
ab379543 1090{
20c901a7 1091 global $tagtree;
ab379543 1092 if ($tree === NULL)
20c901a7 1093 $tree = $tagtree;
ab379543
DO
1094 $ret = array();
1095 foreach ($tree as $taginfo)
1096 {
1097 if (isset ($taginfo['kids']))
1098 {
6e49bd1f 1099 $harvest = getExplicitTagsOnly ($chain, $taginfo['kids']);
ab379543
DO
1100 if (count ($harvest) > 0)
1101 {
1102 $ret = array_merge ($ret, $harvest);
1103 continue;
1104 }
1105 }
1106 // This tag isn't implicit, test is for being explicit.
6e49bd1f 1107 foreach ($chain as $testtag)
ab379543
DO
1108 if ($taginfo['id'] == $testtag['id'])
1109 {
1110 $ret[] = $testtag;
1111 break;
1112 }
1113 }
1114 return $ret;
1115}
1116
6e49bd1f 1117// Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
74ccacff
DO
1118// Unlike other functions, this one accepts and returns a list of integer tag IDs, not
1119// a list of tag structures.
1120function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1121{
20c901a7 1122 global $tagtree;
74ccacff 1123 if ($tree === NULL)
20c901a7 1124 $tree = $tagtree;
74ccacff
DO
1125 $getallkids = $getall;
1126 $ret = array();
1127 foreach ($tree as $taginfo)
1128 {
1129 foreach ($idlist as $test_id)
1130 if ($getall or $taginfo['id'] == $test_id)
1131 {
1132 $ret[] = $taginfo['id'];
1133 // Once matched node makes all sub-nodes match, but don't make
1134 // a mistake of matching every other node at the current level.
1135 $getallkids = TRUE;
1136 break;
1137 }
1138 if (isset ($taginfo['kids']))
1139 $ret = array_merge ($ret, complementByKids ($idlist, $taginfo['kids'], $getallkids));
1140 $getallkids = FALSE;
1141 }
1142 return $ret;
1143}
1144
351c0966
DO
1145// Take a list of user-supplied tag IDs to build a list of valid taginfo
1146// records indexed by tag IDs (tag chain).
cdb7e75d 1147function tagChainFromIdList ($tagidlist)
351c0966
DO
1148{
1149 global $taglist;
1150 $ret = array();
1151 foreach (array_unique ($tagidlist) as $tagid)
1152 if (isset ($taglist[$tagid]))
1153 $ret[$tagid] = $taglist[$tagid];
1154 return $ret;
1155}
1156
cce6b057
DO
1157function getUserAutoTags ($username = NULL)
1158{
1159 global $remote_username, $accounts;
1160 if ($username == NULL)
1161 $username = $remote_username;
1162 $ret = array();
1163 $ret[] = array ('tag' => '$username_' . $username);
1164 if (isset ($accounts[$username]['user_id']))
1165 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
1166 return $ret;
1167}
1168
68225375 1169function loadRackObjectAutoTags ()
ba93bd98 1170{
2c6c7645 1171 assertUIntArg ('object_id', __FUNCTION__);
2fb24351
DO
1172 $object_id = $_REQUEST['object_id'];
1173 $oinfo = getObjectInfo ($object_id);
1174 $ret = array();
0e692350 1175 $ret[] = array ('tag' => '$id_' . $object_id);
fae80c2b 1176 $ret[] = array ('tag' => '$typeid_' . $oinfo['objtype_id']);
d817ba03 1177 $ret[] = array ('tag' => '$any_object');
c396cbf4
DO
1178 if (validTagName ($oinfo['name']))
1179 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
2fb24351
DO
1180 return $ret;
1181}
1182
68225375 1183// Common code for both prefix and address tag listers.
bb0a44e9 1184function getIPv4PrefixTags ($netid)
f9bc186f 1185{
bb0a44e9 1186 $netinfo = getIPv4NetworkInfo ($netid);
f9bc186f 1187 $ret = array();
bb0a44e9 1188 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $netinfo['ip']) . '-' . $netinfo['mask']);
da958e52
DO
1189 // FIXME: find and list tags for all parent networks?
1190 $ret[] = array ('tag' => '$any_ip4net');
d817ba03 1191 $ret[] = array ('tag' => '$any_net');
41bd8c87
DO
1192 return $ret;
1193}
1194
68225375 1195function loadIPv4PrefixAutoTags ()
41bd8c87 1196{
68225375
DO
1197 assertUIntArg ('id', __FUNCTION__);
1198 return array_merge
1199 (
da958e52 1200 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
bb0a44e9 1201 getIPv4PrefixTags ($_REQUEST['id'])
68225375 1202 );
d817ba03
DO
1203}
1204
68225375 1205function loadIPv4AddressAutoTags ()
d817ba03 1206{
2c6c7645 1207 assertIPv4Arg ('ip', __FUNCTION__);
68225375
DO
1208 return array_merge
1209 (
da958e52 1210 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
bb0a44e9 1211 getIPv4PrefixTags (getIPv4AddressNetworkId ($_REQUEST['ip']))
68225375
DO
1212 );
1213}
1214
1215function loadRackAutoTags ()
1216{
1217 assertUIntArg ('rack_id', __FUNCTION__);
d817ba03 1218 $ret = array();
da958e52 1219 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
68225375 1220 $ret[] = array ('tag' => '$any_rack');
d817ba03
DO
1221 return $ret;
1222}
1223
68225375 1224function loadIPv4VSAutoTags ()
d817ba03 1225{
49fb2686 1226 assertUIntArg ('vs_id', __FUNCTION__);
d817ba03 1227 $ret = array();
0e692350 1228 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
d817ba03
DO
1229 $ret[] = array ('tag' => '$any_ipv4vs');
1230 $ret[] = array ('tag' => '$any_vs');
1231 return $ret;
1232}
1233
68225375 1234function loadIPv4RSPoolAutoTags ()
d817ba03 1235{
2c6c7645 1236 assertUIntArg ('pool_id', __FUNCTION__);
d817ba03 1237 $ret = array();
0e692350
DO
1238 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1239 $ret[] = array ('tag' => '$any_ipv4rsp');
1240 $ret[] = array ('tag' => '$any_rsp');
f9bc186f
DO
1241 return $ret;
1242}
1243
53bae67b
DO
1244// If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1245// hold all appropriate (explicit and implicit) tags respectively.
1246// Otherwise some limited redirection is necessary (only page and tab
1247// names are preserved, ophandler name change isn't handled).
da958e52
DO
1248function fixContext ()
1249{
1250 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
53bae67b
DO
1251
1252 $pmap = array
1253 (
1254 'accounts' => 'userlist',
1255 'rspools' => 'ipv4rsplist',
1256 'rspool' => 'ipv4rsp',
1257 'vservices' => 'ipv4vslist',
1258 'vservice' => 'ipv4vs',
1259 );
1260 $tmap = array();
1261 $tmap['objects']['newmulti'] = 'addmore';
1262 $tmap['objects']['newobj'] = 'addmore';
1263 $tmap['object']['switchvlans'] = 'livevlans';
1264 $tmap['object']['slb'] = 'editrspvs';
72d8ced3
DO
1265 $tmap['object']['portfwrd'] = 'nat4';
1266 $tmap['object']['network'] = 'ipv4';
53bae67b
DO
1267 if (isset ($pmap[$pageno]))
1268 redirectUser ($pmap[$pageno], $tabno);
1269 if (isset ($tmap[$pageno][$tabno]))
1270 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1271
da958e52
DO
1272 if (isset ($page[$pageno]['autotagloader']))
1273 $auto_tags = $page[$pageno]['autotagloader'] ();
1274 if
1275 (
1276 isset ($page[$pageno]['tagloader']) and
1277 isset ($page[$pageno]['bypass']) and
1278 isset ($_REQUEST[$page[$pageno]['bypass']])
1279 )
1280 {
1281 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1282 $impl_tags = getImplicitTags ($expl_tags);
1283 }
1284}
1285
6e49bd1f
DO
1286// Build a tag chain from supplied tag id list and return it.
1287function buildTagChainFromIds ($tagidlist)
ab379543 1288{
20c901a7 1289 global $taglist;
ab379543
DO
1290 $ret = array();
1291 foreach ($tagidlist as $tag_id)
1292 if (isset ($taglist[$tag_id]))
1293 $ret[] = $taglist[$tag_id];
1294 return $ret;
1295}
1296
7cc02fc1
DO
1297// Process a given tag tree and return only meaningful branches. The resulting
1298// (sub)tree will have refcnt leaves on every last branch.
1299function getObjectiveTagTree ($tree, $realm)
1300{
1301 $ret = array();
1302 foreach ($tree as $taginfo)
1303 {
1304 $subsearch = array();
1305 $pick = FALSE;
1306 if (count ($taginfo['kids']))
1307 {
1308 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1309 $pick = count ($subsearch) > 0;
1310 }
5bdc04ec 1311 if (isset ($taginfo['refcnt'][$realm]))
7cc02fc1
DO
1312 $pick = TRUE;
1313 if (!$pick)
1314 continue;
1315 $ret[] = array
1316 (
1317 'id' => $taginfo['id'],
1318 'tag' => $taginfo['tag'],
1319 'parent_id' => $taginfo['parent_id'],
1320 'refcnt' => $taginfo['refcnt'],
1321 'kids' => $subsearch
1322 );
1323 }
1324 return $ret;
1325}
1326
a0d54e7e 1327function getTagFilter ()
7cc02fc1 1328{
a0d54e7e 1329 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
7cc02fc1
DO
1330}
1331
a0d54e7e 1332function getTagFilterStr ($tagfilter = array())
932cf41f 1333{
a0d54e7e 1334 $ret = '';
6e49bd1f 1335 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
a0d54e7e
DO
1336 $ret .= "&tagfilter[]=" . $taginfo['id'];
1337 return $ret;
932cf41f 1338}
a0d54e7e 1339
baf37d01 1340function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
da958e52 1341{
46f92ff7 1342 global $root, $page, $pageno, $tabno;
baf37d01
DO
1343 if ($nextpage === NULL)
1344 $nextpage = $pageno;
1345 if ($nexttab === NULL)
1346 $nexttab = $tabno;
1347 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1348 if (isset ($page[$nextpage]['bypass']))
1349 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
0f3c6639 1350 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
da958e52
DO
1351 return $url;
1352}
1353
ebb5441d 1354function buildRedirectURL ($status, $args = array(), $nextpage = NULL, $nexttab = NULL)
46f92ff7 1355{
baf37d01
DO
1356 global $msgcode, $pageno, $tabno, $op;
1357 if ($nextpage === NULL)
1358 $nextpage = $pageno;
1359 if ($nexttab === NULL)
1360 $nexttab = $tabno;
2987fc1f
DO
1361 return buildWideRedirectURL (oneLiner ($msgcode[$pageno][$tabno][$op][$status], $args), $nextpage, $nexttab);
1362}
1363
1364// Return a message log consisting of only one message.
1365function oneLiner ($code, $args = array())
1366{
1367 $ret = array ('v' => 2);
1368 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1369 return $ret;
46f92ff7
DO
1370}
1371
f19c75d6
DO
1372// Return mesage code by status code.
1373function getMessageCode ($status)
1374{
1375 global $pageno, $tabno, $op, $msgcode;
1376 return $msgcode[$pageno][$tabno][$op][$status];
1377}
1378
9f54e6e9 1379function validTagName ($s, $allow_autotag = FALSE)
2eeeca80 1380{
9f54e6e9
DO
1381 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1382 return TRUE;
1383 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1384 return TRUE;
1385 return FALSE;
2eeeca80
DO
1386}
1387
53bae67b
DO
1388function redirectUser ($p, $t)
1389{
1390 global $page, $root;
1391 $l = "{$root}?page=${p}&tab=${t}";
1392 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1393 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1394 header ("Location: " . $l);
1395 die;
1396}
1397
9f3e5caa
DO
1398function getRackCodeStats ()
1399{
1400 global $rackCode;
1401 $defc = $grantc = 0;
1402 foreach ($rackCode as $s)
1403 switch ($s['type'])
1404 {
1405 case 'SYNT_DEFINITION':
1406 $defc++;
1407 break;
1408 case 'SYNT_GRANT':
1409 $grantc++;
1410 break;
1411 default:
1412 break;
1413 }
1414 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1415 return $ret;
1416}
1417
d5157018
DO
1418function getRackImageWidth ()
1419{
1420 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1421}
1422
1423function getRackImageHeight ($units)
1424{
1425 return 3 + 3 + $units * 2;
1426}
1427
2987fc1f
DO
1428// Perform substitutions and return resulting string
1429// used solely by buildLVSConfig()
1430function apply_macros ($macros, $subject)
1431{
1432 $ret = $subject;
1433 foreach ($macros as $search => $replace)
1434 $ret = str_replace ($search, $replace, $ret);
1435 return $ret;
1436}
1437
1438function buildLVSConfig ($object_id = 0)
1439{
1440 if ($object_id <= 0)
1441 {
1442 showError ('Invalid argument', __FUNCTION__);
1443 return;
1444 }
1445 $oInfo = getObjectInfo ($object_id);
1446 $lbconfig = getSLBConfig ($object_id);
1447 if ($lbconfig === NULL)
1448 {
1449 showError ('getSLBConfig() failed', __FUNCTION__);
1450 return;
1451 }
1452 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1453 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1454 foreach ($lbconfig as $vs_id => $vsinfo)
1455 {
1456 $newconfig .= "########################################################\n" .
1457 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1458 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1459 "########################################################\n";
1460 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1461 $macros = array
1462 (
1463 '%VIP%' => $vsinfo['vip'],
1464 '%VPORT%' => $vsinfo['vport'],
1465 '%PROTO%' => $vsinfo['proto'],
1466 '%VNAME%' => $vsinfo['vs_name'],
1467 '%RSPOOLNAME%' => $vsinfo['pool_name']
1468 );
1469 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1470 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1471 $newconfig .= apply_macros
1472 (
1473 $macros,
1474 lf_wrap ($vsinfo['vs_vsconfig']) .
1475 lf_wrap ($vsinfo['lb_vsconfig']) .
1476 lf_wrap ($vsinfo['pool_vsconfig'])
1477 );
1478 foreach ($vsinfo['rslist'] as $rs)
1479 {
1480 $macros['%RSIP%'] = $rs['rsip'];
1481 $macros['%RSPORT%'] = $rs['rsport'];
1482 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1483 $newconfig .= apply_macros
1484 (
1485 $macros,
1486 lf_wrap ($vsinfo['vs_rsconfig']) .
1487 lf_wrap ($vsinfo['lb_rsconfig']) .
1488 lf_wrap ($vsinfo['pool_rsconfig']) .
1489 lf_wrap ($rs['rs_rsconfig'])
1490 );
1491 $newconfig .= "\t}\n";
1492 }
1493 $newconfig .= "}\n\n\n";
1494 }
1495 return $newconfig;
1496}
1497
2d318652
DO
1498// Indicate occupation state of each IP address: none, ordinary or problematic.
1499function markupIPv4AddrList (&$addrlist)
1500{
1501 foreach (array_keys ($addrlist) as $ip_bin)
1502 {
1503 $singlealloc = 0;
1504 $nvirtual = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'shared', 'eq');
1505 $nloopback = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'virtual', 'eq');
1506 $nconnected = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'regular', 'eq');
1507 $nrouter = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'router', 'eq');
1508 $nsl = ($nvirtual + $nloopback > 0) ? 1 : 0;
1509 $nrsv = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0;
1510 $nrealms = $nrsv + $nsl + $nconnected + $nrouter;
1511
1512 if ($nrealms == 1)
1513 $addrlist[$ip_bin]['class'] = 'trbusy';
1514 elseif ($nrealms > 1)
1515 $addrlist[$ip_bin]['class'] = 'trerror';
1516 else
1517 $addrlist[$ip_bin]['class'] = '';
1518 }
1519}
1520
04d619d0
DO
1521// Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1522function findRouters ($addrlist)
1523{
1524 $ret = array();
1525 foreach ($addrlist as $addr)
1526 foreach ($addr['allocs'] as $alloc)
1527 if ($alloc['type'] == 'router')
1528 $ret[] = array
1529 (
1530 'id' => $alloc['object_id'],
1531 'iface' => $alloc['name'],
1532 'dname' => $alloc['object_name'],
1533 'addr' => $addr['ip']
1534 );
1535 return $ret;
1536}
1537
e673ee24 1538?>