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