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