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