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