881e4ee2e46ca468d690b6d2c97d6d97313d9f33
[racktables] / inc / functions.php
1 <?php
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.
30 function displayedName ($objectData)
31 {
32 if ($objectData['name'] != '')
33 return $objectData['name'];
34 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
35 return "ANONYMOUS " . $objectData['objtype_name'];
36 else
37 return "[${objectData['objtype_name']}]";
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.
43 function 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;
60 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
61 break 2;
62 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
63 break 2;
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);
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";
81 return $height;
82 }
83
84 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
85 // attributes.
86 function 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.
97 // Explicitly show even single-cell spanned atoms, because rectHeight()
98 // is expeciting this data for correct calculation.
99 if ($colspan != 0)
100 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
101 else
102 {
103 $colspan = $templateWidth[$template_idx];
104 if ($colspan >= 1)
105 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
106 if ($maxheight >= 1)
107 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
108 }
109 }
110 }
111 }
112 return;
113 }
114
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.
118 function markAllSpans (&$rackData = NULL)
119 {
120 if ($rackData == NULL)
121 {
122 showError ('Invalid rackData', __FUNCTION__);
123 return;
124 }
125 for ($i = $rackData['height']; $i > 0; $i--)
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).
131 function markBestSpan (&$rackData, $i)
132 {
133 global $template, $templateWidth;
134 for ($j = 0; $j < 6; $j++)
135 {
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)
146 {
147 $best_template_index = $j;
148 $bestheight = $height[$j];
149 break;
150 }
151 // distribute span marks
152 markSpan ($rackData, $i, $bestheight, $best_template_index);
153 return TRUE;
154 }
155
156 // We can mount 'F' atoms and unmount our own 'T' atoms.
157 function 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.
175 function 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'.
191 function 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.
207 function 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).
223 function 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.
238 function 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.
256 function 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
272 // netmask conversion from length to number
273 function binMaskFromDec ($maskL)
274 {
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];
311 }
312
313 // complementary value
314 function binInvMaskFromDec ($maskL)
315 {
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];
352 }
353
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.
358 function 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
376 function 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.
385 function 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 }
399 $query .= " order by ${fieldname}";
400 $result = useSelectBlade ($query, __FUNCTION__);
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');
404 while ($row = $result->fetch (PDO::FETCH_ASSOC))
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
423 function getObjectSearchResults ($terms)
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.
436 function 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
454 function 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().
472 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
473 {
474 if ($row_id <= 0 or $rack_id <= 0)
475 {
476 showError ('Invalid arguments passed', __FUNCTION__);
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
486 function getNextIDforRack ($row_id = 0, $rack_id = 0)
487 {
488 if ($row_id <= 0 or $rack_id <= 0)
489 {
490 showError ('Invalid arguments passed', __FUNCTION__);
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.
502 function 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.
518 function restoreRackIDs ($racks)
519 {
520 $ret = array();
521 foreach ($racks as $rack)
522 $ret[$rack['id']] = $rack;
523 return $ret;
524 }
525
526 function 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
567 function sortByName ($a, $b)
568 {
569 return sortTokenize($a['name'], $b['name']);
570 }
571
572 function sortRacks ($a, $b)
573 {
574 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
575 }
576
577 function eq ($a, $b)
578 {
579 return $a==$b;
580 }
581
582 function neq ($a, $b)
583 {
584 return $a!=$b;
585 }
586
587 function 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
598 function 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
608 function sortObjectAddressesAndNames ($a, $b)
609 {
610 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
611 if ($objname_cmp == 0)
612 {
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);
616 if ($objname_cmp == 0)
617 sortTokenize($a['ip'], $b['ip']);
618 return $objname_cmp;
619 }
620 return $objname_cmp;
621 }
622
623
624
625 function 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.
636 function 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
648 function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
649 {
650 if (NULL === getIPv4AddressNetworkId ($localip))
651 return "$localip: Non existant ip";
652 if (NULL === getIPv4AddressNetworkId ($localip))
653 return "$remoteip: Non existant ip";
654 if ( ($localport <= 0) or ($localport >= 65536) )
655 return "$localport: invaild port";
656 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
657 return "$remoteport: invaild port";
658
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.';
677 }
678
679 function 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
689 function 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
699 function getNATv4ForObject ($object_id)
700 {
701 $ret = array();
702 $ret['out'] = array();
703 $ret['in'] = array();
704 $query =
705 "select ".
706 "proto, ".
707 "INET_NTOA(localip) as localip, ".
708 "localport, ".
709 "INET_NTOA(remoteip) as remoteip, ".
710 "remoteport, ".
711 "ipa1.name as local_addr_name, " .
712 "ipa2.name as remote_addr_name, " .
713 "description ".
714 "from PortForwarding ".
715 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
716 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
717 "where object_id='$object_id' ".
718 "order by localip, localport, proto, remoteip, remoteport";
719 $result = useSelectBlade ($query, __FUNCTION__);
720 $count=0;
721 while ($row = $result->fetch (PDO::FETCH_ASSOC))
722 {
723 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
724 $ret['out'][$count][$cname] = $row[$cname];
725 $count++;
726 }
727 $result->closeCursor();
728 unset ($result);
729
730 $query =
731 "select ".
732 "proto, ".
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 ".
740 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
741 "where IPBonds.object_id='$object_id' ".
742 "order by remoteip, remoteport, proto, localip, localport";
743 $result = useSelectBlade ($query, __FUNCTION__);
744 $count=0;
745 while ($row = $result->fetch (PDO::FETCH_ASSOC))
746 {
747 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
748 $ret['in'][$count][$cname] = $row[$cname];
749 $count++;
750 }
751 $result->closeCursor();
752
753 return $ret;
754 }
755
756 // This function returns an array of single element of object's FQDN attribute,
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
759 // object is returned (which may appear 0 and more elements long).
760 function findAllEndpoints ($object_id, $fallback = '')
761 {
762 $values = getAttrValues ($object_id);
763 foreach ($values as $record)
764 if ($record['name'] == 'FQDN' && !empty ($record['value']))
765 return array ($record['value']);
766 $regular = array();
767 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
768 if ($alloc['type'] == 'regular')
769 $regular[] = $dottedquad;
770 if (!count ($regular) && !empty ($fallback))
771 return array ($fallback);
772 return $regular;
773 }
774
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>).
782 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
783 {
784 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
785 {
786 if ($strip_optgroup)
787 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
788 else
789 return $line;
790 }
791 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
792 $s = explode ('|', $line);
793 $o_value = trim ($s[0]);
794 if ($strip_optgroup)
795 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
796 $a_value = trim ($s[1]);
797 if ($which == 'a')
798 return "<a href='${a_value}'>${o_value}</a>";
799 if ($which == 'o')
800 return $o_value;
801 }
802
803 function buildVServiceName ($vsinfo = NULL)
804 {
805 if ($vsinfo == NULL)
806 {
807 showError ('NULL argument', __FUNCTION__);
808 return NULL;
809 }
810 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
811 }
812
813 function 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
823 // rackspace usage for a single rack
824 // (T + W + U) / (height * 3 - A)
825 function getRSUforRack ($data = NULL)
826 {
827 if ($data == NULL)
828 {
829 showError ('Invalid argument', __FUNCTION__);
830 return NULL;
831 }
832 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
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']]++;
836 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
837 }
838
839 // Same for row.
840 function getRSUforRackRow ($rowData = NULL)
841 {
842 if ($rowData === NULL)
843 {
844 showError ('Invalid argument', __FUNCTION__);
845 return NULL;
846 }
847 if (!count ($rowData))
848 return 0;
849 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
850 $total_height = 0;
851 foreach (array_keys ($rowData) as $rack_id)
852 {
853 $data = getRackData ($rack_id);
854 $total_height += $data['height'];
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']]++;
858 }
859 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
860 }
861
862 // Return a list of object IDs, which can be found in the given rackspace block.
863 function stuffInRackspace ($rackData)
864 {
865 $objects = array();
866 for ($i = $rackData['height']; $i > 0; $i--)
867 for ($locidx = 0; $locidx < 3; $locidx++)
868 if
869 (
870 $rackData[$i][$locidx]['state'] == 'T' and
871 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
872 )
873 $objects[] = $rackData[$i][$locidx]['object_id'];
874 return $objects;
875 }
876
877 // Make sure the string is always wrapped with LF characters
878 function lf_wrap ($str)
879 {
880 $ret = trim ($str, "\r\n");
881 if (!empty ($ret))
882 $ret .= "\n";
883 return $ret;
884 }
885
886 // Adopted from Mantis BTS code.
887 function string_insert_hrefs ($s)
888 {
889 if (getConfigVar ('DETECT_URLS') != 'yes')
890 return $s;
891 # Find any URL in a string and replace it by a clickable link
892 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
893 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
894 $s);
895 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
896 '<a href="mailto:\0">\0</a>',
897 $s);
898 return $s;
899 }
900
901 // Idem.
902 function email_regex_simple ()
903 {
904 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
905 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
906 }
907
908 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
909 // for the requested object_type_id.
910 function getAutoPorts ($type_id)
911 {
912 $ret = array();
913 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
914 foreach ($typemap as $equation)
915 {
916 $tmp = explode ('=', $equation);
917 if (count ($tmp) != 2)
918 continue;
919 $objtype_id = $tmp[0];
920 if ($objtype_id != $type_id)
921 continue;
922 $portlist = $tmp[1];
923 foreach (explode ('+', $portlist) as $product)
924 {
925 $tmp = explode ('*', $product);
926 if (count ($tmp) != 3)
927 continue;
928 $nports = $tmp[0];
929 $port_type = $tmp[1];
930 $format = $tmp[2];
931 for ($i = 0; $i < $nports; $i++)
932 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
933 }
934 }
935 return $ret;
936 }
937
938 // Find if a particular tag id exists on the tree, then attach the
939 // given child tag to it. If the parent tag doesn't exist, return FALSE.
940 function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
941 {
942 foreach ($tree as $tagid => $taginfo)
943 {
944 if ($tagid == $parent_id)
945 {
946 $tree[$tagid]['kids'][$child_id] = $child_info;
947 return TRUE;
948 }
949 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
950 return TRUE;
951 }
952 return FALSE;
953 }
954
955 // Build a tree from the tag list and return it.
956 function getTagTree ()
957 {
958 global $taglist;
959 $mytaglist = $taglist;
960 $ret = array();
961 while (count ($mytaglist) > 0)
962 {
963 $picked = FALSE;
964 foreach ($mytaglist as $tagid => $taginfo)
965 {
966 $taginfo['kids'] = array();
967 if ($taginfo['parent_id'] == NULL)
968 {
969 $ret[$tagid] = $taginfo;
970 $picked = TRUE;
971 unset ($mytaglist[$tagid]);
972 }
973 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
974 {
975 $picked = TRUE;
976 unset ($mytaglist[$tagid]);
977 }
978 }
979 if (!$picked) // Only orphaned items on the list.
980 break;
981 }
982 return $ret;
983 }
984
985 // Build a tree from the tag list and return everything _except_ the tree.
986 function getOrphanedTags ()
987 {
988 global $taglist;
989 $mytaglist = $taglist;
990 $dummy = array();
991 while (count ($mytaglist) > 0)
992 {
993 $picked = FALSE;
994 foreach ($mytaglist as $tagid => $taginfo)
995 {
996 $taginfo['kids'] = array();
997 if ($taginfo['parent_id'] == NULL)
998 {
999 $dummy[$tagid] = $taginfo;
1000 $picked = TRUE;
1001 unset ($mytaglist[$tagid]);
1002 }
1003 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
1004 {
1005 $picked = TRUE;
1006 unset ($mytaglist[$tagid]);
1007 }
1008 }
1009 if (!$picked) // Only orphaned items on the list.
1010 return $mytaglist;
1011 }
1012 return array();
1013 }
1014
1015 function serializeTags ($chain, $baseurl = '')
1016 {
1017 $comma = '';
1018 $ret = '';
1019 foreach ($chain as $taginfo)
1020 {
1021 $ret .= $comma .
1022 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
1023 $taginfo['tag'] .
1024 ($baseurl == '' ? '' : '</a>');
1025 $comma = ', ';
1026 }
1027 return $ret;
1028 }
1029
1030 // a helper for getTagChainExpansion()
1031 function traceTagChain ($tree, $chain)
1032 {
1033 // For each tag find its path from the root, then combine items
1034 // of all paths and add them to the chain, if they aren't there yet.
1035 $ret = array();
1036 foreach ($tree as $taginfo1)
1037 {
1038 $hit = FALSE;
1039 foreach ($chain as $taginfo2)
1040 if ($taginfo1['id'] == $taginfo2['id'])
1041 {
1042 $hit = TRUE;
1043 break;
1044 }
1045 if (count ($taginfo1['kids']) > 0)
1046 {
1047 $subsearch = traceTagChain ($taginfo1['kids'], $chain);
1048 if (count ($subsearch))
1049 {
1050 $hit = TRUE;
1051 $ret = array_merge ($ret, $subsearch);
1052 }
1053 }
1054 if ($hit)
1055 $ret[] = $taginfo1;
1056 }
1057 return $ret;
1058 }
1059
1060 // For each tag add all its parent tags onto the list. Don't expect anything
1061 // except user's tags on the chain.
1062 function getTagChainExpansion ($chain)
1063 {
1064 global $tagtree;
1065 return traceTagChain ($tagtree, $chain);
1066 }
1067
1068 // Return the list of missing implicit tags.
1069 function getImplicitTags ($oldtags)
1070 {
1071 $ret = array();
1072 $newtags = getTagChainExpansion ($oldtags);
1073 foreach ($newtags as $newtag)
1074 {
1075 $already_exists = FALSE;
1076 foreach ($oldtags as $oldtag)
1077 if ($newtag['id'] == $oldtag['id'])
1078 {
1079 $already_exists = TRUE;
1080 break;
1081 }
1082 if ($already_exists)
1083 continue;
1084 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
1085 }
1086 return $ret;
1087 }
1088
1089 // Minimize the chain: exclude all implicit tags and return the result.
1090 function getExplicitTagsOnly ($chain, $tree = NULL)
1091 {
1092 global $tagtree;
1093 if ($tree === NULL)
1094 $tree = $tagtree;
1095 $ret = array();
1096 foreach ($tree as $taginfo)
1097 {
1098 if (isset ($taginfo['kids']))
1099 {
1100 $harvest = getExplicitTagsOnly ($chain, $taginfo['kids']);
1101 if (count ($harvest) > 0)
1102 {
1103 $ret = array_merge ($ret, $harvest);
1104 continue;
1105 }
1106 }
1107 // This tag isn't implicit, test is for being explicit.
1108 foreach ($chain as $testtag)
1109 if ($taginfo['id'] == $testtag['id'])
1110 {
1111 $ret[] = $testtag;
1112 break;
1113 }
1114 }
1115 return $ret;
1116 }
1117
1118 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
1119 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
1120 // a list of tag structures. Same structure (tag ID list) is returned after processing.
1121 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1122 {
1123 global $tagtree;
1124 if ($tree === NULL)
1125 $tree = $tagtree;
1126 $getallkids = $getall;
1127 $ret = array();
1128 foreach ($tree as $taginfo)
1129 {
1130 foreach ($idlist as $test_id)
1131 if ($getall or $taginfo['id'] == $test_id)
1132 {
1133 $ret[] = $taginfo['id'];
1134 // Once matched node makes all sub-nodes match, but don't make
1135 // a mistake of matching every other node at the current level.
1136 $getallkids = TRUE;
1137 break;
1138 }
1139 if (isset ($taginfo['kids']))
1140 $ret = array_merge ($ret, complementByKids ($idlist, $taginfo['kids'], $getallkids));
1141 $getallkids = FALSE;
1142 }
1143 return $ret;
1144 }
1145
1146 function getUserAutoTags ($username = NULL)
1147 {
1148 global $remote_username, $accounts;
1149 if ($username == NULL)
1150 $username = $remote_username;
1151 $ret = array();
1152 $ret[] = array ('tag' => '$username_' . $username);
1153 if (isset ($accounts[$username]['user_id']))
1154 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
1155 return $ret;
1156 }
1157
1158 function loadRackObjectAutoTags ()
1159 {
1160 assertUIntArg ('object_id', __FUNCTION__);
1161 $object_id = $_REQUEST['object_id'];
1162 $oinfo = getObjectInfo ($object_id);
1163 $ret = array();
1164 $ret[] = array ('tag' => '$id_' . $object_id);
1165 $ret[] = array ('tag' => '$typeid_' . $oinfo['objtype_id']);
1166 $ret[] = array ('tag' => '$any_object');
1167 if (validTagName ($oinfo['name']))
1168 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
1169 return $ret;
1170 }
1171
1172 // Common code for both prefix and address tag listers.
1173 function getIPv4PrefixTags ($netid)
1174 {
1175 $netinfo = getIPv4NetworkInfo ($netid);
1176 $ret = array();
1177 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $netinfo['ip']) . '-' . $netinfo['mask']);
1178 // FIXME: find and list tags for all parent networks?
1179 $ret[] = array ('tag' => '$any_ip4net');
1180 $ret[] = array ('tag' => '$any_net');
1181 return $ret;
1182 }
1183
1184 function loadIPv4PrefixAutoTags ()
1185 {
1186 assertUIntArg ('id', __FUNCTION__);
1187 return array_merge
1188 (
1189 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
1190 getIPv4PrefixTags ($_REQUEST['id'])
1191 );
1192 }
1193
1194 function loadIPv4AddressAutoTags ()
1195 {
1196 assertIPv4Arg ('ip', __FUNCTION__);
1197 return array_merge
1198 (
1199 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
1200 getIPv4PrefixTags (getIPv4AddressNetworkId ($_REQUEST['ip']))
1201 );
1202 }
1203
1204 function loadRackAutoTags ()
1205 {
1206 assertUIntArg ('rack_id', __FUNCTION__);
1207 $ret = array();
1208 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
1209 $ret[] = array ('tag' => '$any_rack');
1210 return $ret;
1211 }
1212
1213 function loadIPv4VSAutoTags ()
1214 {
1215 assertUIntArg ('vs_id', __FUNCTION__);
1216 $ret = array();
1217 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
1218 $ret[] = array ('tag' => '$any_ipv4vs');
1219 $ret[] = array ('tag' => '$any_vs');
1220 return $ret;
1221 }
1222
1223 function loadIPv4RSPoolAutoTags ()
1224 {
1225 assertUIntArg ('pool_id', __FUNCTION__);
1226 $ret = array();
1227 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1228 $ret[] = array ('tag' => '$any_ipv4rsp');
1229 $ret[] = array ('tag' => '$any_rsp');
1230 return $ret;
1231 }
1232
1233 // Check, if the given tag is present on the chain (will only work
1234 // for regular tags with tag ID set.
1235 function tagOnChain ($taginfo, $tagchain)
1236 {
1237 if (!isset ($taginfo['id']))
1238 return FALSE;
1239 foreach ($tagchain as $test)
1240 if ($test['id'] == $taginfo['id'])
1241 return TRUE;
1242 return FALSE;
1243 }
1244
1245 // Idem, but use ID list instead of chain.
1246 function tagOnIdList ($taginfo, $tagidlist)
1247 {
1248 if (!isset ($taginfo['id']))
1249 return FALSE;
1250 foreach ($tagidlist as $tagid)
1251 if ($taginfo['id'] == $tagid)
1252 return TRUE;
1253 return FALSE;
1254 }
1255
1256 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1257 // Assume, that neither of the lists contains duplicates.
1258 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1259 function tagChainCmp ($chain1, $chain2)
1260 {
1261 if (count ($chain1) != count ($chain2))
1262 return TRUE;
1263 foreach ($chain1 as $taginfo1)
1264 if (!tagOnChain ($taginfo1, $chain2))
1265 return TRUE;
1266 return FALSE;
1267 }
1268
1269 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1270 // hold all appropriate (explicit and implicit) tags respectively.
1271 // Otherwise some limited redirection is necessary (only page and tab
1272 // names are preserved, ophandler name change isn't handled).
1273 function fixContext ()
1274 {
1275 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
1276
1277 $pmap = array
1278 (
1279 'accounts' => 'userlist',
1280 'rspools' => 'ipv4rsplist',
1281 'rspool' => 'ipv4rsp',
1282 'vservices' => 'ipv4vslist',
1283 'vservice' => 'ipv4vs',
1284 );
1285 $tmap = array();
1286 $tmap['objects']['newmulti'] = 'addmore';
1287 $tmap['objects']['newobj'] = 'addmore';
1288 $tmap['object']['switchvlans'] = 'livevlans';
1289 $tmap['object']['slb'] = 'editrspvs';
1290 $tmap['object']['portfwrd'] = 'nat4';
1291 $tmap['object']['network'] = 'ipv4';
1292 if (isset ($pmap[$pageno]))
1293 redirectUser ($pmap[$pageno], $tabno);
1294 if (isset ($tmap[$pageno][$tabno]))
1295 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1296
1297 if (isset ($page[$pageno]['autotagloader']))
1298 $auto_tags = $page[$pageno]['autotagloader'] ();
1299 if
1300 (
1301 isset ($page[$pageno]['tagloader']) and
1302 isset ($page[$pageno]['bypass']) and
1303 isset ($_REQUEST[$page[$pageno]['bypass']])
1304 )
1305 {
1306 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1307 $impl_tags = getImplicitTags ($expl_tags);
1308 }
1309 }
1310
1311 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1312 // records indexed by tag IDs (tag chain).
1313 function buildTagChainFromIds ($tagidlist)
1314 {
1315 global $taglist;
1316 $ret = array();
1317 foreach (array_unique ($tagidlist) as $tag_id)
1318 if (isset ($taglist[$tag_id]))
1319 $ret[] = $taglist[$tag_id];
1320 return $ret;
1321 }
1322
1323 // Process a given tag tree and return only meaningful branches. The resulting
1324 // (sub)tree will have refcnt leaves on every last branch.
1325 function getObjectiveTagTree ($tree, $realm)
1326 {
1327 $ret = array();
1328 foreach ($tree as $taginfo)
1329 {
1330 $subsearch = array();
1331 $pick = FALSE;
1332 if (count ($taginfo['kids']))
1333 {
1334 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1335 $pick = count ($subsearch) > 0;
1336 }
1337 if (isset ($taginfo['refcnt'][$realm]))
1338 $pick = TRUE;
1339 if (!$pick)
1340 continue;
1341 $ret[] = array
1342 (
1343 'id' => $taginfo['id'],
1344 'tag' => $taginfo['tag'],
1345 'parent_id' => $taginfo['parent_id'],
1346 'refcnt' => $taginfo['refcnt'],
1347 'kids' => $subsearch
1348 );
1349 }
1350 return $ret;
1351 }
1352
1353 function getTagFilter ()
1354 {
1355 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
1356 }
1357
1358 function getTagFilterStr ($tagfilter = array())
1359 {
1360 $ret = '';
1361 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
1362 $ret .= "&tagfilter[]=" . $taginfo['id'];
1363 return $ret;
1364 }
1365
1366 function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
1367 {
1368 global $root, $page, $pageno, $tabno;
1369 if ($nextpage === NULL)
1370 $nextpage = $pageno;
1371 if ($nexttab === NULL)
1372 $nexttab = $tabno;
1373 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1374 if (isset ($page[$nextpage]['bypass']))
1375 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
1376 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
1377 return $url;
1378 }
1379
1380 function buildRedirectURL ($status, $args = array(), $nextpage = NULL, $nexttab = NULL)
1381 {
1382 global $msgcode, $pageno, $tabno, $op;
1383 if ($nextpage === NULL)
1384 $nextpage = $pageno;
1385 if ($nexttab === NULL)
1386 $nexttab = $tabno;
1387 return buildWideRedirectURL (oneLiner ($msgcode[$pageno][$tabno][$op][$status], $args), $nextpage, $nexttab);
1388 }
1389
1390 // Return a message log consisting of only one message.
1391 function oneLiner ($code, $args = array())
1392 {
1393 $ret = array ('v' => 2);
1394 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1395 return $ret;
1396 }
1397
1398 // Return mesage code by status code.
1399 function getMessageCode ($status)
1400 {
1401 global $pageno, $tabno, $op, $msgcode;
1402 return $msgcode[$pageno][$tabno][$op][$status];
1403 }
1404
1405 function validTagName ($s, $allow_autotag = FALSE)
1406 {
1407 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1408 return TRUE;
1409 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1410 return TRUE;
1411 return FALSE;
1412 }
1413
1414 function redirectUser ($p, $t)
1415 {
1416 global $page, $root;
1417 $l = "{$root}?page=${p}&tab=${t}";
1418 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1419 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1420 header ("Location: " . $l);
1421 die;
1422 }
1423
1424 function getRackCodeStats ()
1425 {
1426 global $rackCode;
1427 $defc = $grantc = 0;
1428 foreach ($rackCode as $s)
1429 switch ($s['type'])
1430 {
1431 case 'SYNT_DEFINITION':
1432 $defc++;
1433 break;
1434 case 'SYNT_GRANT':
1435 $grantc++;
1436 break;
1437 default:
1438 break;
1439 }
1440 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1441 return $ret;
1442 }
1443
1444 function getRackImageWidth ()
1445 {
1446 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1447 }
1448
1449 function getRackImageHeight ($units)
1450 {
1451 return 3 + 3 + $units * 2;
1452 }
1453
1454 // Perform substitutions and return resulting string
1455 // used solely by buildLVSConfig()
1456 function apply_macros ($macros, $subject)
1457 {
1458 $ret = $subject;
1459 foreach ($macros as $search => $replace)
1460 $ret = str_replace ($search, $replace, $ret);
1461 return $ret;
1462 }
1463
1464 function buildLVSConfig ($object_id = 0)
1465 {
1466 if ($object_id <= 0)
1467 {
1468 showError ('Invalid argument', __FUNCTION__);
1469 return;
1470 }
1471 $oInfo = getObjectInfo ($object_id);
1472 $lbconfig = getSLBConfig ($object_id);
1473 if ($lbconfig === NULL)
1474 {
1475 showError ('getSLBConfig() failed', __FUNCTION__);
1476 return;
1477 }
1478 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1479 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1480 foreach ($lbconfig as $vs_id => $vsinfo)
1481 {
1482 $newconfig .= "########################################################\n" .
1483 "# VS (id == ${vs_id}): " . (empty ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1484 "# RS pool (id == ${vsinfo['pool_id']}): " . (empty ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1485 "########################################################\n";
1486 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1487 $macros = array
1488 (
1489 '%VIP%' => $vsinfo['vip'],
1490 '%VPORT%' => $vsinfo['vport'],
1491 '%PROTO%' => $vsinfo['proto'],
1492 '%VNAME%' => $vsinfo['vs_name'],
1493 '%RSPOOLNAME%' => $vsinfo['pool_name']
1494 );
1495 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1496 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1497 $newconfig .= apply_macros
1498 (
1499 $macros,
1500 lf_wrap ($vsinfo['vs_vsconfig']) .
1501 lf_wrap ($vsinfo['lb_vsconfig']) .
1502 lf_wrap ($vsinfo['pool_vsconfig'])
1503 );
1504 foreach ($vsinfo['rslist'] as $rs)
1505 {
1506 $macros['%RSIP%'] = $rs['rsip'];
1507 $macros['%RSPORT%'] = $rs['rsport'];
1508 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1509 $newconfig .= apply_macros
1510 (
1511 $macros,
1512 lf_wrap ($vsinfo['vs_rsconfig']) .
1513 lf_wrap ($vsinfo['lb_rsconfig']) .
1514 lf_wrap ($vsinfo['pool_rsconfig']) .
1515 lf_wrap ($rs['rs_rsconfig'])
1516 );
1517 $newconfig .= "\t}\n";
1518 }
1519 $newconfig .= "}\n\n\n";
1520 }
1521 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1522 return str_replace ("\r", '', $newconfig);
1523 }
1524
1525 // Indicate occupation state of each IP address: none, ordinary or problematic.
1526 function markupIPv4AddrList (&$addrlist)
1527 {
1528 foreach (array_keys ($addrlist) as $ip_bin)
1529 {
1530 $singlealloc = 0;
1531 $nvirtual = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'shared', 'eq');
1532 $nloopback = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'virtual', 'eq');
1533 $nconnected = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'regular', 'eq');
1534 $nrouter = countRefsOfType ($addrlist[$ip_bin]['allocs'], 'router', 'eq');
1535 $nsl = ($nvirtual + $nloopback > 0) ? 1 : 0;
1536 $nrsv = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0;
1537 $nrealms = $nrsv + $nsl + $nconnected + $nrouter;
1538
1539 if ($nrealms == 1)
1540 $addrlist[$ip_bin]['class'] = 'trbusy';
1541 elseif ($nrealms > 1)
1542 $addrlist[$ip_bin]['class'] = 'trerror';
1543 else
1544 $addrlist[$ip_bin]['class'] = '';
1545 }
1546 }
1547
1548 // Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1549 function findRouters ($addrlist)
1550 {
1551 $ret = array();
1552 foreach ($addrlist as $addr)
1553 foreach ($addr['allocs'] as $alloc)
1554 if ($alloc['type'] == 'router')
1555 $ret[] = array
1556 (
1557 'id' => $alloc['object_id'],
1558 'iface' => $alloc['name'],
1559 'dname' => $alloc['object_name'],
1560 'addr' => $addr['ip']
1561 );
1562 return $ret;
1563 }
1564
1565 ?>