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