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