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