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