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