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