4763da389e90becf1b74ee87a68669b3c85e3552
[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 // Rack thumbnail image width summands: "front", "interior" and "rear" elements w/o surrounding border.
40 $rtwidth = array
41 (
42 0 => 9,
43 1 => 21,
44 2 => 9
45 );
46
47 $netmaskbylen = array
48 (
49 32 => '255.255.255.255',
50 31 => '255.255.255.254',
51 30 => '255.255.255.252',
52 29 => '255.255.255.248',
53 28 => '255.255.255.240',
54 27 => '255.255.255.224',
55 26 => '255.255.255.192',
56 25 => '255.255.255.128',
57 24 => '255.255.255.0',
58 23 => '255.255.254.0',
59 22 => '255.255.252.0',
60 21 => '255.255.248.0',
61 20 => '255.255.240.0',
62 19 => '255.255.224.0',
63 18 => '255.255.192.0',
64 17 => '255.255.128.0',
65 16 => '255.255.0.0',
66 15 => '255.254.0.0',
67 14 => '255.252.0.0',
68 13 => '255.248.0.0',
69 12 => '255.240.0.0',
70 11 => '255.224.0.0',
71 10 => '255.192.0.0',
72 9 => '255.128.0.0',
73 8 => '255.0.0.0',
74 7 => '254.0.0.0',
75 6 => '252.0.0.0',
76 5 => '248.0.0.0',
77 4 => '240.0.0.0',
78 3 => '224.0.0.0',
79 2 => '192.0.0.0',
80 1 => '128.0.0.0'
81 );
82
83 $wildcardbylen = array
84 (
85 32 => '0.0.0.0',
86 31 => '0.0.0.1',
87 30 => '0.0.0.3',
88 29 => '0.0.0.7',
89 28 => '0.0.0.15',
90 27 => '0.0.0.31',
91 26 => '0.0.0.63',
92 25 => '0.0.0.127',
93 24 => '0.0.0.255',
94 23 => '0.0.1.255',
95 22 => '0.0.3.255',
96 21 => '0.0.7.255',
97 20 => '0.0.15.255',
98 19 => '0.0.31.255',
99 18 => '0.0.63.255',
100 17 => '0.0.127.255',
101 16 => '0.0.255.25',
102 15 => '0.1.255.255',
103 14 => '0.3.255.255',
104 13 => '0.7.255.255',
105 12 => '0.15.255.255',
106 11 => '0.31.255.255',
107 10 => '0.63.255.255',
108 9 => '0.127.255.255',
109 8 => '0.255.255.255',
110 7 => '1.255.255.255',
111 6 => '3.255.255.255',
112 5 => '7.255.255.255',
113 4 => '15.255.255.255',
114 3 => '31.255.255.255',
115 2 => '63.255.255.255',
116 1 => '127.255.255.255'
117 );
118
119 // This function assures that specified argument was passed
120 // and is a number greater than zero.
121 function assertUIntArg ($argname, $allow_zero = FALSE)
122 {
123 if (!isset ($_REQUEST[$argname]))
124 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is missing');
125 if (!is_numeric ($_REQUEST[$argname]))
126 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a number');
127 if ($_REQUEST[$argname] < 0)
128 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is less than zero');
129 if (!$allow_zero and $_REQUEST[$argname] === 0)
130 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is zero');
131 }
132
133 // This function assures that specified argument was passed
134 // and is a non-empty string.
135 function assertStringArg ($argname, $ok_if_empty = FALSE)
136 {
137 if (!isset ($_REQUEST[$argname]))
138 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is missing');
139 if (!is_string ($_REQUEST[$argname]))
140 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a string');
141 if (!$ok_if_empty and !strlen ($_REQUEST[$argname]))
142 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is an empty string');
143 }
144
145 function assertBoolArg ($argname, $ok_if_empty = FALSE)
146 {
147 if (!isset ($_REQUEST[$argname]))
148 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is missing');
149 if (!is_string ($_REQUEST[$argname]) or $_REQUEST[$argname] != 'on')
150 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a string');
151 if (!$ok_if_empty and !strlen ($_REQUEST[$argname]))
152 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is an empty string');
153 }
154
155 function assertIPv4Arg ($argname, $ok_if_empty = FALSE)
156 {
157 assertStringArg ($argname, $ok_if_empty);
158 if (strlen ($_REQUEST[$argname]) and long2ip (ip2long ($_REQUEST[$argname])) !== $_REQUEST[$argname])
159 throw new InvalidRequestArgException($argname, $_REQUEST[$argname], 'parameter is not a valid ipv4 address');
160 }
161
162 // Objects of some types should be explicitly shown as
163 // anonymous (labelless). This function is a single place where the
164 // decision about displayed name is made.
165 function setDisplayedName (&$cell)
166 {
167 if ($cell['name'] != '')
168 $cell['dname'] = $cell['name'];
169 else
170 {
171 $cell['atags'][] = array ('tag' => '$nameless');
172 if (considerConfiguredConstraint ($cell, 'NAMEWARN_LISTSRC'))
173 $cell['dname'] = 'ANONYMOUS ' . decodeObjectType ($cell['objtype_id'], 'o');
174 else
175 $cell['dname'] = '[' . decodeObjectType ($cell['objtype_id'], 'o') . ']';
176 }
177 }
178
179 // This function finds height of solid rectangle of atoms, which are all
180 // assigned to the same object. Rectangle base is defined by specified
181 // template.
182 function rectHeight ($rackData, $startRow, $template_idx)
183 {
184 $height = 0;
185 // The first met object_id is used to match all the folowing IDs.
186 $object_id = 0;
187 global $template;
188 do
189 {
190 for ($locidx = 0; $locidx < 3; $locidx++)
191 {
192 // At least one value in template is TRUE, but the following block
193 // can meet 'skipped' atoms. Let's ensure we have something after processing
194 // the first row.
195 if ($template[$template_idx][$locidx])
196 {
197 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
198 break 2;
199 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
200 break 2;
201 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
202 break 2;
203 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
204 break 2;
205 if ($object_id == 0)
206 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
207 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
208 break 2;
209 }
210 }
211 // If the first row can't offer anything, bail out.
212 if ($height == 0 and $object_id == 0)
213 break;
214 $height++;
215 }
216 while ($startRow - $height > 0);
217 # echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
218 # echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
219 # echo ") height==${height}<br>\n";
220 return $height;
221 }
222
223 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
224 // attributes.
225 function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
226 {
227 global $template, $templateWidth;
228 $colspan = 0;
229 for ($height = 0; $height < $maxheight; $height++)
230 {
231 for ($locidx = 0; $locidx < 3; $locidx++)
232 {
233 if ($template[$template_idx][$locidx])
234 {
235 // Add colspan/rowspan to the first row met and mark the following ones to skip.
236 // Explicitly show even single-cell spanned atoms, because rectHeight()
237 // is expeciting this data for correct calculation.
238 if ($colspan != 0)
239 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
240 else
241 {
242 $colspan = $templateWidth[$template_idx];
243 if ($colspan >= 1)
244 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
245 if ($maxheight >= 1)
246 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
247 }
248 }
249 }
250 }
251 return;
252 }
253
254 // This function sets rowspan/solspan/skipped atom attributes for renderRack()
255 // What we actually have to do is to find _all_ possible rectangles for each unit
256 // and then select the widest of those with the maximal square.
257 function markAllSpans (&$rackData = NULL)
258 {
259 if ($rackData == NULL)
260 {
261 showWarning ('Invalid rackData', __FUNCTION__);
262 return;
263 }
264 for ($i = $rackData['height']; $i > 0; $i--)
265 while (markBestSpan ($rackData, $i));
266 }
267
268 // Calculate height of 6 possible span templates (array is presorted by width
269 // descending) and mark the best (if any).
270 function markBestSpan (&$rackData, $i)
271 {
272 global $template, $templateWidth;
273 for ($j = 0; $j < 6; $j++)
274 {
275 $height[$j] = rectHeight ($rackData, $i, $j);
276 $square[$j] = $height[$j] * $templateWidth[$j];
277 }
278 // find the widest rectangle of those with maximal height
279 $maxsquare = max ($square);
280 if (!$maxsquare)
281 return FALSE;
282 $best_template_index = 0;
283 for ($j = 0; $j < 6; $j++)
284 if ($square[$j] == $maxsquare)
285 {
286 $best_template_index = $j;
287 $bestheight = $height[$j];
288 break;
289 }
290 // distribute span marks
291 markSpan ($rackData, $i, $bestheight, $best_template_index);
292 return TRUE;
293 }
294
295 // We can mount 'F' atoms and unmount our own 'T' atoms.
296 function applyObjectMountMask (&$rackData, $object_id)
297 {
298 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
299 for ($locidx = 0; $locidx < 3; $locidx++)
300 switch ($rackData[$unit_no][$locidx]['state'])
301 {
302 case 'F':
303 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
304 break;
305 case 'T':
306 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
307 break;
308 default:
309 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
310 }
311 }
312
313 // Design change means transition between 'F' and 'A' and back.
314 function applyRackDesignMask (&$rackData)
315 {
316 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
317 for ($locidx = 0; $locidx < 3; $locidx++)
318 switch ($rackData[$unit_no][$locidx]['state'])
319 {
320 case 'F':
321 case 'A':
322 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
323 break;
324 default:
325 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
326 }
327 }
328
329 // The same for 'F' and 'U'.
330 function applyRackProblemMask (&$rackData)
331 {
332 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
333 for ($locidx = 0; $locidx < 3; $locidx++)
334 switch ($rackData[$unit_no][$locidx]['state'])
335 {
336 case 'F':
337 case 'U':
338 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
339 break;
340 default:
341 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
342 }
343 }
344
345 // This function highlights specified object (and removes previous highlight).
346 function highlightObject (&$rackData, $object_id)
347 {
348 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
349 for ($locidx = 0; $locidx < 3; $locidx++)
350 if
351 (
352 $rackData[$unit_no][$locidx]['state'] == 'T' and
353 $rackData[$unit_no][$locidx]['object_id'] == $object_id
354 )
355 $rackData[$unit_no][$locidx]['hl'] = 'h';
356 else
357 unset ($rackData[$unit_no][$locidx]['hl']);
358 }
359
360 // This function marks atoms to selected or not depending on their current state.
361 function markupAtomGrid (&$data, $checked_state)
362 {
363 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
364 for ($locidx = 0; $locidx < 3; $locidx++)
365 {
366 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
367 continue;
368 if ($data[$unit_no][$locidx]['state'] == $checked_state)
369 $data[$unit_no][$locidx]['checked'] = ' checked';
370 else
371 $data[$unit_no][$locidx]['checked'] = '';
372 }
373 }
374
375 // This function is almost a clone of processGridForm(), but doesn't save anything to database
376 // Return value is the changed rack data.
377 // Here we assume that correct filter has already been applied, so we just
378 // set or unset checkbox inputs w/o changing atom state.
379 function mergeGridFormToRack (&$rackData)
380 {
381 $rack_id = $rackData['id'];
382 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
383 for ($locidx = 0; $locidx < 3; $locidx++)
384 {
385 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
386 continue;
387 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
388 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
389 $rackData[$unit_no][$locidx]['checked'] = ' checked';
390 else
391 $rackData[$unit_no][$locidx]['checked'] = '';
392 }
393 }
394
395 // netmask conversion from length to number
396 function binMaskFromDec ($maskL)
397 {
398 $map_straight = array (
399 0 => 0x00000000,
400 1 => 0x80000000,
401 2 => 0xc0000000,
402 3 => 0xe0000000,
403 4 => 0xf0000000,
404 5 => 0xf8000000,
405 6 => 0xfc000000,
406 7 => 0xfe000000,
407 8 => 0xff000000,
408 9 => 0xff800000,
409 10 => 0xffc00000,
410 11 => 0xffe00000,
411 12 => 0xfff00000,
412 13 => 0xfff80000,
413 14 => 0xfffc0000,
414 15 => 0xfffe0000,
415 16 => 0xffff0000,
416 17 => 0xffff8000,
417 18 => 0xffffc000,
418 19 => 0xffffe000,
419 20 => 0xfffff000,
420 21 => 0xfffff800,
421 22 => 0xfffffc00,
422 23 => 0xfffffe00,
423 24 => 0xffffff00,
424 25 => 0xffffff80,
425 26 => 0xffffffc0,
426 27 => 0xffffffe0,
427 28 => 0xfffffff0,
428 29 => 0xfffffff8,
429 30 => 0xfffffffc,
430 31 => 0xfffffffe,
431 32 => 0xffffffff,
432 );
433 return $map_straight[$maskL];
434 }
435
436 // complementary value
437 function binInvMaskFromDec ($maskL)
438 {
439 $map_compl = array (
440 0 => 0xffffffff,
441 1 => 0x7fffffff,
442 2 => 0x3fffffff,
443 3 => 0x1fffffff,
444 4 => 0x0fffffff,
445 5 => 0x07ffffff,
446 6 => 0x03ffffff,
447 7 => 0x01ffffff,
448 8 => 0x00ffffff,
449 9 => 0x007fffff,
450 10 => 0x003fffff,
451 11 => 0x001fffff,
452 12 => 0x000fffff,
453 13 => 0x0007ffff,
454 14 => 0x0003ffff,
455 15 => 0x0001ffff,
456 16 => 0x0000ffff,
457 17 => 0x00007fff,
458 18 => 0x00003fff,
459 19 => 0x00001fff,
460 20 => 0x00000fff,
461 21 => 0x000007ff,
462 22 => 0x000003ff,
463 23 => 0x000001ff,
464 24 => 0x000000ff,
465 25 => 0x0000007f,
466 26 => 0x0000003f,
467 27 => 0x0000001f,
468 28 => 0x0000000f,
469 29 => 0x00000007,
470 30 => 0x00000003,
471 31 => 0x00000001,
472 32 => 0x00000000,
473 );
474 return $map_compl[$maskL];
475 }
476
477 // This function looks up 'has_problems' flag for 'T' atoms
478 // and modifies 'hl' key. May be, this should be better done
479 // in amplifyCell(). We don't honour 'skipped' key, because
480 // the function is also used for thumb creation.
481 function markupObjectProblems (&$rackData)
482 {
483 for ($i = $rackData['height']; $i > 0; $i--)
484 for ($locidx = 0; $locidx < 3; $locidx++)
485 if ($rackData[$i][$locidx]['state'] == 'T')
486 {
487 $object = spotEntity ('object', $rackData[$i][$locidx]['object_id']);
488 if ($object['has_problems'] == 'yes')
489 {
490 // Object can be already highlighted.
491 if (isset ($rackData[$i][$locidx]['hl']))
492 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
493 else
494 $rackData[$i][$locidx]['hl'] = 'w';
495 }
496 }
497 }
498
499 // Return a uniformly (010203040506 or 0102030405060708) formatted address, if it is present
500 // in the provided string, an empty string for an empty string or NULL for error.
501 function l2addressForDatabase ($string)
502 {
503 $string = strtoupper ($string);
504 switch (TRUE)
505 {
506 case ($string == '' or preg_match (RE_L2_SOLID, $string) or preg_match (RE_L2_WWN_SOLID, $string)):
507 return $string;
508 case (preg_match (RE_L2_IFCFG, $string) or preg_match (RE_L2_WWN_COLON, $string)):
509 // reformat output of SunOS ifconfig
510 $ret = '';
511 foreach (explode (':', $string) as $byte)
512 $ret .= (strlen ($byte) == 1 ? '0' : '') . $byte;
513 return $ret;
514 case (preg_match (RE_L2_CISCO, $string)):
515 return str_replace ('.', '', $string);
516 case (preg_match (RE_L2_IPCFG, $string) or preg_match (RE_L2_WWN_HYPHEN, $string)):
517 return str_replace ('-', '', $string);
518 default:
519 return NULL;
520 }
521 }
522
523 function l2addressFromDatabase ($string)
524 {
525 switch (strlen ($string))
526 {
527 case 12: // Ethernet
528 case 16: // FireWire/Fibre Channel
529 $ret = implode (':', str_split ($string, 2));
530 break;
531 default:
532 $ret = $string;
533 break;
534 }
535 return $ret;
536 }
537
538 // The following 2 functions return previous and next rack IDs for
539 // a given rack ID. The order of racks is the same as in renderRackspace()
540 // or renderRow().
541 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
542 {
543 if ($row_id <= 0 or $rack_id <= 0)
544 {
545 showWarning ('Invalid arguments passed', __FUNCTION__);
546 return NULL;
547 }
548 $rackList = listCells ('rack', $row_id);
549 doubleLink ($rackList);
550 if (isset ($rackList[$rack_id]['prev_key']))
551 return $rackList[$rack_id]['prev_key'];
552 return NULL;
553 }
554
555 function getNextIDforRack ($row_id = 0, $rack_id = 0)
556 {
557 if ($row_id <= 0 or $rack_id <= 0)
558 {
559 showWarning ('Invalid arguments passed', __FUNCTION__);
560 return NULL;
561 }
562 $rackList = listCells ('rack', $row_id);
563 doubleLink ($rackList);
564 if (isset ($rackList[$rack_id]['next_key']))
565 return $rackList[$rack_id]['next_key'];
566 return NULL;
567 }
568
569 // This function finds previous and next array keys for each array key and
570 // modifies its argument accordingly.
571 function doubleLink (&$array)
572 {
573 $prev_key = NULL;
574 foreach (array_keys ($array) as $key)
575 {
576 if ($prev_key)
577 {
578 $array[$key]['prev_key'] = $prev_key;
579 $array[$prev_key]['next_key'] = $key;
580 }
581 $prev_key = $key;
582 }
583 }
584
585 function sortTokenize ($a, $b)
586 {
587 $aold='';
588 while ($a != $aold)
589 {
590 $aold=$a;
591 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
592 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
593 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
594 }
595
596 $bold='';
597 while ($b != $bold)
598 {
599 $bold=$b;
600 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
601 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
602 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
603 }
604
605
606
607 $ar = explode(' ', $a);
608 $br = explode(' ', $b);
609 for ($i=0; $i<count($ar) && $i<count($br); $i++)
610 {
611 $ret = 0;
612 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
613 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
614 else
615 $ret = strcasecmp($ar[$i], $br[$i]);
616 if ($ret != 0)
617 return $ret;
618 }
619 if ($i<count($ar))
620 return 1;
621 if ($i<count($br))
622 return -1;
623 return 0;
624 }
625
626 function sortByName ($a, $b)
627 {
628 $result = sortTokenize ($a['name'], $b['name']);
629 if ($result != 0)
630 return $result;
631 if ($a['iif_id'] != $b['iif_id'])
632 return $a['iif_id'] - $b['iif_id'];
633 $result = strcmp ($a['label'], $b['label']);
634 if ($result != 0)
635 return $result;
636 $result = strcmp ($a['l2address'], $b['l2address']);
637 if ($result != 0)
638 return $result;
639 return $a['id'] - $b['id'];
640 }
641
642 function sortObjectAddressesAndNames ($a, $b)
643 {
644 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
645 if ($objname_cmp == 0)
646 {
647 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
648 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
649 $objname_cmp = sortTokenize($name_a, $name_b);
650 if ($objname_cmp == 0)
651 sortTokenize($a['ip'], $b['ip']);
652 return $objname_cmp;
653 }
654 return $objname_cmp;
655 }
656
657 // This function returns an array of single element of object's FQDN attribute,
658 // if FQDN is set. The next choice is object's common name, if it looks like a
659 // hostname. Otherwise an array of all 'regular' IP addresses of the
660 // object is returned (which may appear 0 and more elements long).
661 function findAllEndpoints ($object_id, $fallback = '')
662 {
663 foreach (getAttrValues ($object_id) as $record)
664 if ($record['id'] == 3 && strlen ($record['value'])) // FQDN
665 return array ($record['value']);
666 $regular = array();
667 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
668 if ($alloc['type'] == 'regular')
669 $regular[] = $dottedquad;
670 if (!count ($regular) && strlen ($fallback))
671 return array ($fallback);
672 return $regular;
673 }
674
675 // Some records in the dictionary may be written as plain text or as Wiki
676 // link in the following syntax:
677 // 1. word
678 // 2. [[word URL]] // FIXME: this isn't working
679 // 3. [[word word word | URL]]
680 // This function parses the line and returns text suitable for either A
681 // (rendering <A HREF>) or O (for <OPTION>).
682 function parseWikiLink ($line, $which)
683 {
684 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
685 {
686 // always strip the marker for A-data, but let cookOptgroup()
687 // do this later (otherwise it can't sort groups out)
688 if ($which == 'a')
689 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
690 else
691 return $line;
692 }
693 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
694 $s = explode ('|', $line);
695 $o_value = trim ($s[0]);
696 if ($which == 'o')
697 return $o_value;
698 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
699 $a_value = trim ($s[1]);
700 return "<a href='${a_value}'>${o_value}</a>";
701 }
702
703 // FIXME: should this be saved as "P-data"?
704 function execGMarker ($line)
705 {
706 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
707 }
708
709 // rackspace usage for a single rack
710 // (T + W + U) / (height * 3 - A)
711 function getRSUforRack ($data = NULL)
712 {
713 if ($data == NULL)
714 {
715 showWarning ('Invalid argument', __FUNCTION__);
716 return NULL;
717 }
718 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
719 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
720 for ($locidx = 0; $locidx < 3; $locidx++)
721 $counter[$data[$unit_no][$locidx]['state']]++;
722 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
723 }
724
725 // Same for row.
726 function getRSUforRackRow ($rowData = NULL)
727 {
728 if ($rowData === NULL)
729 {
730 showWarning ('Invalid argument', __FUNCTION__);
731 return NULL;
732 }
733 if (!count ($rowData))
734 return 0;
735 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
736 $total_height = 0;
737 foreach (array_keys ($rowData) as $rack_id)
738 {
739 $data = spotEntity ('rack', $rack_id);
740 amplifyCell ($data);
741 $total_height += $data['height'];
742 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
743 for ($locidx = 0; $locidx < 3; $locidx++)
744 $counter[$data[$unit_no][$locidx]['state']]++;
745 }
746 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
747 }
748
749 // Make sure the string is always wrapped with LF characters
750 function lf_wrap ($str)
751 {
752 $ret = trim ($str, "\r\n");
753 if (strlen ($ret))
754 $ret .= "\n";
755 return $ret;
756 }
757
758 // Adopted from Mantis BTS code.
759 function string_insert_hrefs ($s)
760 {
761 if (getConfigVar ('DETECT_URLS') != 'yes')
762 return $s;
763 # Find any URL in a string and replace it by a clickable link
764 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
765 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
766 $s);
767 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
768 '<a href="mailto:\0">\0</a>',
769 $s);
770 return $s;
771 }
772
773 // Idem.
774 function email_regex_simple ()
775 {
776 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
777 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
778 }
779
780 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
781 // for the requested object_type_id.
782 function getAutoPorts ($type_id)
783 {
784 $ret = array();
785 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
786 foreach ($typemap as $equation)
787 {
788 $tmp = explode ('=', $equation);
789 if (count ($tmp) != 2)
790 continue;
791 $objtype_id = $tmp[0];
792 if ($objtype_id != $type_id)
793 continue;
794 $portlist = $tmp[1];
795 foreach (explode ('+', $portlist) as $product)
796 {
797 $tmp = explode ('*', $product);
798 if (count ($tmp) != 3)
799 continue;
800 $nports = $tmp[0];
801 $port_type = $tmp[1];
802 $format = $tmp[2];
803 for ($i = 0; $i < $nports; $i++)
804 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
805 }
806 }
807 return $ret;
808 }
809
810 // Use pre-served trace to traverse the tree, then place given node where it belongs.
811 function pokeNode (&$tree, $trace, $key, $value, $threshold = 0)
812 {
813 // This function needs the trace to be followed FIFO-way. The fastest
814 // way to do so is to use array_push() for putting values into the
815 // list and array_shift() for getting them out. This exposed up to 11%
816 // performance gain compared to other patterns of array_push/array_unshift/
817 // array_reverse/array_pop/array_shift conjunction.
818 $myid = array_shift ($trace);
819 if (!count ($trace)) // reached the target
820 {
821 if (!$threshold or ($threshold and $tree[$myid]['kidc'] + 1 < $threshold))
822 $tree[$myid]['kids'][$key] = $value;
823 // Reset accumulated records once, when the limit is reached, not each time
824 // after that.
825 if (++$tree[$myid]['kidc'] == $threshold)
826 $tree[$myid]['kids'] = array();
827 }
828 else // not yet
829 {
830 $self = __FUNCTION__;
831 $self ($tree[$myid]['kids'], $trace, $key, $value, $threshold);
832 }
833 }
834
835 // Likewise traverse the tree with the trace and return the final node.
836 function peekNode ($tree, $trace, $target_id)
837 {
838 $self = __FUNCTION__;
839 if (NULL === ($next = array_shift ($trace))) // warm
840 {
841 foreach ($tree as $node)
842 if (array_key_exists ('id', $node) and $node['id'] == $target_id) // hot
843 return $node;
844 }
845 else // cold
846 {
847 foreach ($tree as $node)
848 if (array_key_exists ('id', $node) and $node['id'] == $next) // warmer
849 return $self ($node['kids'], $trace, $target_id);
850 }
851 // HCF
852 return NULL;
853 }
854
855 // Build a tree from the item list and return it. Input and output data is
856 // indexed by item id (nested items in output are recursively stored in 'kids'
857 // key, which is in turn indexed by id. Functions, which are ready to handle
858 // tree collapsion/expansion themselves, may request non-zero threshold value
859 // for smaller resulting tree.
860 function treeFromList (&$orig_nodelist, $threshold = 0, $return_main_payload = TRUE)
861 {
862 $tree = array();
863 $nodelist = $orig_nodelist;
864 // Array equivalent of traceEntity() function.
865 $trace = array();
866 // set kidc and kids only once
867 foreach (array_keys ($nodelist) as $nodeid)
868 {
869 $nodelist[$nodeid]['kidc'] = 0;
870 $nodelist[$nodeid]['kids'] = array();
871 }
872 do
873 {
874 $nextpass = FALSE;
875 foreach (array_keys ($nodelist) as $nodeid)
876 {
877 // When adding a node to the working tree, book another
878 // iteration, because the new item could make a way for
879 // others onto the tree. Also remove any item added from
880 // the input list, so iteration base shrinks.
881 // First check if we can assign directly.
882 if ($nodelist[$nodeid]['parent_id'] == NULL)
883 {
884 $tree[$nodeid] = $nodelist[$nodeid];
885 $trace[$nodeid] = array(); // Trace to root node is empty
886 unset ($nodelist[$nodeid]);
887 $nextpass = TRUE;
888 }
889 // Now look if it fits somewhere on already built tree.
890 elseif (isset ($trace[$nodelist[$nodeid]['parent_id']]))
891 {
892 // Trace to a node is a trace to its parent plus parent id.
893 $trace[$nodeid] = $trace[$nodelist[$nodeid]['parent_id']];
894 $trace[$nodeid][] = $nodelist[$nodeid]['parent_id'];
895 pokeNode ($tree, $trace[$nodeid], $nodeid, $nodelist[$nodeid], $threshold);
896 // path to any other node is made of all parent nodes plus the added node itself
897 unset ($nodelist[$nodeid]);
898 $nextpass = TRUE;
899 }
900 }
901 }
902 while ($nextpass);
903 if (!$return_main_payload)
904 return $nodelist;
905 // update each input node with its backtrace route
906 foreach ($trace as $nodeid => $route)
907 $orig_nodelist[$nodeid]['trace'] = $route;
908 return $tree;
909 }
910
911 // Build a tree from the tag list and return everything _except_ the tree.
912 // IOW, return taginfo items, which have parent_id set and pointing outside
913 // of the "normal" tree, which originates from the root.
914 function getOrphanedTags ()
915 {
916 global $taglist;
917 return treeFromList ($taglist, 0, FALSE);
918 }
919
920 function serializeTags ($chain, $baseurl = '')
921 {
922 $comma = '';
923 $ret = '';
924 foreach ($chain as $taginfo)
925 {
926 $ret .= $comma .
927 ($baseurl == '' ? '' : "<a href='${baseurl}cft[]=${taginfo['id']}'>") .
928 $taginfo['tag'] .
929 ($baseurl == '' ? '' : '</a>');
930 $comma = ', ';
931 }
932 return $ret;
933 }
934
935 // Return the list of missing implicit tags.
936 function getImplicitTags ($oldtags)
937 {
938 global $taglist;
939 $tmp = array();
940 foreach ($oldtags as $taginfo)
941 $tmp = array_merge ($tmp, $taglist[$taginfo['id']]['trace']);
942 // don't call array_unique here, it is in the function we will call now
943 return buildTagChainFromIds ($tmp);
944 }
945
946 // Minimize the chain: exclude all implicit tags and return the result.
947 // This function makes use of an external cache with a miss/hit ratio
948 // about 3/7 (ticket:255).
949 function getExplicitTagsOnly ($chain)
950 {
951 global $taglist, $tagRelCache;
952 $ret = array();
953 foreach (array_keys ($chain) as $keyA) // check each A
954 {
955 $tagidA = $chain[$keyA]['id'];
956 // do not include A in result, if A is seen on the trace of any B!=A
957 foreach (array_keys ($chain) as $keyB)
958 {
959 $tagidB = $chain[$keyB]['id'];
960 if ($tagidA == $tagidB)
961 continue;
962 if (!isset ($tagRelCache[$tagidA][$tagidB]))
963 $tagRelCache[$tagidA][$tagidB] = in_array ($tagidA, $taglist[$tagidB]['trace']);
964 if ($tagRelCache[$tagidA][$tagidB] === TRUE) // A is ancestor of B
965 continue 2; // skip this A
966 }
967 $ret[] = $chain[$keyA];
968 }
969 return $ret;
970 }
971
972 // Universal autotags generator, a complementing function for loadEntityTags().
973 // Bypass key isn't strictly typed, but interpreted depending on the realm.
974 function generateEntityAutoTags ($cell)
975 {
976 $ret = array();
977 switch ($cell['realm'])
978 {
979 case 'rack':
980 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
981 $ret[] = array ('tag' => '$any_rack');
982 break;
983 case 'object':
984 $ret[] = array ('tag' => '$id_' . $cell['id']);
985 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
986 $ret[] = array ('tag' => '$any_object');
987 if (validTagName ('$cn_' . $cell['name'], TRUE))
988 $ret[] = array ('tag' => '$cn_' . $cell['name']);
989 if (!strlen ($cell['rack_id']))
990 $ret[] = array ('tag' => '$unmounted');
991 if (!$cell['nports'])
992 $ret[] = array ('tag' => '$portless');
993 if ($cell['asset_no'] == '')
994 $ret[] = array ('tag' => '$no_asset_tag');
995 break;
996 case 'ipv4net':
997 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
998 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
999 for ($i = 8; $i < 32; $i++)
1000 {
1001 // these conditions hit 1 to 3 times per each i
1002 if ($cell['mask'] >= $i)
1003 $ret[] = array ('tag' => '$masklen_ge_' . $i);
1004 if ($cell['mask'] <= $i)
1005 $ret[] = array ('tag' => '$masklen_le_' . $i);
1006 if ($cell['mask'] == $i)
1007 $ret[] = array ('tag' => '$masklen_eq_' . $i);
1008 }
1009 $ret[] = array ('tag' => '$any_ip4net');
1010 $ret[] = array ('tag' => '$any_net');
1011 break;
1012 case 'ipv4vs':
1013 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
1014 $ret[] = array ('tag' => '$any_ipv4vs');
1015 $ret[] = array ('tag' => '$any_vs');
1016 break;
1017 case 'ipv4rspool':
1018 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
1019 $ret[] = array ('tag' => '$any_ipv4rsp');
1020 $ret[] = array ('tag' => '$any_rsp');
1021 break;
1022 case 'user':
1023 // {$username_XXX} autotag is generated always, but {$userid_XXX}
1024 // appears only for accounts, which exist in local database.
1025 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
1026 if (isset ($cell['user_id']))
1027 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
1028 break;
1029 case 'file':
1030 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
1031 $ret[] = array ('tag' => '$any_file');
1032 break;
1033 default: // HCF!
1034 break;
1035 }
1036 // {$tagless} doesn't apply to users
1037 switch ($cell['realm'])
1038 {
1039 case 'rack':
1040 case 'object':
1041 case 'ipv4net':
1042 case 'ipv4vs':
1043 case 'ipv4rspool':
1044 case 'file':
1045 if (!count ($cell['etags']))
1046 $ret[] = array ('tag' => '$untagged');
1047 break;
1048 default:
1049 break;
1050 }
1051 return $ret;
1052 }
1053
1054 // Check, if the given tag is present on the chain (will only work
1055 // for regular tags with tag ID set.
1056 function tagOnChain ($taginfo, $tagchain)
1057 {
1058 if (!isset ($taginfo['id']))
1059 return FALSE;
1060 foreach ($tagchain as $test)
1061 if ($test['id'] == $taginfo['id'])
1062 return TRUE;
1063 return FALSE;
1064 }
1065
1066 function tagNameOnChain ($tagname, $tagchain)
1067 {
1068 foreach ($tagchain as $test)
1069 if ($test['tag'] == $tagname)
1070 return TRUE;
1071 return FALSE;
1072 }
1073
1074 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1075 // Assume, that neither of the lists contains duplicates.
1076 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1077 function tagChainCmp ($chain1, $chain2)
1078 {
1079 if (count ($chain1) != count ($chain2))
1080 return TRUE;
1081 foreach ($chain1 as $taginfo1)
1082 if (!tagOnChain ($taginfo1, $chain2))
1083 return TRUE;
1084 return FALSE;
1085 }
1086
1087 function redirectIfNecessary ()
1088 {
1089 global
1090 $trigger,
1091 $pageno,
1092 $tabno;
1093 $pmap = array
1094 (
1095 'accounts' => 'userlist',
1096 'rspools' => 'ipv4rsplist',
1097 'rspool' => 'ipv4rsp',
1098 'vservices' => 'ipv4vslist',
1099 'vservice' => 'ipv4vs',
1100 'objects' => 'depot',
1101 'objgroup' => 'depot',
1102 );
1103 $tmap = array();
1104 $tmap['objects']['newmulti'] = 'addmore';
1105 $tmap['objects']['newobj'] = 'addmore';
1106 $tmap['object']['switchvlans'] = 'livevlans';
1107 $tmap['object']['slb'] = 'editrspvs';
1108 $tmap['object']['portfwrd'] = 'nat4';
1109 $tmap['object']['network'] = 'ipv4';
1110 if (isset ($pmap[$pageno]))
1111 redirectUser ($pmap[$pageno], $tabno);
1112 if (isset ($tmap[$pageno][$tabno]))
1113 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1114 // check if we accidentaly got on a dynamic tab that shouldn't be shown for this object
1115 if (isset ($trigger[$pageno][$tabno]) and !strlen ($trigger[$pageno][$tabno] ()))
1116 redirectUser ($pageno, 'default');
1117 }
1118
1119 function prepareNavigation() {
1120 global
1121 $pageno,
1122 $tabno;
1123
1124 $pageno = (isset ($_REQUEST['page'])) ? $_REQUEST['page'] : 'index';
1125
1126 // Special handling of tab number to substitute the "last" index where applicable.
1127 // Always show explicitly requested tab, substitute the last used name in case
1128 // it is awailable, fall back to the default one.
1129
1130 if (isset ($_REQUEST['tab'])) {
1131 $tabno = $_REQUEST['tab'];
1132 } elseif (basename($_SERVER['PHP_SELF']) == 'index.php' and getConfigVar ('SHOW_LAST_TAB') == 'yes' and isset ($_SESSION['RTLT'][$pageno])) {
1133 redirectUser ($pageno, $_SESSION['RTLT'][$pageno]);
1134 } else {
1135 $tabno = 'default';
1136 }
1137 }
1138
1139 function fixContext ($target = NULL)
1140 {
1141 global
1142 $pageno,
1143 $auto_tags,
1144 $expl_tags,
1145 $impl_tags,
1146 $target_given_tags,
1147 $user_given_tags,
1148 $etype_by_pageno,
1149 $page;
1150
1151 if ($target !== NULL)
1152 {
1153 $target_given_tags = $target['etags'];
1154 // Don't reset autochain, because auth procedures could push stuff there in.
1155 // Another important point is to ignore 'user' realm, so we don't infuse effective
1156 // context with autotags of the displayed account.
1157 if ($target['realm'] != 'user')
1158 $auto_tags = array_merge ($auto_tags, $target['atags']);
1159 }
1160 elseif (array_key_exists ($pageno, $etype_by_pageno))
1161 {
1162 // Each page listed in the map above requires one uint argument.
1163 $target_realm = $etype_by_pageno[$pageno];
1164 assertUIntArg ($page[$pageno]['bypass']);
1165 $target_id = $_REQUEST[$page[$pageno]['bypass']];
1166 $target = spotEntity ($target_realm, $target_id);
1167 $target_given_tags = $target['etags'];
1168 if ($target['realm'] != 'user')
1169 $auto_tags = array_merge ($auto_tags, $target['atags']);
1170 }
1171 // Explicit and implicit chains should be normally empty at this point, so
1172 // overwrite the contents anyway.
1173 $expl_tags = mergeTagChains ($user_given_tags, $target_given_tags);
1174 $impl_tags = getImplicitTags ($expl_tags);
1175 }
1176
1177 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1178 // records indexed by tag IDs (tag chain).
1179 function buildTagChainFromIds ($tagidlist)
1180 {
1181 global $taglist;
1182 $ret = array();
1183 foreach (array_unique ($tagidlist) as $tag_id)
1184 if (isset ($taglist[$tag_id]))
1185 $ret[] = $taglist[$tag_id];
1186 return $ret;
1187 }
1188
1189 // Process a given tag tree and return only meaningful branches. The resulting
1190 // (sub)tree will have refcnt leaves on every last branch.
1191 function getObjectiveTagTree ($tree, $realm, $preselect)
1192 {
1193 $self = __FUNCTION__;
1194 $ret = array();
1195 foreach ($tree as $taginfo)
1196 {
1197 $subsearch = $self ($taginfo['kids'], $realm, $preselect);
1198 // If the current node addresses something, add it to the result
1199 // regardless of how many sub-nodes it features.
1200 if
1201 (
1202 isset ($taginfo['refcnt'][$realm]) or
1203 count ($subsearch) > 1 or
1204 in_array ($taginfo['id'], $preselect)
1205 )
1206 $ret[] = array
1207 (
1208 'id' => $taginfo['id'],
1209 'tag' => $taginfo['tag'],
1210 'parent_id' => $taginfo['parent_id'],
1211 'refcnt' => $taginfo['refcnt'],
1212 'kids' => $subsearch
1213 );
1214 else
1215 $ret = array_merge ($ret, $subsearch);
1216 }
1217 return $ret;
1218 }
1219
1220 // Get taginfo record by tag name, return NULL, if record doesn't exist.
1221 function getTagByName ($target_name)
1222 {
1223 global $taglist;
1224 foreach ($taglist as $taginfo)
1225 if ($taginfo['tag'] == $target_name)
1226 return $taginfo;
1227 return NULL;
1228 }
1229
1230 // Merge two chains, filtering dupes out. Return the resulting superset.
1231 function mergeTagChains ($chainA, $chainB)
1232 {
1233 // $ret = $chainA;
1234 // Reindex by tag id in any case.
1235 $ret = array();
1236 foreach ($chainA as $tag)
1237 $ret[$tag['id']] = $tag;
1238 foreach ($chainB as $tag)
1239 if (!isset ($ret[$tag['id']]))
1240 $ret[$tag['id']] = $tag;
1241 return $ret;
1242 }
1243
1244 function getCellFilter ()
1245 {
1246 global $sic;
1247 if (isset ($_REQUEST['tagfilter']) and is_array ($_REQUEST['tagfilter']))
1248 {
1249 $_REQUEST['cft'] = $_REQUEST['tagfilter'];
1250 unset ($_REQUEST['tagfilter']);
1251 }
1252 $ret = array
1253 (
1254 'tagidlist' => array(),
1255 'tnamelist' => array(),
1256 'pnamelist' => array(),
1257 'andor' => '',
1258 'text' => '',
1259 'extratext' => '',
1260 'expression' => array(),
1261 'urlextra' => '', // Just put text here and let makeHref call urlencode().
1262 );
1263 switch (TRUE)
1264 {
1265 case (!isset ($_REQUEST['andor'])):
1266 $andor2 = getConfigVar ('FILTER_DEFAULT_ANDOR');
1267 break;
1268 case ($_REQUEST['andor'] == 'and'):
1269 case ($_REQUEST['andor'] == 'or'):
1270 $ret['andor'] = $andor2 = $_REQUEST['andor'];
1271 $ret['urlextra'] .= '&andor=' . $ret['andor'];
1272 break;
1273 default:
1274 showWarning ('Invalid and/or switch value in submitted form', __FUNCTION__);
1275 return NULL;
1276 }
1277 $andor1 = '';
1278 // Both tags and predicates, which don't exist, should be
1279 // handled somehow. Discard them silently for now.
1280 if (isset ($_REQUEST['cft']) and is_array ($_REQUEST['cft']))
1281 {
1282 global $taglist;
1283 foreach ($_REQUEST['cft'] as $req_id)
1284 if (isset ($taglist[$req_id]))
1285 {
1286 $ret['tagidlist'][] = $req_id;
1287 $ret['tnamelist'][] = $taglist[$req_id]['tag'];
1288 $ret['text'] .= $andor1 . '{' . $taglist[$req_id]['tag'] . '}';
1289 $andor1 = ' ' . $andor2 . ' ';
1290 $ret['urlextra'] .= '&cft[]=' . $req_id;
1291 }
1292 }
1293 if (isset ($_REQUEST['cfp']) and is_array ($_REQUEST['cfp']))
1294 {
1295 global $pTable;
1296 foreach ($_REQUEST['cfp'] as $req_name)
1297 if (isset ($pTable[$req_name]))
1298 {
1299 $ret['pnamelist'][] = $req_name;
1300 $ret['text'] .= $andor1 . '[' . $req_name . ']';
1301 $andor1 = ' ' . $andor2 . ' ';
1302 $ret['urlextra'] .= '&cfp[]=' . $req_name;
1303 }
1304 }
1305 // Extra text comes from TEXTAREA and is easily screwed by standard escaping function.
1306 if (isset ($sic['cfe']))
1307 {
1308 // Only consider extra text, when it is a correct RackCode expression.
1309 $parse = spotPayload ($sic['cfe'], 'SYNT_EXPR');
1310 if ($parse['result'] == 'ACK')
1311 {
1312 $ret['extratext'] = trim ($sic['cfe']);
1313 $ret['urlextra'] .= '&cfe=' . $ret['extratext'];
1314 }
1315 }
1316 $finaltext = array();
1317 if (strlen ($ret['text']))
1318 $finaltext[] = '(' . $ret['text'] . ')';
1319 if (strlen ($ret['extratext']))
1320 $finaltext[] = '(' . $ret['extratext'] . ')';
1321 $finaltext = implode (' ' . $andor2 . ' ', $finaltext);
1322 if (strlen ($finaltext))
1323 {
1324 $parse = spotPayload ($finaltext, 'SYNT_EXPR');
1325 $ret['expression'] = $parse['result'] == 'ACK' ? $parse['load'] : NULL;
1326 // It's not quite fair enough to put the blame of the whole text onto
1327 // non-empty "extra" portion of it, but it's the only user-generated portion
1328 // of it, thus the most probable cause of parse error.
1329 if (strlen ($ret['extratext']))
1330 $ret['extraclass'] = $parse['result'] == 'ACK' ? 'validation-success' : 'validation-error';
1331 }
1332 return $ret;
1333 }
1334
1335 // Return an empty message log.
1336 function emptyLog ()
1337 {
1338 return array
1339 (
1340 'v' => 2,
1341 'm' => array()
1342 );
1343 }
1344
1345 // Return a message log consisting of only one message.
1346 function oneLiner ($code, $args = array())
1347 {
1348 $ret = emptyLog();
1349 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1350 return $ret;
1351 }
1352
1353 // Merge message payload from two message logs given and return the result.
1354 function mergeLogs ($log1, $log2)
1355 {
1356 $ret = emptyLog();
1357 $ret['m'] = array_merge ($log1['m'], $log2['m']);
1358 return $ret;
1359 }
1360
1361 function validTagName ($s, $allow_autotag = FALSE)
1362 {
1363 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1364 return TRUE;
1365 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1366 return TRUE;
1367 return FALSE;
1368 }
1369
1370 function redirectUser ($p, $t)
1371 {
1372 global $page;
1373 $l = "index.php?page=${p}&tab=${t}";
1374 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1375 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1376 header ("Location: " . $l);
1377 die;
1378 }
1379
1380 function getRackCodeStats ()
1381 {
1382 global $rackCode;
1383 $defc = $grantc = $modc = 0;
1384 foreach ($rackCode as $s)
1385 switch ($s['type'])
1386 {
1387 case 'SYNT_DEFINITION':
1388 $defc++;
1389 break;
1390 case 'SYNT_GRANT':
1391 $grantc++;
1392 break;
1393 case 'SYNT_CTXMOD':
1394 $modc++;
1395 break;
1396 default:
1397 break;
1398 }
1399 $ret = array
1400 (
1401 'Definition sentences' => $defc,
1402 'Grant sentences' => $grantc,
1403 'Context mod sentences' => $modc
1404 );
1405 return $ret;
1406 }
1407
1408 function getRackImageWidth ()
1409 {
1410 global $rtwidth;
1411 return 3 + $rtwidth[0] + $rtwidth[1] + $rtwidth[2] + 3;
1412 }
1413
1414 function getRackImageHeight ($units)
1415 {
1416 return 3 + 3 + $units * 2;
1417 }
1418
1419 // Perform substitutions and return resulting string
1420 // used solely by buildLVSConfig()
1421 function apply_macros ($macros, $subject)
1422 {
1423 $ret = $subject;
1424 foreach ($macros as $search => $replace)
1425 $ret = str_replace ($search, $replace, $ret);
1426 return $ret;
1427 }
1428
1429 function buildLVSConfig ($object_id = 0)
1430 {
1431 if ($object_id <= 0)
1432 {
1433 showWarning ('Invalid argument', __FUNCTION__);
1434 return;
1435 }
1436 $oInfo = spotEntity ('object', $object_id);
1437 $lbconfig = getSLBConfig ($object_id);
1438 if ($lbconfig === NULL)
1439 {
1440 showWarning ('getSLBConfig() failed', __FUNCTION__);
1441 return;
1442 }
1443 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1444 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1445 foreach ($lbconfig as $vs_id => $vsinfo)
1446 {
1447 $newconfig .= "########################################################\n" .
1448 "# VS (id == ${vs_id}): " . (!strlen ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1449 "# RS pool (id == ${vsinfo['pool_id']}): " . (!strlen ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1450 "########################################################\n";
1451 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1452 $macros = array
1453 (
1454 '%VIP%' => $vsinfo['vip'],
1455 '%VPORT%' => $vsinfo['vport'],
1456 '%PROTO%' => $vsinfo['proto'],
1457 '%VNAME%' => $vsinfo['vs_name'],
1458 '%RSPOOLNAME%' => $vsinfo['pool_name']
1459 );
1460 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1461 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1462 $newconfig .= apply_macros
1463 (
1464 $macros,
1465 lf_wrap ($vsinfo['vs_vsconfig']) .
1466 lf_wrap ($vsinfo['lb_vsconfig']) .
1467 lf_wrap ($vsinfo['pool_vsconfig'])
1468 );
1469 foreach ($vsinfo['rslist'] as $rs)
1470 {
1471 if (!strlen ($rs['rsport']))
1472 $rs['rsport'] = $vsinfo['vport'];
1473 $macros['%RSIP%'] = $rs['rsip'];
1474 $macros['%RSPORT%'] = $rs['rsport'];
1475 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1476 $newconfig .= apply_macros
1477 (
1478 $macros,
1479 lf_wrap ($vsinfo['vs_rsconfig']) .
1480 lf_wrap ($vsinfo['lb_rsconfig']) .
1481 lf_wrap ($vsinfo['pool_rsconfig']) .
1482 lf_wrap ($rs['rs_rsconfig'])
1483 );
1484 $newconfig .= "\t}\n";
1485 }
1486 $newconfig .= "}\n\n\n";
1487 }
1488 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1489 return str_replace ("\r", '', $newconfig);
1490 }
1491
1492 // Indicate occupation state of each IP address: none, ordinary or problematic.
1493 function markupIPv4AddrList (&$addrlist)
1494 {
1495 foreach (array_keys ($addrlist) as $ip_bin)
1496 {
1497 $refc = array
1498 (
1499 'shared' => 0, // virtual
1500 'virtual' => 0, // loopback
1501 'regular' => 0, // connected host
1502 'router' => 0 // connected gateway
1503 );
1504 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1505 $refc[$a['type']]++;
1506 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
1507 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1508 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
1509
1510 if ($nrealms == 1)
1511 $addrlist[$ip_bin]['class'] = 'trbusy';
1512 elseif ($nrealms > 1)
1513 $addrlist[$ip_bin]['class'] = 'trerror';
1514 else
1515 $addrlist[$ip_bin]['class'] = '';
1516 }
1517 }
1518
1519 // Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1520 function findRouters ($addrlist)
1521 {
1522 $ret = array();
1523 foreach ($addrlist as $addr)
1524 foreach ($addr['allocs'] as $alloc)
1525 if ($alloc['type'] == 'router')
1526 $ret[] = array
1527 (
1528 'id' => $alloc['object_id'],
1529 'iface' => $alloc['name'],
1530 'dname' => $alloc['object_name'],
1531 'addr' => $addr['ip']
1532 );
1533 return $ret;
1534 }
1535
1536 // Assist in tag chain sorting.
1537 function taginfoCmp ($tagA, $tagB)
1538 {
1539 return $tagA['ci'] - $tagB['ci'];
1540 }
1541
1542 // Compare networks. When sorting a tree, the records on the list will have
1543 // distinct base IP addresses.
1544 // "The comparison function must return an integer less than, equal to, or greater
1545 // than zero if the first argument is considered to be respectively less than,
1546 // equal to, or greater than the second." (c) PHP manual
1547 function IPv4NetworkCmp ($netA, $netB)
1548 {
1549 // There's a problem just substracting one u32 integer from another,
1550 // because the result may happen big enough to become a negative i32
1551 // integer itself (PHP tries to cast everything it sees to signed int)
1552 // The comparison below must treat positive and negative values of both
1553 // arguments.
1554 // Equal values give instant decision regardless of their [equal] sign.
1555 if ($netA['ip_bin'] == $netB['ip_bin'])
1556 return 0;
1557 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1558 // 0x00000001~0x7fffffff 1~2147483647
1559 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1560 // 0x80000000~0xffffffff -2147483648~-1
1561 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1562 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1563 if ($signA == $signB)
1564 {
1565 if ($netA['ip_bin'] > $netB['ip_bin'])
1566 return 1;
1567 else
1568 return -1;
1569 }
1570 else // With only one of two values being negative, it... wins!
1571 {
1572 if ($netA['ip_bin'] < $netB['ip_bin'])
1573 return 1;
1574 else
1575 return -1;
1576 }
1577 }
1578
1579 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1580 function sortTree (&$tree, $sortfunc = '')
1581 {
1582 if (!strlen ($sortfunc))
1583 return;
1584 $self = __FUNCTION__;
1585 usort ($tree, $sortfunc);
1586 // Don't make a mistake of directly iterating over the items of current level, because this way
1587 // the sorting will be performed on a _copy_ if each item, not the item itself.
1588 foreach (array_keys ($tree) as $tagid)
1589 $self ($tree[$tagid]['kids'], $sortfunc);
1590 }
1591
1592 function iptree_fill (&$netdata)
1593 {
1594 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
1595 return;
1596 // If we really have nested prefixes, they must fit into the tree.
1597 $worktree = array
1598 (
1599 'ip_bin' => $netdata['ip_bin'],
1600 'mask' => $netdata['mask']
1601 );
1602 foreach ($netdata['kids'] as $pfx)
1603 iptree_embed ($worktree, $pfx);
1604 $netdata['kids'] = iptree_construct ($worktree);
1605 $netdata['kidc'] = count ($netdata['kids']);
1606 }
1607
1608 function iptree_construct ($node)
1609 {
1610 $self = __FUNCTION__;
1611
1612 if (!isset ($node['right']))
1613 {
1614 if (!isset ($node['ip']))
1615 {
1616 $node['ip'] = long2ip ($node['ip_bin']);
1617 $node['kids'] = array();
1618 $node['kidc'] = 0;
1619 $node['name'] = '';
1620 }
1621 return array ($node);
1622 }
1623 else
1624 return array_merge ($self ($node['left']), $self ($node['right']));
1625 }
1626
1627 function iptree_embed (&$node, $pfx)
1628 {
1629 $self = __FUNCTION__;
1630
1631 // hit?
1632 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1633 {
1634 $node = $pfx;
1635 return;
1636 }
1637 if ($node['mask'] == $pfx['mask'])
1638 {
1639 throw new RuntimeException('Internal error, the recurring loop lost control');
1640 }
1641
1642 // split?
1643 if (!isset ($node['right']))
1644 {
1645 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
1646 $node['left']['mask'] = $node['mask'] + 1;
1647 $node['left']['ip_bin'] = $node['ip_bin'];
1648 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
1649 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] | binInvMaskFromDec ($node['left']['mask']));
1650
1651 $node['right']['mask'] = $node['mask'] + 1;
1652 $node['right']['ip_bin'] = $node['ip_bin'] + binInvMaskFromDec ($node['mask'] + 1) + 1;
1653 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
1654 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] | binInvMaskFromDec ($node['right']['mask']));
1655 }
1656
1657 // repeat!
1658 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1659 $self ($node['left'], $pfx);
1660 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1661 $self ($node['right'], $pfx);
1662 else
1663 {
1664 throw new RuntimeException ('Internal error, cannot decide between left and right');
1665 }
1666 }
1667
1668 function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
1669 {
1670 if (!strlen ($func))
1671 return;
1672 $self = __FUNCTION__;
1673 foreach (array_keys ($tree) as $key)
1674 {
1675 $func ($tree[$key]);
1676 if (strlen ($stopfunc) and $stopfunc ($tree[$key]))
1677 continue;
1678 $self ($tree[$key]['kids'], $func);
1679 }
1680 }
1681
1682 function loadIPv4AddrList (&$netinfo)
1683 {
1684 loadOwnIPv4Addresses ($netinfo);
1685 markupIPv4AddrList ($netinfo['addrlist']);
1686 }
1687
1688 function countOwnIPv4Addresses (&$node)
1689 {
1690 $toscan = array();
1691 $node['addrt'] = 0;
1692 $node['mask_bin'] = binMaskFromDec ($node['mask']);
1693 $node['mask_bin_inv'] = binInvMaskFromDec ($node['mask']);
1694 $node['db_first'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] & $node['mask_bin']);
1695 $node['db_last'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] | ($node['mask_bin_inv']));
1696 if (!count ($node['kids']))
1697 {
1698 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1699 $node['addrt'] = binInvMaskFromDec ($node['mask']) + 1;
1700 }
1701 else
1702 foreach ($node['kids'] as $nested)
1703 if (!isset ($nested['id'])) // spare
1704 {
1705 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1706 $node['addrt'] += binInvMaskFromDec ($nested['mask']) + 1;
1707 }
1708 // Don't do anything more, because the displaying function will load the addresses anyway.
1709 return;
1710 $node['addrc'] = count (scanIPv4Space ($toscan));
1711 }
1712
1713 function nodeIsCollapsed ($node)
1714 {
1715 return $node['symbol'] == 'node-collapsed';
1716 }
1717
1718 function loadOwnIPv4Addresses (&$node)
1719 {
1720 $toscan = array();
1721 if (!isset ($node['kids']) or !count ($node['kids']))
1722 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1723 else
1724 foreach ($node['kids'] as $nested)
1725 if (!isset ($nested['id'])) // spare
1726 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1727 $node['addrlist'] = scanIPv4Space ($toscan);
1728 $node['addrc'] = count ($node['addrlist']);
1729 }
1730
1731 function prepareIPv4Tree ($netlist, $expanded_id = 0)
1732 {
1733 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
1734 // so perform necessary pre-processing to make orphans belong to root. This trick
1735 // was earlier performed by getIPv4NetworkList().
1736 $netids = array_keys ($netlist);
1737 foreach ($netids as $cid)
1738 if (!in_array ($netlist[$cid]['parent_id'], $netids))
1739 $netlist[$cid]['parent_id'] = NULL;
1740 $tree = treeFromList ($netlist); // medium call
1741 sortTree ($tree, 'IPv4NetworkCmp');
1742 // complement the tree before markup to make the spare networks have "symbol" set
1743 treeApplyFunc ($tree, 'iptree_fill');
1744 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
1745 // count addresses after the markup to skip computation for hidden tree nodes
1746 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
1747 return $tree;
1748 }
1749
1750 // Check all items of the tree recursively, until the requested target id is
1751 // found. Mark all items leading to this item as "expanded", collapsing all
1752 // the rest, which exceed the given threshold (if the threshold is given).
1753 function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
1754 {
1755 $self = __FUNCTION__;
1756 $ret = FALSE;
1757 foreach (array_keys ($tree) as $key)
1758 {
1759 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
1760 $below = $self ($tree[$key]['kids'], $threshold, $target);
1761 if (!$tree[$key]['kidc']) // terminal node
1762 $tree[$key]['symbol'] = 'spacer';
1763 elseif ($tree[$key]['kidc'] < $threshold)
1764 $tree[$key]['symbol'] = 'node-expanded-static';
1765 elseif ($here or $below)
1766 $tree[$key]['symbol'] = 'node-expanded';
1767 else
1768 $tree[$key]['symbol'] = 'node-collapsed';
1769 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
1770 }
1771 return $ret;
1772 }
1773
1774 // Convert entity name to human-readable value
1775 function formatEntityName ($name) {
1776 switch ($name)
1777 {
1778 case 'ipv4net':
1779 return 'IPv4 Network';
1780 case 'ipv4rspool':
1781 return 'IPv4 RS Pool';
1782 case 'ipv4vs':
1783 return 'IPv4 Virtual Service';
1784 case 'object':
1785 return 'Object';
1786 case 'rack':
1787 return 'Rack';
1788 case 'user':
1789 return 'User';
1790 }
1791 return 'invalid';
1792 }
1793
1794 // Take a MySQL or other generic timestamp and make it prettier
1795 function formatTimestamp ($timestamp) {
1796 return date('n/j/y g:iA', strtotime($timestamp));
1797 }
1798
1799 // Display hrefs for all of a file's parents. If scissors are requested,
1800 // prepend cutting button to each of them.
1801 function serializeFileLinks ($links, $scissors = FALSE)
1802 {
1803 $comma = '';
1804 $ret = '';
1805 foreach ($links as $link_id => $li)
1806 {
1807 switch ($li['entity_type'])
1808 {
1809 case 'ipv4net':
1810 $params = "page=ipv4net&id=";
1811 break;
1812 case 'ipv4rspool':
1813 $params = "page=ipv4rspool&pool_id=";
1814 break;
1815 case 'ipv4vs':
1816 $params = "page=ipv4vs&vs_id=";
1817 break;
1818 case 'object':
1819 $params = "page=object&object_id=";
1820 break;
1821 case 'rack':
1822 $params = "page=rack&rack_id=";
1823 break;
1824 case 'user':
1825 $params = "page=user&user_id=";
1826 break;
1827 }
1828 $ret .= $comma;
1829 if ($scissors)
1830 {
1831 $ret .= "<a href='" . makeHrefProcess(array('op'=>'unlinkFile', 'link_id'=>$link_id)) . "'";
1832 $ret .= getImageHREF ('cut') . '</a> ';
1833 }
1834 $ret .= sprintf("<a href='index.php?%s%s'>%s</a>", $params, $li['entity_id'], $li['name']);
1835 $comma = '<br>';
1836 }
1837 return $ret;
1838 }
1839
1840 // Convert filesize to appropriate unit and make it human-readable
1841 function formatFileSize ($bytes) {
1842 // bytes
1843 if($bytes < 1024) // bytes
1844 return "${bytes} bytes";
1845
1846 // kilobytes
1847 if ($bytes < 1024000)
1848 return sprintf ("%.1fk", round (($bytes / 1024), 1));
1849
1850 // megabytes
1851 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
1852 }
1853
1854 // Reverse of formatFileSize, it converts human-readable value to bytes
1855 function convertToBytes ($value) {
1856 $value = trim($value);
1857 $last = strtolower($value[strlen($value)-1]);
1858 switch ($last)
1859 {
1860 case 'g':
1861 $value *= 1024;
1862 case 'm':
1863 $value *= 1024;
1864 case 'k':
1865 $value *= 1024;
1866 }
1867
1868 return $value;
1869 }
1870
1871 function ip_quad2long ($ip)
1872 {
1873 return sprintf("%u", ip2long($ip));
1874 }
1875
1876 function ip_long2quad ($quad)
1877 {
1878 return long2ip($quad);
1879 }
1880
1881 function makeHref($params = array())
1882 {
1883 $ret = 'index.php?';
1884 $first = true;
1885 foreach($params as $key=>$value)
1886 {
1887 if (!$first)
1888 $ret.='&';
1889 $ret .= urlencode($key).'='.urlencode($value);
1890 $first = false;
1891 }
1892 return $ret;
1893 }
1894
1895 function makeHrefProcess($params = array())
1896 {
1897 global $pageno, $tabno;
1898 $ret = 'process.php?';
1899 $first = true;
1900 if (!isset($params['page']))
1901 $params['page'] = $pageno;
1902 if (!isset($params['tab']))
1903 $params['tab'] = $tabno;
1904 foreach($params as $key=>$value)
1905 {
1906 if (!$first)
1907 $ret.='&';
1908 $ret .= urlencode($key).'='.urlencode($value);
1909 $first = false;
1910 }
1911 return $ret;
1912 }
1913
1914 function makeHrefForHelper ($helper_name, $params = array())
1915 {
1916 $ret = 'popup.php?helper=' . $helper_name;
1917 foreach($params as $key=>$value)
1918 $ret .= '&'.urlencode($key).'='.urlencode($value);
1919 return $ret;
1920 }
1921
1922 // Process the given list of records to build data suitable for printNiftySelect()
1923 // (like it was formerly executed by printSelect()). Screen out vendors according
1924 // to VENDOR_SIEVE, if object type ID is provided. However, the OPTGROUP with already
1925 // selected OPTION is protected from being screened.
1926 function cookOptgroups ($recordList, $object_type_id = 0, $existing_value = 0)
1927 {
1928 $ret = array();
1929 // Always keep "other" OPTGROUP at the SELECT bottom.
1930 $therest = array();
1931 foreach ($recordList as $dict_key => $dict_value)
1932 if (strpos ($dict_value, '%GSKIP%') !== FALSE)
1933 {
1934 $tmp = explode ('%GSKIP%', $dict_value, 2);
1935 $ret[$tmp[0]][$dict_key] = $tmp[1];
1936 }
1937 elseif (strpos ($dict_value, '%GPASS%') !== FALSE)
1938 {
1939 $tmp = explode ('%GPASS%', $dict_value, 2);
1940 $ret[$tmp[0]][$dict_key] = $tmp[1];
1941 }
1942 else
1943 $therest[$dict_key] = $dict_value;
1944 if ($object_type_id != 0)
1945 {
1946 $screenlist = array();
1947 foreach (explode (';', getConfigVar ('VENDOR_SIEVE')) as $sieve)
1948 if (FALSE !== mb_ereg ("^([^@]+)(@${object_type_id})?\$", trim ($sieve), $regs))
1949 $screenlist[] = $regs[1];
1950 foreach (array_keys ($ret) as $vendor)
1951 if (in_array ($vendor, $screenlist))
1952 {
1953 $ok_to_screen = TRUE;
1954 if ($existing_value)
1955 foreach (array_keys ($ret[$vendor]) as $recordkey)
1956 if ($recordkey == $existing_value)
1957 {
1958 $ok_to_screen = FALSE;
1959 break;
1960 }
1961 if ($ok_to_screen)
1962 unset ($ret[$vendor]);
1963 }
1964 }
1965 $ret['other'] = $therest;
1966 return $ret;
1967 }
1968
1969 function dos2unix ($text)
1970 {
1971 return str_replace ("\r\n", "\n", $text);
1972 }
1973
1974 function unix2dos ($text)
1975 {
1976 return str_replace ("\n", "\r\n", $text);
1977 }
1978
1979 function buildPredicateTable ($parsetree)
1980 {
1981 $ret = array();
1982 foreach ($parsetree as $sentence)
1983 if ($sentence['type'] == 'SYNT_DEFINITION')
1984 $ret[$sentence['term']] = $sentence['definition'];
1985 // Now we have predicate table filled in with the latest definitions of each
1986 // particular predicate met. This isn't as chik, as on-the-fly predicate
1987 // overloading during allow/deny scan, but quite sufficient for this task.
1988 return $ret;
1989 }
1990
1991 // Take a list of records and filter against given RackCode expression. Return
1992 // the original list intact, if there was no filter requested, but return an
1993 // empty list, if there was an error.
1994 function filterCellList ($list_in, $expression = array())
1995 {
1996 if ($expression === NULL)
1997 return array();
1998 if (!count ($expression))
1999 return $list_in;
2000 $list_out = array();
2001 foreach ($list_in as $item_key => $item_value)
2002 if (TRUE === judgeCell ($item_value, $expression))
2003 $list_out[$item_key] = $item_value;
2004 return $list_out;
2005 }
2006
2007 // Tell, if the given expression is true for the given entity. Take complete record on input.
2008 function judgeCell ($cell, $expression)
2009 {
2010 global $pTable;
2011 return eval_expression
2012 (
2013 $expression,
2014 array_merge
2015 (
2016 $cell['etags'],
2017 $cell['itags'],
2018 $cell['atags']
2019 ),
2020 $pTable,
2021 TRUE
2022 );
2023 }
2024
2025 // Tell, if a constraint from config option permits given record.
2026 function considerConfiguredConstraint ($cell, $varname)
2027 {
2028 if (!strlen (getConfigVar ($varname)))
2029 return TRUE; // no restriction
2030 global $parseCache;
2031 if (!isset ($parseCache[$varname]))
2032 // getConfigVar() doesn't re-read the value from DB because of its
2033 // own cache, so there is no race condition here between two calls.
2034 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
2035 if ($parseCache[$varname]['result'] != 'ACK')
2036 return FALSE; // constraint set, but cannot be used due to compilation error
2037 return judgeCell ($cell, $parseCache[$varname]['load']);
2038 }
2039
2040 // Return list of records in the given realm, which conform to
2041 // the given RackCode expression. If the realm is unknown or text
2042 // doesn't validate as a RackCode expression, return NULL.
2043 // Otherwise (successful scan) return a list of all matched
2044 // records, even if the list is empty (array() !== NULL). If the
2045 // text is an empty string, return all found records in the given
2046 // realm.
2047 function scanRealmByText ($realm = NULL, $ftext = '')
2048 {
2049 switch ($realm)
2050 {
2051 case 'object':
2052 case 'user':
2053 case 'ipv4net':
2054 case 'file':
2055 case 'ipv4vs':
2056 case 'ipv4rspool':
2057 if (!strlen ($ftext = trim ($ftext)))
2058 $fexpr = array();
2059 else
2060 {
2061 $fparse = spotPayload ($ftext, 'SYNT_EXPR');
2062 if ($fparse['result'] != 'ACK')
2063 return NULL;
2064 $fexpr = $fparse['load'];
2065 }
2066 return filterCellList (listCells ($realm), $fexpr);
2067 default:
2068 throw new InvalidArgException ('$realm', $realm);
2069 }
2070
2071 }
2072
2073 function getIPv4VSOptions ()
2074 {
2075 $ret = array();
2076 foreach (listCells ('ipv4vs') as $vsid => $vsinfo)
2077 $ret[$vsid] = $vsinfo['dname'] . (!strlen ($vsinfo['name']) ? '' : " (${vsinfo['name']})");
2078 return $ret;
2079 }
2080
2081 function getIPv4RSPoolOptions ()
2082 {
2083 $ret = array();
2084 foreach (listCells ('ipv4rspool') as $pool_id => $poolInfo)
2085 $ret[$pool_id] = $poolInfo['name'];
2086 return $ret;
2087 }
2088
2089 // Derive a complete cell structure from the given username regardless
2090 // if it is a local account or not.
2091 function constructUserCell ($username)
2092 {
2093 if (NULL !== ($userid = getUserIDByUsername ($username)))
2094 return spotEntity ('user', $userid);
2095 $ret = array
2096 (
2097 'realm' => 'user',
2098 'user_name' => $username,
2099 'user_realname' => '',
2100 'etags' => array(),
2101 'itags' => array(),
2102 );
2103 $ret['atags'] = generateEntityAutoTags ($ret);
2104 return $ret;
2105 }
2106
2107 // Let's have this debug helper here to enable debugging of process.php w/o interface.php.
2108 function dump ($var)
2109 {
2110 echo '<div align=left><pre>';
2111 print_r ($var);
2112 echo '</pre></div>';
2113 }
2114
2115 function getTagChart ($limit = 0, $realm = 'total', $special_tags = array())
2116 {
2117 global $taglist;
2118 // first build top-N chart...
2119 $toplist = array();
2120 foreach ($taglist as $taginfo)
2121 if (isset ($taginfo['refcnt'][$realm]))
2122 $toplist[$taginfo['id']] = $taginfo['refcnt'][$realm];
2123 arsort ($toplist, SORT_NUMERIC);
2124 $ret = array();
2125 $done = 0;
2126 foreach (array_keys ($toplist) as $tag_id)
2127 {
2128 $ret[$tag_id] = $taglist[$tag_id];
2129 if (++$done == $limit)
2130 break;
2131 }
2132 // ...then make sure, that every item of the special list is shown
2133 // (using the same sort order)
2134 $extra = array();
2135 foreach ($special_tags as $taginfo)
2136 if (!array_key_exists ($taginfo['id'], $ret))
2137 $extra[$taginfo['id']] = $taglist[$taginfo['id']]['refcnt'][$realm];
2138 arsort ($extra, SORT_NUMERIC);
2139 foreach (array_keys ($extra) as $tag_id)
2140 $ret[] = $taglist[$tag_id];
2141 return $ret;
2142 }
2143
2144 function decodeObjectType ($objtype_id, $style = 'r')
2145 {
2146 static $types = array();
2147 if (!count ($types))
2148 $types = array
2149 (
2150 'r' => readChapter (CHAP_OBJTYPE),
2151 'a' => readChapter (CHAP_OBJTYPE, 'a'),
2152 'o' => readChapter (CHAP_OBJTYPE, 'o')
2153 );
2154 return $types[$style][$objtype_id];
2155 }
2156
2157 function isolatedPermission ($p, $t, $cell)
2158 {
2159 // This function is called from both "file" page and a number of other pages,
2160 // which have already fixed security context and authorized the user for it.
2161 // OTOH, it is necessary here to authorize against the current file, which
2162 // means saving the current context and building a new one.
2163 global
2164 $expl_tags,
2165 $impl_tags,
2166 $target_given_tags,
2167 $auto_tags;
2168 // push current context
2169 $orig_expl_tags = $expl_tags;
2170 $orig_impl_tags = $impl_tags;
2171 $orig_target_given_tags = $target_given_tags;
2172 $orig_auto_tags = $auto_tags;
2173 // retarget
2174 fixContext ($cell);
2175 // remember decision
2176 $ret = permitted ($p, $t);
2177 // pop context
2178 $expl_tags = $orig_expl_tags;
2179 $impl_tags = $orig_impl_tags;
2180 $target_given_tags = $orig_target_given_tags;
2181 $auto_tags = $orig_auto_tags;
2182 return $ret;
2183 }
2184
2185 function getPortListPrefs()
2186 {
2187 $ret = array();
2188 if (0 >= ($ret['iif_pick'] = getConfigVar ('DEFAULT_PORT_IIF_ID')))
2189 $ret['iif_pick'] = 1;
2190 $ret['oif_picks'] = array();
2191 foreach (explode (';', getConfigVar ('DEFAULT_PORT_OIF_IDS')) as $tmp)
2192 {
2193 $tmp = explode ('=', trim ($tmp));
2194 if (count ($tmp) == 2 and $tmp[0] > 0 and $tmp[1] > 0)
2195 $ret['oif_picks'][$tmp[0]] = $tmp[1];
2196 }
2197 // enforce default value
2198 if (!array_key_exists (1, $ret['oif_picks']))
2199 $ret['oif_picks'][1] = 24;
2200 $ret['selected'] = $ret['iif_pick'] . '-' . $ret['oif_picks'][$ret['iif_pick']];
2201 return $ret;
2202 }
2203
2204 // Return data for printNiftySelect() with port type options. All OIF options
2205 // for the default IIF will be shown, but only the default OIFs will be present
2206 // for each other IIFs. IIFs, for which there is no default OIF, will not
2207 // be listed.
2208 // This SELECT will be used for the "add new port" form.
2209 function getNewPortTypeOptions()
2210 {
2211 $ret = array();
2212 $prefs = getPortListPrefs();
2213 foreach (getPortInterfaceCompat() as $row)
2214 {
2215 if ($row['iif_id'] == $prefs['iif_pick'])
2216 $optgroup = $row['iif_name'];
2217 elseif (array_key_exists ($row['iif_id'], $prefs['oif_picks']) and $prefs['oif_picks'][$row['iif_id']] == $row['oif_id'])
2218 $optgroup = 'other';
2219 else
2220 continue;
2221 if (!array_key_exists ($optgroup, $ret))
2222 $ret[$optgroup] = array();
2223 $ret[$optgroup][$row['iif_id'] . '-' . $row['oif_id']] = $row['oif_name'];
2224 }
2225 return $ret;
2226 }
2227
2228 function getVLANDomain ($vdid)
2229 {
2230 $ret = getVLANDomainInfo ($vdid);
2231 $ret['vlanlist'] = array();
2232 foreach (getDomainVLANs ($vdid) as $vlan_id => $vlan_descr)
2233 $ret['vlanlist'][$vlan_id] = $vlan_descr;
2234 $ret['switchlist'] = getVLANDomainSwitches ($vdid);
2235 return $ret;
2236 }
2237
2238 // Return a serialized version of VLAN configuration for a port.
2239 // If a native VLAN is defined, print it first. All other VLANs
2240 // are tagged and are listed after a plus sign. When no configuration
2241 // is set for a port, return "default" string.
2242 function serializeVLANPack ($native_vid = 0, $allowed_vids = array())
2243 {
2244 $tagged = array();
2245 foreach ($allowed_vids as $vlan_id)
2246 if ($vlan_id != $native_vid)
2247 $tagged[] = $vlan_id;
2248 sort ($tagged);
2249 $ret = $native_vid ? $native_vid : '';
2250 $tagged_bits = array();
2251 $id_from = $id_to = 0;
2252 foreach ($tagged as $next_id)
2253 {
2254 if ($id_to)
2255 {
2256 if ($next_id == $id_to + 1) // merge
2257 {
2258 $id_to = $next_id;
2259 continue;
2260 }
2261 // flush
2262 $tagged_bits[] = $id_from == $id_to ? $id_from : "${id_from}-${id_to}";
2263 }
2264 $id_from = $id_to = $next_id; // start next pair
2265 }
2266 // pull last pair
2267 if ($id_to)
2268 $tagged_bits[] = $id_from == $id_to ? $id_from : "${id_from}-${id_to}";
2269 if (count ($tagged))
2270 $ret .= '+' . implode (',', $tagged_bits);
2271 return strlen ($ret) ? $ret : 'default';
2272 }
2273
2274 // Decode VLAN compound key (which is a string formatted DOMAINID-VLANID) and
2275 // return the numbers as an array of two.
2276 function decodeVLANCK ($string)
2277 {
2278 $matches = array();
2279 if (1 != preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $string, $matches))
2280 throw new InvalidArgException ('VLAN compound key', $string);
2281 return array ($matches[1], $matches[2]);
2282 }
2283
2284 // Return VLAN name formatted for HTML output (note, that input
2285 // argument comes from database unescaped).
2286 function formatVLANName ($vlaninfo)
2287 {
2288 $ret = '<tt>VLAN' . $vlaninfo['vlan_id'] . '</tt>';
2289 if (strlen ($vlaninfo['vlan_descr']))
2290 $ret .= ' <i>(' . niftyString ($vlaninfo['vlan_descr']) . ')</i>';
2291 return $ret;
2292 }
2293
2294 // Read given running-config and return a list of work items in a format
2295 // similar to the one, which setSwitchVLANConfig() understands.
2296 function ios12ReadVLANConfig ($input)
2297 {
2298 $ret = array
2299 (
2300 'vlanlist' => array(),
2301 'portdata' => array(),
2302 );
2303 $procfunc = 'ios12ScanTopLevel';
2304 foreach (explode ("\n", $input) as $line)
2305 $procfunc = $procfunc ($ret, $line);
2306 return $ret;
2307 }
2308
2309 function ios12ScanTopLevel (&$work, $line)
2310 {
2311 $matches = array();
2312 switch (TRUE)
2313 {
2314 case (preg_match ('@^interface ((Ethernet|FastEthernet|GigabitEthernet|TenGigabitEthernet)[[:digit:]]+(/[[:digit:]]+)*)$@', $line, $matches)):
2315 // map interface name
2316 $matches[1] = preg_replace ('@^Ethernet(.+)$@', 'et\\1', $matches[1]);
2317 $matches[1] = preg_replace ('@^FastEthernet(.+)$@', 'fa\\1', $matches[1]);
2318 $matches[1] = preg_replace ('@^GigabitEthernet(.+)$@', 'gi\\1', $matches[1]);
2319 $matches[1] = preg_replace ('@^TenGigabitEthernet(.+)$@', 'te\\1', $matches[1]);
2320 $work['current'] = array ('port_name' => $matches[1]);
2321 return 'ios12PickSwitchportCommand'; // switch to interface block reading
2322 case (preg_match ('/^VLAN Name Status Ports$/', $line, $matches)):
2323 return 'ios12PickVLANCommand';
2324 default:
2325 return __FUNCTION__; // continue scan
2326 }
2327 }
2328
2329 function ios12PickSwitchportCommand (&$work, $line)
2330 {
2331 if ($line[0] != ' ') // end of interface section
2332 {
2333 $boiled = array ('port_name' => $work['current']['port_name']);
2334 // fill in defaults
2335 if (!array_key_exists ('mode', $work['current']))
2336 $work['current']['mode'] = 'access';
2337 if (!array_key_exists ('access vlan', $work['current']))
2338 $work['current']['access vlan'] = 1;
2339 if (!array_key_exists ('trunk native vlan', $work['current']))
2340 $work['current']['trunk native vlan'] = 1;
2341 if (!array_key_exists ('trunk allowed vlan', $work['current']))
2342 $work['current']['trunk allowed vlan'] = range (VLAN_MIN_ID, VLAN_MAX_ID);
2343 // save work, if it makes sense
2344 switch ($work['current']['mode'])
2345 {
2346 case 'access':
2347 $work['portdata'][$work['current']['port_name']] = array
2348 (
2349 'allowed' => array ($work['current']['access vlan']),
2350 'native' => $work['current']['access vlan'],
2351 );
2352 break;
2353 case 'trunk':
2354 // Having configured VLAN as "native" doesn't mean anything
2355 // as long as it's not listed on the "allowed" line.
2356 $effective_native = in_array
2357 (
2358 $work['current']['trunk native vlan'],
2359 $work['current']['trunk allowed vlan']
2360 ) ? $work['current']['trunk native vlan'] : 0;
2361 $work['portdata'][$work['current']['port_name']] = array
2362 (
2363 'allowed' => $work['current']['trunk allowed vlan'],
2364 'native' => $effective_native,
2365 );
2366 break;
2367 default:
2368 // dot1q-tunnel, dynamic, private-vlan --- skip these
2369 }
2370 unset ($work['current']);
2371 return 'ios12ScanTopLevel';
2372 }
2373 // not yet
2374 $matches = array();
2375 switch (TRUE)
2376 {
2377 case (preg_match ('@^ switchport mode (.+)$@', $line, $matches)):
2378 $work['current']['mode'] = $matches[1];
2379 break;
2380 case (preg_match ('@^ switchport access vlan (.+)$@', $line, $matches)):
2381 $work['current']['access vlan'] = $matches[1];
2382 break;
2383 case (preg_match ('@^ switchport trunk native vlan (.+)$@', $line, $matches)):
2384 $work['current']['trunk native vlan'] = $matches[1];
2385 break;
2386 case (preg_match ('@^ switchport trunk allowed vlan add (.+)$@', $line, $matches)):
2387 $work['current']['trunk allowed vlan'] = array_merge
2388 (
2389 $work['current']['trunk allowed vlan'],
2390 iosParseVLANString ($matches[1])
2391 );
2392 break;
2393 case (preg_match ('@^ switchport trunk allowed vlan (.+)$@', $line, $matches)):
2394 $work['current']['trunk allowed vlan'] = iosParseVLANString ($matches[1]);
2395 break;
2396 default: // suppress warning on irrelevant config clause
2397 }
2398 return __FUNCTION__;
2399 }
2400
2401 function ios12PickVLANCommand (&$work, $line)
2402 {
2403 $matches = array();
2404 switch (TRUE)
2405 {
2406 case ($line == '---- -------------------------------- --------- -------------------------------'):
2407 // ignore the rest of VLAN table header;
2408 break;
2409 case (preg_match ('@! END OF VLAN LIST$@', $line)):
2410 return 'ios12ScanTopLevel';
2411 case (preg_match ('@^([[:digit:]]+) {1,4}.{32} active @', $line, $matches)):
2412 if (!array_key_exists ($matches[1], $work['vlanlist']))
2413 $work['vlanlist'][] = $matches[1];
2414 break;
2415 default:
2416 }
2417 return __FUNCTION__;
2418 }
2419
2420 function iosParseVLANString ($string)
2421 {
2422 $ret = array();
2423 foreach (explode (',', $string) as $item)
2424 {
2425 $matches = array();
2426 if (preg_match ('/^([[:digit:]]+)$/', $item, $matches))
2427 $ret[] = $matches[1];
2428 elseif (preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $item, $matches))
2429 $ret = array_merge ($ret, range ($matches[1], $matches[2]));
2430 }
2431 return $ret;
2432 }
2433
2434 // Another finite automata to read a dialect of Foundry configuration.
2435 function fdry5ReadVLANConfig ($input)
2436 {
2437 $ret = array
2438 (
2439 'vlanlist' => array(),
2440 'portdata' => array(),
2441 );
2442 $procfunc = 'fdry5ScanTopLevel';
2443 foreach (explode ("\n", $input) as $line)
2444 $procfunc = $procfunc ($ret, $line);
2445 return $ret;
2446 }
2447
2448 function fdry5ScanTopLevel (&$work, $line)
2449 {
2450 $matches = array();
2451 switch (TRUE)
2452 {
2453 case (preg_match ('@^vlan ([[:digit:]]+)( name .+)? (by port)$@', $line, $matches)):
2454 if (!array_key_exists ($matches[1], $work['vlanlist']))
2455 $work['vlanlist'][] = $matches[1];
2456 $work['current'] = array ('vlan_id' => $matches[1]);
2457 return 'fdry5PickVLANSubcommand';
2458 case (preg_match ('@^interface ethernet ([[:digit:]]+/[[:digit:]]+/[[:digit:]]+)$@', $line, $matches)):
2459 $work['current'] = array ('port_name' => 'e' . $matches[1]);
2460 return 'fdry5PickInterfaceSubcommand';
2461 default:
2462 return __FUNCTION__;
2463 }
2464 }
2465
2466 function fdry5PickVLANSubcommand (&$work, $line)
2467 {
2468 if ($line[0] != ' ') // end of VLAN section
2469 {
2470 unset ($work['current']);
2471 return 'fdry5ScanTopLevel';
2472 }
2473 // not yet
2474 $matches = array();
2475 switch (TRUE)
2476 {
2477 case (preg_match ('@^ tagged (.+)$@', $line, $matches)):
2478 // add current VLAN to 'allowed' list of each mentioned port
2479 foreach (fdry5ParsePortString ($matches[1]) as $port_name)
2480 if (array_key_exists ($port_name, $work['portdata']))
2481 $work['portdata'][$port_name]['allowed'][] = $work['current']['vlan_id'];
2482 else
2483 $work['portdata'][$port_name] = array
2484 (
2485 'allowed' => array ($work['current']['vlan_id']),
2486 'native' => 0, // can be updated later
2487 );
2488 break;
2489 case (preg_match ('@^ untagged (.+)$@', $line, $matches)):
2490 // replace 'native' column of each mentioned port with current VLAN ID
2491 foreach (fdry5ParsePortString ($matches[1]) as $port_name)
2492 if (array_key_exists ($port_name, $work['portdata']))
2493 {
2494 $work['portdata'][$port_name]['native'] = $work['current']['vlan_id'];
2495 $work['portdata'][$port_name]['allowed'][] = $work['current']['vlan_id'];
2496 }
2497 else
2498 $work['portdata'][$port_name] = array
2499 (
2500 'allowed' => array ($work['current']['vlan_id']),
2501 'native' => $work['current']['vlan_id'],
2502 );
2503 break;
2504 default: // nom-nom
2505 }
2506 return __FUNCTION__;
2507 }
2508
2509 function fdry5PickInterfaceSubcommand (&$work, $line)
2510 {
2511 if ($line[0] != ' ') // end of interface section
2512 {
2513 if (array_key_exists ('dual-mode', $work['current']))
2514 {
2515 if (array_key_exists ($work['current']['port_name'], $work['portdata']))
2516 // update existing record
2517 $work['portdata'][$work['current']['port_name']]['native'] = $work['current']['dual-mode'];
2518 else
2519 // add new
2520 $work['portdata'][$work['current']['port_name']] = array
2521 (
2522 'allowed' => array ($work['current']['dual-mode']),
2523 'native' => $work['current']['dual-mode'],
2524 );
2525 }
2526 unset ($work['current']);
2527 return 'fdry5ScanTopLevel';
2528 }
2529 $matches = array();
2530 switch (TRUE)
2531 {
2532 case (preg_match ('@^ dual-mode( +[[:digit:]]+ *)?$@', $line, $matches)):
2533 // default VLAN ID for dual-mode command is 1
2534 $work['current']['dual-mode'] = strlen (trim ($matches[1])) ? trim ($matches[1]) : 1;
2535 break;
2536 default: // nom-nom
2537 }
2538 return __FUNCTION__;
2539 }
2540
2541 function fdry5ParsePortString ($string)
2542 {
2543 $ret = array();
2544 $tokens = explode (' ', trim ($string));
2545 while (count ($tokens))
2546 {
2547 $letters = array_shift ($tokens); // "ethe", "to"
2548 $numbers = array_shift ($tokens); // "x", "x/x", "x/x/x"
2549 switch ($letters)
2550 {
2551 case 'ethe':
2552 if ($prev_numbers != NULL)
2553 $ret[] = 'e' . $prev_numbers;
2554 $prev_numbers = $numbers;
2555 break;
2556 case 'to':
2557 $ret = array_merge ($ret, fdry5GenPortRange ($prev_numbers, $numbers));
2558 $prev_numbers = NULL; // no action on next token
2559 break;
2560 default: // ???
2561 return array();
2562 }
2563 }
2564 // flush delayed item
2565 if ($prev_numbers != NULL)
2566 $ret[] = 'e' . $prev_numbers;
2567 return $ret;
2568 }
2569
2570 // Take two indices in form "x", "x/x" or "x/x/x" and return the range of
2571 // ports spanning from the first to the last. The switch software makes it
2572 // easier to perform, because "ethe x/x/x to y/y/y" ranges never cross
2573 // unit/slot boundary (every index except the last remains constant).
2574 function fdry5GenPortRange ($from, $to)
2575 {
2576 $matches = array();
2577 if (1 !== preg_match ('@^([[:digit:]]+/)?([[:digit:]]+/)?([[:digit:]]+)$@', $from, $matches))
2578 return array();
2579 $prefix = 'e' . $matches[1] . $matches[2];
2580 $from_idx = $matches[3];
2581 if (1 !== preg_match ('@^([[:digit:]]+/)?([[:digit:]]+/)?([[:digit:]]+)$@', $to, $matches))
2582 return array();
2583 $to_idx = $matches[3];
2584 for ($i = $from_idx; $i <= $to_idx; $i++)
2585 $ret[] = $prefix . $i;
2586 return $ret;
2587 }
2588
2589 // Scan given work accumulator array and return the key, which
2590 // addresses the port with requested name (or NULL if there is none such).
2591 // Note that 0 and NULL mean completely different things and thus
2592 // require strict checking (=== and !===).
2593 function scanArrayForItem ($table, $scan_column, $scan_value)
2594 {
2595 foreach ($table as $key => $row)
2596 if ($row[$scan_column] == $scan_value)
2597 return $key;
2598 return NULL;
2599 }
2600
2601 function computeSwitchPushRequest ($object_id, $which_ports)
2602 {
2603 $vswitch = getVLANSwitchInfo ($object_id);
2604 $vdomain = getVLANDomain ($vswitch['domain_id']);
2605 $device_config = getDevice8021QConfig ($object_id);
2606 // only ignore VLANs, which exist and are explicitly shown as "alien"
2607 $old_managed_vlans = array();
2608 foreach ($device_config['vlanlist'] as $vlan_id)
2609 if
2610 (
2611 !array_key_exists ($vlan_id, $vdomain['vlanlist']) or
2612 $vdomain['vlanlist'][$vlan_id]['vlan_type'] != 'alien'
2613 )
2614 $old_managed_vlans[] = $vlan_id;
2615 $db_config = getDesired8021QConfig ($object_id);
2616 $ports_to_do = array();
2617 foreach ($which_ports as $port_name)
2618 if (array_key_exists ($port_name, $db_config))
2619 $ports_to_do[$port_name] = array
2620 (
2621 'old_allowed' => array_key_exists ($port_name, $device_config['portdata']) ?
2622 $device_config['portdata'][$port_name]['allowed'] :
2623 array(),
2624 'old_native' => array_key_exists ($port_name, $device_config['portdata']) ?
2625 $device_config['portdata'][$port_name]['native'] :
2626 0,
2627 'new_allowed' => $db_config[$port_name]['allowed'],
2628 'new_native' => $db_config[$port_name]['native'],
2629 );
2630 // New VLAN table is a union of:
2631 // 1. all compulsory VLANs
2632 // 2. all "current" allowed VLANs of those ports, which are left
2633 // intact (including VLANs, which don't exist in current domain)
2634 // 3. all "new" allowed VLANs of those ports, which we do "push" now
2635 // Like for old_managed_vlans, a VLANs is never listed, only if it
2636 // exists and belongs to "alien" type.
2637 $new_managed_vlans = array();
2638 foreach ($vdomain['vlanlist'] as $vlan_id => $vlan)
2639 if ($vlan['vlan_type'] == 'compulsory')
2640 $new_managed_vlans[] = $vlan_id;
2641 foreach ($device_config['portdata'] as $port_name => $port)
2642 if (!in_array ($port_name, $ports_to_do))
2643 foreach ($port['allowed'] as $vlan_id)
2644 if
2645 (
2646 (!array_key_exists ($vlan_id, $vdomain['vlanlist']) or
2647 $vdomain['vlanlist'][$vlan_id]['vlan_type'] != 'alien') and
2648 !in_array ($vlan_id, $new_managed_vlans)
2649 )
2650 $new_managed_vlans[] = $vlan_id;
2651 foreach ($ports_to_do as $port)
2652 foreach ($port['new_allowed'] as $vlan_id)
2653 if
2654 (
2655 $vdomain['vlanlist'][$vlan_id]['vlan_type'] == 'ondemand' and
2656 !in_array ($vlan_id, $new_managed_vlans)
2657 )
2658 $new_managed_vlans[] = $vlan_id;
2659 $ret = array();
2660 // Before removing old VLANs as such it is necessary to unassign
2661 // ports from them (to remove VLANs from ports' list of "allowed"
2662 // VLANs. This change in turn requires, that "native" VLAN isn't
2663 // set to the one being removed.
2664 foreach ($ports_to_do as $port_name => $port)
2665 {
2666 // "old" native is set and differs from the "new" native
2667 if ($port['old_native'] and $port['old_native'] != $port['new_native'])
2668 $ret[] = array
2669 (
2670 'opcode' => 'unset native',
2671 'arg1' => $port_name,
2672 'arg2' => $port['old_native'],
2673 );
2674 foreach (array_diff ($port['old_allowed'], $port['new_allowed']) as $vlan_id)
2675 $ret[] = array
2676 (
2677 'opcode' => 'rem allowed',
2678 'arg1' => $port_name,
2679 'arg2' => $vlan_id,
2680 );
2681 }
2682 // Now it is safe to unconfigure VLANs, which still exist on device,
2683 // but are not present on the "new" list.
2684 foreach (array_diff ($old_managed_vlans, $new_managed_vlans) as $vlan_id)
2685 $ret[] = array
2686 (
2687 'opcode' => 'destroy VLAN',
2688 'arg1' => $vlan_id,
2689 );
2690 // Configure VLANs, which must be present on the device, but are not yet.
2691 foreach (array_diff ($new_managed_vlans, $old_managed_vlans) as $vlan_id)
2692 $ret[] = array
2693 (
2694 'opcode' => 'create VLAN',
2695 'arg1' => $vlan_id,
2696 );
2697 // Now, when all new VLANs are created (queued), it is safe to assign (queue)
2698 // ports to the new VLANs.
2699 foreach ($ports_to_do as $port_name => $port)
2700 {
2701 // For each allowed VLAN, which is present on the "new" list and missing from
2702 // the "old" one, queue a command to assign current port to that VLAN.
2703 foreach (array_diff ($port['new_allowed'], $port['old_allowed']) as $vlan_id)
2704 $ret[] = array
2705 (
2706 'opcode' => 'add allowed',
2707 'arg1' => $port_name,
2708 'arg2' => $vlan_id,
2709 );
2710 // One of the "allowed" VLANs for this port may probably be "native".
2711 // "new native" is set and differs from "old native"
2712 if ($port['new_native'] and $port['new_native'] != $port['old_native'])
2713 $ret[] = array
2714 (
2715 'opcode' => 'set native',
2716 'arg1' => $port_name,
2717 'arg2' => $port['new_native'],
2718 );
2719
2720 }
2721 return $ret;
2722 }
2723
2724 // Get a list of VLAN management pseudo-commands and return a text
2725 // of real vendor-specific commands, which implement the work.
2726 function ios12TranslatePushQueue ($queue)
2727 {
2728 $ret = "conf t\n";
2729 foreach ($queue as $cmd)
2730 switch ($cmd['opcode'])
2731 {
2732 case 'create VLAN':
2733 $ret .= "vlan ${cmd['arg1']}\nexit\n";
2734 break;
2735 case 'destroy VLAN':
2736 $ret .= "no vlan ${cmd['arg1']}\n";
2737 break;
2738 case 'add allowed':
2739 $ret .= "interface ${cmd['arg1']}\nswitchport trunk allowed vlan add ${cmd['arg2']}\nexit\n";
2740 break;
2741 case 'rem allowed':
2742 $ret .= "interface ${cmd['arg1']}\nswitchport trunk allowed vlan remove ${cmd['arg2']}\nexit\n";
2743 break;
2744 case 'set native':
2745 $ret .= "interface ${cmd['arg1']}\nswitchport trunk native vlan ${cmd['arg2']}\nexit\n";
2746 break;
2747 case 'unset native':
2748 $ret .= "interface ${cmd['arg1']}\nno switchport trunk native vlan ${cmd['arg2']}\nexit\n";
2749 break;
2750 }
2751 $ret .= "end\n";
2752 return $ret;
2753 }
2754
2755 function fdry5TranslatePushQueue ($queue)
2756 {
2757 $ret = "conf t\n";
2758 foreach ($queue as $cmd)
2759 switch ($cmd['opcode'])
2760 {
2761 case 'create VLAN':
2762 $ret .= "vlan ${cmd['arg1']}\nexit\n";
2763 break;
2764 case 'destroy VLAN':
2765 $ret .= "no vlan ${cmd['arg1']}\n";
2766 break;
2767 case 'add allowed':
2768 $ret .= "vlan ${cmd['arg2']}\ntagged ${cmd['arg1']}\nexit\n";
2769 break;
2770 case 'rem allowed':
2771 $ret .= "vlan ${cmd['arg2']}\nno tagged ${cmd['arg1']}\nexit\n";
2772 break;
2773 case 'set native':
2774 $ret .= "interface ${cmd['arg1']}\ndual-mode ${cmd['arg2']}\nexit\n";
2775 break;
2776 case 'unset native':
2777 $ret .= "interface ${cmd['arg1']}\nno dual-mode ${cmd['arg2']}\nexit\n";
2778 break;
2779 }
2780 $ret .= "end\n";
2781 return $ret;
2782 }
2783
2784 ?>