6aa9b308cc4175a283614d84fe36e959b9d1368c
[racktables] / 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 and returns text suitable for either A
871 // (rendering <A HREF>) or O (for <OPTION>).
872 function parseWikiLink ($line, $which)
873 {
874 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
875 {
876 // always strip the marker for A-data, but let cookOptgroup()
877 // do this later (otherwise it can't sort groups out)
878 if ($which == 'a')
879 return preg_replace ('/^.+%GSKIP%/', '', preg_replace ('/^(.+)%GPASS%/', '\\1 ', $line));
880 else
881 return $line;
882 }
883 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
884 $s = explode ('|', $line);
885 $o_value = trim ($s[0]);
886 if ($which == 'o')
887 return $o_value;
888 $o_value = preg_replace ('/^.+%GSKIP%/', '', preg_replace ('/^(.+)%GPASS%/', '\\1 ', $o_value));
889 $a_value = trim ($s[1]);
890 return $o_value . " <a class='img-link' href='${a_value}'>" . getImageHREF ('html', 'vendor`s info page') . "</a>";
891 }
892
893 // FIXME: should this be saved as "P-data"?
894 function execGMarker ($line)
895 {
896 return preg_replace ('/^.+%GSKIP%/', '', preg_replace ('/^(.+)%GPASS%/', '\\1 ', $line));
897 }
898
899 // rackspace usage for a single rack
900 // (T + W + U) / (height * 3 - A)
901 function getRSUforRack ($data)
902 {
903 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
904 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
905 for ($locidx = 0; $locidx < 3; $locidx++)
906 $counter[$data[$unit_no][$locidx]['state']]++;
907 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
908 }
909
910 // Same for row.
911 function getRSUforRackRow ($rowData)
912 {
913 if (!count ($rowData))
914 return 0;
915 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
916 $total_height = 0;
917 foreach (array_keys ($rowData) as $rack_id)
918 {
919 $data = spotEntity ('rack', $rack_id);
920 amplifyCell ($data);
921 $total_height += $data['height'];
922 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
923 for ($locidx = 0; $locidx < 3; $locidx++)
924 $counter[$data[$unit_no][$locidx]['state']]++;
925 }
926 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
927 }
928
929 // Make sure the string is always wrapped with LF characters
930 function lf_wrap ($str)
931 {
932 $ret = trim ($str, "\r\n");
933 if (strlen ($ret))
934 $ret .= "\n";
935 return $ret;
936 }
937
938 // Adopted from Mantis BTS code.
939 function string_insert_hrefs ($s)
940 {
941 if (getConfigVar ('DETECT_URLS') != 'yes')
942 return $s;
943 # Find any URL in a string and replace it by a clickable link
944 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
945 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
946 $s);
947 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
948 '<a href="mailto:\0">\0</a>',
949 $s);
950 return $s;
951 }
952
953 // Idem.
954 function email_regex_simple ()
955 {
956 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
957 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
958 }
959
960 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
961 // for the requested object_type_id.
962 function getAutoPorts ($type_id)
963 {
964 $ret = array();
965 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
966 foreach ($typemap as $equation)
967 {
968 $tmp = explode ('=', $equation);
969 if (count ($tmp) != 2)
970 continue;
971 $objtype_id = $tmp[0];
972 if ($objtype_id != $type_id)
973 continue;
974 $portlist = $tmp[1];
975 foreach (explode ('+', $portlist) as $product)
976 {
977 $tmp = explode ('*', $product);
978 if (count ($tmp) != 3)
979 continue;
980 $nports = $tmp[0];
981 $port_type = $tmp[1];
982 $format = $tmp[2];
983 for ($i = 0; $i < $nports; $i++)
984 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
985 }
986 }
987 return $ret;
988 }
989
990 // Use pre-served trace to traverse the tree, then place given node where it belongs.
991 function pokeNode (&$tree, $trace, $key, $value, $threshold = 0)
992 {
993 // This function needs the trace to be followed FIFO-way. The fastest
994 // way to do so is to use array_push() for putting values into the
995 // list and array_shift() for getting them out. This exposed up to 11%
996 // performance gain compared to other patterns of array_push/array_unshift/
997 // array_reverse/array_pop/array_shift conjunction.
998 $myid = array_shift ($trace);
999 if (!count ($trace)) // reached the target
1000 {
1001 if (!$threshold or ($threshold and $tree[$myid]['kidc'] + 1 < $threshold))
1002 $tree[$myid]['kids'][$key] = $value;
1003 // Reset accumulated records once, when the limit is reached, not each time
1004 // after that.
1005 if (++$tree[$myid]['kidc'] == $threshold)
1006 $tree[$myid]['kids'] = array();
1007 }
1008 else // not yet
1009 {
1010 $self = __FUNCTION__;
1011 $self ($tree[$myid]['kids'], $trace, $key, $value, $threshold);
1012 }
1013 }
1014
1015 // Likewise traverse the tree with the trace and return the final node.
1016 function peekNode ($tree, $trace, $target_id)
1017 {
1018 $self = __FUNCTION__;
1019 if (NULL === ($next = array_shift ($trace))) // warm
1020 {
1021 foreach ($tree as $node)
1022 if (array_key_exists ('id', $node) and $node['id'] == $target_id) // hot
1023 return $node;
1024 }
1025 else // cold
1026 {
1027 foreach ($tree as $node)
1028 if (array_key_exists ('id', $node) and $node['id'] == $next) // warmer
1029 return $self ($node['kids'], $trace, $target_id);
1030 }
1031 throw new RackTablesError ('inconsistent tree data', RackTablesError::INTERNAL);
1032 }
1033
1034 // Build a tree from the item list and return it. Input and output data is
1035 // indexed by item id (nested items in output are recursively stored in 'kids'
1036 // key, which is in turn indexed by id. Functions, which are ready to handle
1037 // tree collapsion/expansion themselves, may request non-zero threshold value
1038 // for smaller resulting tree.
1039 function treeFromList (&$orig_nodelist, $threshold = 0, $return_main_payload = TRUE)
1040 {
1041 $tree = array();
1042 $nodelist = $orig_nodelist;
1043 // Array equivalent of traceEntity() function.
1044 $trace = array();
1045 // set kidc and kids only once
1046 foreach (array_keys ($nodelist) as $nodeid)
1047 {
1048 $nodelist[$nodeid]['kidc'] = 0;
1049 $nodelist[$nodeid]['kids'] = array();
1050 }
1051 do
1052 {
1053 $nextpass = FALSE;
1054 foreach (array_keys ($nodelist) as $nodeid)
1055 {
1056 // When adding a node to the working tree, book another
1057 // iteration, because the new item could make a way for
1058 // others onto the tree. Also remove any item added from
1059 // the input list, so iteration base shrinks.
1060 // First check if we can assign directly.
1061 if ($nodelist[$nodeid]['parent_id'] == NULL)
1062 {
1063 $tree[$nodeid] = $nodelist[$nodeid];
1064 $trace[$nodeid] = array(); // Trace to root node is empty
1065 unset ($nodelist[$nodeid]);
1066 $nextpass = TRUE;
1067 }
1068 // Now look if it fits somewhere on already built tree.
1069 elseif (isset ($trace[$nodelist[$nodeid]['parent_id']]))
1070 {
1071 // Trace to a node is a trace to its parent plus parent id.
1072 $trace[$nodeid] = $trace[$nodelist[$nodeid]['parent_id']];
1073 $trace[$nodeid][] = $nodelist[$nodeid]['parent_id'];
1074 pokeNode ($tree, $trace[$nodeid], $nodeid, $nodelist[$nodeid], $threshold);
1075 // path to any other node is made of all parent nodes plus the added node itself
1076 unset ($nodelist[$nodeid]);
1077 $nextpass = TRUE;
1078 }
1079 }
1080 }
1081 while ($nextpass);
1082 if (!$return_main_payload)
1083 return $nodelist;
1084 // update each input node with its backtrace route
1085 foreach ($trace as $nodeid => $route)
1086 $orig_nodelist[$nodeid]['trace'] = $route;
1087 return $tree;
1088 }
1089
1090 // Build a tree from the tag list and return everything _except_ the tree.
1091 // IOW, return taginfo items, which have parent_id set and pointing outside
1092 // of the "normal" tree, which originates from the root.
1093 function getOrphanedTags ()
1094 {
1095 global $taglist;
1096 return treeFromList ($taglist, 0, FALSE);
1097 }
1098
1099 function serializeTags ($chain, $baseurl = '')
1100 {
1101 $comma = '';
1102 $ret = '';
1103 foreach ($chain as $taginfo)
1104 {
1105 $ret .= $comma .
1106 ($baseurl == '' ? '' : "<a href='${baseurl}cft[]=${taginfo['id']}'>") .
1107 $taginfo['tag'] .
1108 ($baseurl == '' ? '' : '</a>');
1109 $comma = ', ';
1110 }
1111 return $ret;
1112 }
1113
1114 // Return the list of missing implicit tags.
1115 function getImplicitTags ($oldtags)
1116 {
1117 global $taglist;
1118 $tmp = array();
1119 foreach ($oldtags as $taginfo)
1120 $tmp = array_merge ($tmp, $taglist[$taginfo['id']]['trace']);
1121 // don't call array_unique here, it is in the function we will call now
1122 return buildTagChainFromIds ($tmp);
1123 }
1124
1125 // Minimize the chain: exclude all implicit tags and return the result.
1126 // This function makes use of an external cache with a miss/hit ratio
1127 // about 3/7 (ticket:255).
1128 function getExplicitTagsOnly ($chain)
1129 {
1130 global $taglist, $tagRelCache;
1131 $ret = array();
1132 foreach (array_keys ($chain) as $keyA) // check each A
1133 {
1134 $tagidA = $chain[$keyA]['id'];
1135 // do not include A in result, if A is seen on the trace of any B!=A
1136 foreach (array_keys ($chain) as $keyB)
1137 {
1138 $tagidB = $chain[$keyB]['id'];
1139 if ($tagidA == $tagidB)
1140 continue;
1141 if (!isset ($tagRelCache[$tagidA][$tagidB]))
1142 $tagRelCache[$tagidA][$tagidB] = in_array ($tagidA, $taglist[$tagidB]['trace']);
1143 if ($tagRelCache[$tagidA][$tagidB] === TRUE) // A is ancestor of B
1144 continue 2; // skip this A
1145 }
1146 $ret[] = $chain[$keyA];
1147 }
1148 return $ret;
1149 }
1150
1151 // Universal autotags generator, a complementing function for loadEntityTags().
1152 // Bypass key isn't strictly typed, but interpreted depending on the realm.
1153 function generateEntityAutoTags ($cell)
1154 {
1155 $ret = array();
1156 if (! array_key_exists ('realm', $cell))
1157 throw new InvalidArgException ('cell', '(array)', 'malformed structure');
1158 switch ($cell['realm'])
1159 {
1160 case 'rack':
1161 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
1162 $ret[] = array ('tag' => '$any_rack');
1163 break;
1164 case 'object':
1165 $ret[] = array ('tag' => '$id_' . $cell['id']);
1166 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
1167 $ret[] = array ('tag' => '$any_object');
1168 if (validTagName ('$cn_' . $cell['name'], TRUE))
1169 $ret[] = array ('tag' => '$cn_' . $cell['name']);
1170 if (!strlen ($cell['rack_id']))
1171 $ret[] = array ('tag' => '$unmounted');
1172 if (!$cell['nports'])
1173 $ret[] = array ('tag' => '$portless');
1174 if ($cell['asset_no'] == '')
1175 $ret[] = array ('tag' => '$no_asset_tag');
1176 if ($cell['runs8021Q'])
1177 $ret[] = array ('tag' => '$runs_8021Q');
1178
1179 // dictionary attribute autotags '$attr_X_Y'
1180 $attrs = getAttrValues($cell['id']);
1181 foreach ($attrs as $attr_id => $attr_record)
1182 if (isset ($attr_record['key']))
1183 $ret[] = array ('tag' => "\$attr_{$attr_id}_{$attr_record['key']}");
1184 break;
1185 case 'ipv4net':
1186 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
1187 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
1188 for ($i = 8; $i < 32; $i++)
1189 {
1190 // these conditions hit 1 to 3 times per each i
1191 if ($cell['mask'] >= $i)
1192 $ret[] = array ('tag' => '$masklen_ge_' . $i);
1193 if ($cell['mask'] <= $i)
1194 $ret[] = array ('tag' => '$masklen_le_' . $i);
1195 if ($cell['mask'] == $i)
1196 $ret[] = array ('tag' => '$masklen_eq_' . $i);
1197 }
1198 $ret[] = array ('tag' => '$any_ip4net');
1199 $ret[] = array ('tag' => '$any_net');
1200 break;
1201 case 'ipv6net':
1202 $ret[] = array ('tag' => '$ip6netid_' . $cell['id']);
1203 $ret[] = array ('tag' => '$any_ip6net');
1204 $ret[] = array ('tag' => '$any_net');
1205 break;
1206 case 'ipv4vs':
1207 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
1208 $ret[] = array ('tag' => '$any_ipv4vs');
1209 $ret[] = array ('tag' => '$any_vs');
1210 break;
1211 case 'ipv4rspool':
1212 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
1213 $ret[] = array ('tag' => '$any_ipv4rsp');
1214 $ret[] = array ('tag' => '$any_rsp');
1215 break;
1216 case 'user':
1217 // {$username_XXX} autotag is generated always, but {$userid_XXX}
1218 // appears only for accounts, which exist in local database.
1219 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
1220 if (isset ($cell['user_id']))
1221 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
1222 break;
1223 case 'file':
1224 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
1225 $ret[] = array ('tag' => '$any_file');
1226 break;
1227 default:
1228 throw new InvalidArgException ('cell', '(array)', 'this input does not belong here');
1229 break;
1230 }
1231 // {$tagless} doesn't apply to users
1232 switch ($cell['realm'])
1233 {
1234 case 'rack':
1235 case 'object':
1236 case 'ipv4net':
1237 case 'ipv4vs':
1238 case 'ipv4rspool':
1239 case 'file':
1240 if (!count ($cell['etags']))
1241 $ret[] = array ('tag' => '$untagged');
1242 break;
1243 default:
1244 break;
1245 }
1246 return $ret;
1247 }
1248
1249 // Check, if the given tag is present on the chain (will only work
1250 // for regular tags with tag ID set.
1251 function tagOnChain ($taginfo, $tagchain)
1252 {
1253 if (!isset ($taginfo['id']))
1254 return FALSE;
1255 foreach ($tagchain as $test)
1256 if ($test['id'] == $taginfo['id'])
1257 return TRUE;
1258 return FALSE;
1259 }
1260
1261 function tagNameOnChain ($tagname, $tagchain)
1262 {
1263 foreach ($tagchain as $test)
1264 if ($test['tag'] == $tagname)
1265 return TRUE;
1266 return FALSE;
1267 }
1268
1269 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1270 // Assume, that neither of the lists contains duplicates.
1271 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1272 function tagChainCmp ($chain1, $chain2)
1273 {
1274 if (count ($chain1) != count ($chain2))
1275 return TRUE;
1276 foreach ($chain1 as $taginfo1)
1277 if (!tagOnChain ($taginfo1, $chain2))
1278 return TRUE;
1279 return FALSE;
1280 }
1281
1282 function redirectIfNecessary ()
1283 {
1284 global
1285 $trigger,
1286 $pageno,
1287 $tabno;
1288 $pmap = array
1289 (
1290 'accounts' => 'userlist',
1291 'rspools' => 'ipv4rsplist',
1292 'rspool' => 'ipv4rsp',
1293 'vservices' => 'ipv4vslist',
1294 'vservice' => 'ipv4vs',
1295 'objects' => 'depot',
1296 'objgroup' => 'depot',
1297 );
1298 $tmap = array();
1299 $tmap['objects']['newmulti'] = 'addmore';
1300 $tmap['objects']['newobj'] = 'addmore';
1301 $tmap['object']['switchvlans'] = 'livevlans';
1302 $tmap['object']['slb'] = 'editrspvs';
1303 $tmap['object']['portfwrd'] = 'nat4';
1304 $tmap['object']['network'] = 'ipv4';
1305 if (isset ($pmap[$pageno]))
1306 redirectUser ($pmap[$pageno], $tabno);
1307 if (isset ($tmap[$pageno][$tabno]))
1308 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1309
1310 if
1311 (
1312 ! isset ($_REQUEST['tab']) and
1313 isset ($_SESSION['RTLT'][$pageno]) and
1314 getConfigVar ('SHOW_LAST_TAB') == 'yes' and
1315 permitted ($pageno, $_SESSION['RTLT'][$pageno]['tabname']) and
1316 time() - $_SESSION['RTLT'][$pageno]['time'] <= TAB_REMEMBER_TIMEOUT
1317 )
1318 redirectUser ($pageno, $_SESSION['RTLT'][$pageno]['tabname']);
1319
1320 // check if we accidentaly got on a dynamic tab that shouldn't be shown for this object
1321 if
1322 (
1323 isset ($trigger[$pageno][$tabno]) and
1324 !strlen (call_user_func ($trigger[$pageno][$tabno]))
1325 )
1326 {
1327 $_SESSION['RTLT'][$pageno]['dont_remember'] = 1;
1328 redirectUser ($pageno, 'default');
1329 }
1330 }
1331
1332 function prepareNavigation()
1333 {
1334 global
1335 $pageno,
1336 $tabno;
1337 $pageno = (isset ($_REQUEST['page'])) ? $_REQUEST['page'] : 'index';
1338
1339 if (isset ($_REQUEST['tab']))
1340 $tabno = $_REQUEST['tab'];
1341 else
1342 $tabno = 'default';
1343 }
1344
1345 function fixContext ($target = NULL)
1346 {
1347 global
1348 $pageno,
1349 $auto_tags,
1350 $expl_tags,
1351 $impl_tags,
1352 $target_given_tags,
1353 $user_given_tags,
1354 $etype_by_pageno,
1355 $page;
1356
1357 if ($target !== NULL)
1358 {
1359 $target_given_tags = $target['etags'];
1360 // Don't reset autochain, because auth procedures could push stuff there in.
1361 // Another important point is to ignore 'user' realm, so we don't infuse effective
1362 // context with autotags of the displayed account.
1363 if ($target['realm'] != 'user')
1364 $auto_tags = array_merge ($auto_tags, $target['atags']);
1365 }
1366 elseif (array_key_exists ($pageno, $etype_by_pageno))
1367 {
1368 // Each page listed in the map above requires one uint argument.
1369 $target_realm = $etype_by_pageno[$pageno];
1370 assertUIntArg ($page[$pageno]['bypass']);
1371 $target_id = $_REQUEST[$page[$pageno]['bypass']];
1372 $target = spotEntity ($target_realm, $target_id);
1373 $target_given_tags = $target['etags'];
1374 if ($target['realm'] != 'user')
1375 $auto_tags = array_merge ($auto_tags, $target['atags']);
1376 }
1377 // Explicit and implicit chains should be normally empty at this point, so
1378 // overwrite the contents anyway.
1379 $expl_tags = mergeTagChains ($user_given_tags, $target_given_tags);
1380 $impl_tags = getImplicitTags ($expl_tags);
1381 }
1382
1383 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1384 // records indexed by tag IDs (tag chain).
1385 function buildTagChainFromIds ($tagidlist)
1386 {
1387 global $taglist;
1388 $ret = array();
1389 foreach (array_unique ($tagidlist) as $tag_id)
1390 if (isset ($taglist[$tag_id]))
1391 $ret[] = $taglist[$tag_id];
1392 return $ret;
1393 }
1394
1395 // Process a given tag tree and return only meaningful branches. The resulting
1396 // (sub)tree will have refcnt leaves on every last branch.
1397 function getObjectiveTagTree ($tree, $realm, $preselect)
1398 {
1399 $self = __FUNCTION__;
1400 $ret = array();
1401 foreach ($tree as $taginfo)
1402 {
1403 $subsearch = $self ($taginfo['kids'], $realm, $preselect);
1404 // If the current node addresses something, add it to the result
1405 // regardless of how many sub-nodes it features.
1406 if
1407 (
1408 isset ($taginfo['refcnt'][$realm]) or
1409 count ($subsearch) > 1 or
1410 in_array ($taginfo['id'], $preselect)
1411 )
1412 $ret[] = array
1413 (
1414 'id' => $taginfo['id'],
1415 'tag' => $taginfo['tag'],
1416 'parent_id' => $taginfo['parent_id'],
1417 'refcnt' => $taginfo['refcnt'],
1418 'kids' => $subsearch
1419 );
1420 else
1421 $ret = array_merge ($ret, $subsearch);
1422 }
1423 return $ret;
1424 }
1425
1426 // Preprocess tag tree to get only tags which can effectively reduce given filter result,
1427 // than passes shrinked tag tree to getObjectiveTagTree and return its result.
1428 // This makes sense only if andor mode is 'and', otherwise function does not modify tree.
1429 // 'Given filter' is a pair of $entity_list(filter result) and $preselect(filter data).
1430 // 'Effectively' means reduce to non-empty result.
1431 function getShrinkedTagTree($entity_list, $realm, $preselect) {
1432 global $tagtree;
1433 if ($preselect['andor'] != 'and' || empty($entity_list) && $preselect['is_empty'])
1434 return getObjectiveTagTree($tagtree, $realm, $preselect['tagidlist']);
1435
1436 $used_tags = array(); //associative, keys - tag ids, values - taginfos
1437 foreach ($entity_list as $entity)
1438 {
1439 foreach ($entity['etags'] as $etag)
1440 if (! array_key_exists($etag['id'], $used_tags))
1441 $used_tags[$etag['id']] = 1;
1442 else
1443 $used_tags[$etag['id']]++;
1444
1445 foreach ($entity['itags'] as $itag)
1446 if (! array_key_exists($itag['id'], $used_tags))
1447 $used_tags[$itag['id']] = 0;
1448 }
1449
1450 $shrinked_tree = shrinkSubtree($tagtree, $used_tags, $preselect, $realm);
1451 return getObjectiveTagTree($shrinked_tree, $realm, $preselect['tagidlist']);
1452 }
1453
1454 // deletes item from tag subtree unless it exists in $used_tags and not preselected
1455 function shrinkSubtree($tree, $used_tags, $preselect, $realm) {
1456 $self = __FUNCTION__;
1457
1458 foreach($tree as $i => &$item) {
1459 $item['kids'] = $self($item['kids'], $used_tags, $preselect, $realm);
1460 $item['kidc'] = count($item['kids']);
1461 if
1462 (
1463 ! array_key_exists($item['id'], $used_tags) &&
1464 ! in_array($item['id'], $preselect['tagidlist']) &&
1465 ! $item['kidc']
1466 )
1467 unset($tree[$i]);
1468 else {
1469 $item['refcnt'][$realm] = $used_tags[$item['id']];
1470 if (! $item['refcnt'][$realm])
1471 unset($item['refcnt'][$realm]);
1472 }
1473 }
1474 return $tree;
1475 }
1476
1477 // Get taginfo record by tag name, return NULL, if record doesn't exist.
1478 function getTagByName ($target_name)
1479 {
1480 global $taglist;
1481 foreach ($taglist as $taginfo)
1482 if ($taginfo['tag'] == $target_name)
1483 return $taginfo;
1484 return NULL;
1485 }
1486
1487 // Merge two chains, filtering dupes out. Return the resulting superset.
1488 function mergeTagChains ($chainA, $chainB)
1489 {
1490 // $ret = $chainA;
1491 // Reindex by tag id in any case.
1492 $ret = array();
1493 foreach ($chainA as $tag)
1494 $ret[$tag['id']] = $tag;
1495 foreach ($chainB as $tag)
1496 if (!isset ($ret[$tag['id']]))
1497 $ret[$tag['id']] = $tag;
1498 return $ret;
1499 }
1500
1501 function getCellFilter ()
1502 {
1503 global $sic;
1504 global $pageno;
1505 $staticFilter = getConfigVar ('STATIC_FILTER');
1506 if (isset ($_REQUEST['tagfilter']) and is_array ($_REQUEST['tagfilter']))
1507 {
1508 $_REQUEST['cft'] = $_REQUEST['tagfilter'];
1509 unset ($_REQUEST['tagfilter']);
1510 }
1511 $andor_used = FALSE;
1512 //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.
1513 if(isset($_REQUEST['andor']))
1514 {
1515 $andor_used = TRUE;
1516 unset($_SESSION[$pageno]);
1517 }
1518 if (isset ($_SESSION[$pageno]['tagfilter']) and is_array ($_SESSION[$pageno]['tagfilter']) and !(isset($_REQUEST['cft'])) and $staticFilter == 'yes')
1519 {
1520 $_REQUEST['cft'] = $_SESSION[$pageno]['tagfilter'];
1521 }
1522 if (isset ($_SESSION[$pageno]['cfe']) and !(isset($sic['cfe'])) and $staticFilter == 'yes')
1523 {
1524 $sic['cfe'] = $_SESSION[$pageno]['cfe'];
1525 }
1526 if (isset ($_SESSION[$pageno]['andor']) and !(isset($_REQUEST['andor'])) and $staticFilter == 'yes')
1527 {
1528 $_REQUEST['andor'] = $_SESSION[$pageno]['andor'];
1529 }
1530
1531
1532 $ret = array
1533 (
1534 'tagidlist' => array(),
1535 'tnamelist' => array(),
1536 'pnamelist' => array(),
1537 'andor' => '',
1538 'text' => '',
1539 'extratext' => '',
1540 'expression' => array(),
1541 'urlextra' => '', // Just put text here and let makeHref call urlencode().
1542 'is_empty' => TRUE,
1543 );
1544 switch (TRUE)
1545 {
1546 case (!isset ($_REQUEST['andor'])):
1547 $andor2 = getConfigVar ('FILTER_DEFAULT_ANDOR');
1548 break;
1549 case ($_REQUEST['andor'] == 'and'):
1550 case ($_REQUEST['andor'] == 'or'):
1551 $_SESSION[$pageno]['andor'] = $_REQUEST['andor'];
1552 $ret['andor'] = $andor2 = $_REQUEST['andor'];
1553 break;
1554 default:
1555 showWarning ('Invalid and/or switch value in submitted form');
1556 return NULL;
1557 }
1558 $andor1 = '';
1559 // Both tags and predicates, which don't exist, should be
1560 // handled somehow. Discard them silently for now.
1561 if (isset ($_REQUEST['cft']) and is_array ($_REQUEST['cft']))
1562 {
1563 $_SESSION[$pageno]['tagfilter'] = $_REQUEST['cft'];
1564 global $taglist;
1565 foreach ($_REQUEST['cft'] as $req_id)
1566 if (isset ($taglist[$req_id]))
1567 {
1568 $ret['tagidlist'][] = $req_id;
1569 $ret['tnamelist'][] = $taglist[$req_id]['tag'];
1570 $andor_used = $andor_used || (trim($andor1) != '');
1571 $ret['text'] .= $andor1 . '{' . $taglist[$req_id]['tag'] . '}';
1572 $andor1 = ' ' . $andor2 . ' ';
1573 $ret['urlextra'] .= '&cft[]=' . $req_id;
1574 }
1575 }
1576 if (isset ($_REQUEST['cfp']) and is_array ($_REQUEST['cfp']))
1577 {
1578 global $pTable;
1579 foreach ($_REQUEST['cfp'] as $req_name)
1580 if (isset ($pTable[$req_name]))
1581 {
1582 $ret['pnamelist'][] = $req_name;
1583 $andor_used = $andor_used || (trim($andor1) != '');
1584 $ret['text'] .= $andor1 . '[' . $req_name . ']';
1585 $andor1 = ' ' . $andor2 . ' ';
1586 $ret['urlextra'] .= '&cfp[]=' . $req_name;
1587 }
1588 }
1589 // Extra text comes from TEXTAREA and is easily screwed by standard escaping function.
1590 if (isset ($sic['cfe']))
1591 {
1592 $_SESSION[$pageno]['cfe'] = $sic['cfe'];
1593 // Only consider extra text, when it is a correct RackCode expression.
1594 $parse = spotPayload ($sic['cfe'], 'SYNT_EXPR');
1595 if ($parse['result'] == 'ACK')
1596 {
1597 $ret['extratext'] = trim ($sic['cfe']);
1598 $ret['urlextra'] .= '&cfe=' . $ret['extratext'];
1599 }
1600 }
1601 $finaltext = array();
1602 if (strlen ($ret['text']))
1603 $finaltext[] = '(' . $ret['text'] . ')';
1604 if (strlen ($ret['extratext']))
1605 $finaltext[] = '(' . $ret['extratext'] . ')';
1606 $andor_used = $andor_used || (count($finaltext) > 1);
1607 $finaltext = implode (' ' . $andor2 . ' ', $finaltext);
1608 if (strlen ($finaltext))
1609 {
1610 $ret['is_empty'] = FALSE;
1611 $parse = spotPayload ($finaltext, 'SYNT_EXPR');
1612 $ret['expression'] = $parse['result'] == 'ACK' ? $parse['load'] : NULL;
1613 // It's not quite fair enough to put the blame of the whole text onto
1614 // non-empty "extra" portion of it, but it's the only user-generated portion
1615 // of it, thus the most probable cause of parse error.
1616 if (strlen ($ret['extratext']))
1617 $ret['extraclass'] = $parse['result'] == 'ACK' ? 'validation-success' : 'validation-error';
1618 }
1619 if (! $andor_used)
1620 $ret['andor'] = getConfigVar ('FILTER_DEFAULT_ANDOR');
1621 else
1622 $ret['urlextra'] .= '&andor=' . $ret['andor'];
1623 return $ret;
1624 }
1625
1626 // Return an empty message log.
1627 function emptyLog ()
1628 {
1629 return array
1630 (
1631 'v' => 2,
1632 'm' => array()
1633 );
1634 }
1635
1636 // Return a message log consisting of only one message.
1637 function oneLiner ($code, $args = array())
1638 {
1639 $ret = emptyLog();
1640 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1641 return $ret;
1642 }
1643
1644 // Merge message payload from two message logs given and return the result.
1645 function mergeLogs ($log1, $log2)
1646 {
1647 $ret = emptyLog();
1648 $ret['m'] = array_merge ($log1['m'], $log2['m']);
1649 return $ret;
1650 }
1651
1652 function validTagName ($s, $allow_autotag = FALSE)
1653 {
1654 if (1 == preg_match (TAGNAME_REGEXP, $s))
1655 return TRUE;
1656 if ($allow_autotag and 1 == preg_match (AUTOTAGNAME_REGEXP, $s))
1657 return TRUE;
1658 return FALSE;
1659 }
1660
1661 function redirectUser ($p, $t)
1662 {
1663 global $page;
1664 $l = "index.php?page=${p}&tab=${t}";
1665 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1666 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1667 if (isset ($page[$p]['bypass_tabs']))
1668 foreach ($page[$p]['bypass_tabs'] as $param_name)
1669 if (isset ($_REQUEST[$param_name]))
1670 $l .= '&' . urlencode ($param_name) . '=' . urlencode ($_REQUEST[$param_name]);
1671 header ("Location: " . $l);
1672 die;
1673 }
1674
1675 function getRackCodeStats ()
1676 {
1677 global $rackCode;
1678 $defc = $grantc = $modc = 0;
1679 foreach ($rackCode as $s)
1680 switch ($s['type'])
1681 {
1682 case 'SYNT_DEFINITION':
1683 $defc++;
1684 break;
1685 case 'SYNT_GRANT':
1686 $grantc++;
1687 break;
1688 case 'SYNT_CTXMOD':
1689 $modc++;
1690 break;
1691 default:
1692 break;
1693 }
1694 $ret = array
1695 (
1696 'Definition sentences' => $defc,
1697 'Grant sentences' => $grantc,
1698 'Context mod sentences' => $modc
1699 );
1700 return $ret;
1701 }
1702
1703 function getRackImageWidth ()
1704 {
1705 global $rtwidth;
1706 return 3 + $rtwidth[0] + $rtwidth[1] + $rtwidth[2] + 3;
1707 }
1708
1709 function getRackImageHeight ($units)
1710 {
1711 return 3 + 3 + $units * 2;
1712 }
1713
1714 // Perform substitutions and return resulting string
1715 // used solely by buildLVSConfig()
1716 function apply_macros ($macros, $subject, &$error_macro_stat)
1717 {
1718 // clear all text before last %RESET% macro
1719 $reset_keyword = '%RESET%';
1720 $reset_position = mb_strpos($subject, $reset_keyword, 0);
1721 if ($reset_position === FALSE)
1722 $ret = $subject;
1723 else
1724 $ret = trim
1725 (
1726 mb_substr($subject, $reset_position + mb_strlen($reset_keyword)),
1727 "\n\r"
1728 );
1729
1730 foreach ($macros as $search => $replace)
1731 {
1732 if (empty($replace))
1733 {
1734 $replace = "<span class=\"msg_error\">$search</span>";
1735 $count = 0;
1736 $ret = str_replace ($search, $replace, $ret, $count);
1737 if ($count)
1738 {
1739 if (array_key_exists($search, $error_macro_stat))
1740 $error_macro_stat[$search] += $count;
1741 else
1742 $error_macro_stat[$search] = $count;
1743 }
1744 }
1745 else
1746 $ret = str_replace ($search, $replace, $ret);
1747 }
1748 return $ret;
1749 }
1750
1751 // throws RTBuildLVSConfigError exception if undefined macros found
1752 function buildLVSConfig ($object_id)
1753 {
1754 $oInfo = spotEntity ('object', $object_id);
1755 $defaults = getSLBDefaults (TRUE);
1756 $lbconfig = getSLBConfig ($object_id);
1757 if ($lbconfig === NULL)
1758 {
1759 showWarning ('getSLBConfig() failed');
1760 return;
1761 }
1762 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1763 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1764
1765 $error_stat = array();
1766 foreach ($lbconfig as $vs_id => $vsinfo)
1767 {
1768 $newconfig .= "########################################################\n" .
1769 "# VS (id == ${vs_id}): " . (!strlen ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1770 "# RS pool (id == ${vsinfo['pool_id']}): " . (!strlen ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1771 "########################################################\n";
1772 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1773 $macros = array
1774 (
1775 '%VIP%' => $vsinfo['vip'],
1776 '%VPORT%' => $vsinfo['vport'],
1777 '%PROTO%' => $vsinfo['proto'],
1778 '%VNAME%' => $vsinfo['vs_name'],
1779 '%RSPOOLNAME%' => $vsinfo['pool_name'],
1780 '%PRIO%' => $vsinfo['prio']
1781 );
1782 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1783 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1784 $newconfig .= lf_wrap (apply_macros
1785 (
1786 $macros,
1787 lf_wrap ($defaults['vs']) .
1788 lf_wrap ($vsinfo['vs_vsconfig']) .
1789 lf_wrap ($vsinfo['lb_vsconfig']) .
1790 lf_wrap ($vsinfo['pool_vsconfig']),
1791 $error_stat
1792 ));
1793 foreach ($vsinfo['rslist'] as $rs)
1794 {
1795 if (!strlen ($rs['rsport']))
1796 $rs['rsport'] = $vsinfo['vport'];
1797 $macros['%RSIP%'] = $rs['rsip'];
1798 $macros['%RSPORT%'] = $rs['rsport'];
1799 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1800 $newconfig .= lf_wrap (apply_macros
1801 (
1802 $macros,
1803 lf_wrap ($defaults['rs']) .
1804 lf_wrap ($vsinfo['vs_rsconfig']) .
1805 lf_wrap ($vsinfo['lb_rsconfig']) .
1806 lf_wrap ($vsinfo['pool_rsconfig']) .
1807 lf_wrap ($rs['rs_rsconfig']),
1808 $error_stat
1809 ));
1810 $newconfig .= "\t}\n";
1811 }
1812 $newconfig .= "}\n\n\n";
1813 }
1814 if (! empty($error_stat))
1815 {
1816 $error_messages = array();
1817 foreach ($error_stat as $macro => $count)
1818 $error_messages[] = "Error: macro $macro can not be empty ($count occurences)";
1819 throw new RTBuildLVSConfigError($error_messages, $newconfig, $object_id);
1820 }
1821
1822 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1823 return dos2unix ($newconfig);
1824 }
1825
1826 // Indicate occupation state of each IP address: none, ordinary or problematic.
1827 function markupIPAddrList (&$addrlist)
1828 {
1829 foreach (array_keys ($addrlist) as $ip_bin)
1830 {
1831 $refc = array
1832 (
1833 'shared' => 0, // virtual
1834 'virtual' => 0, // loopback
1835 'regular' => 0, // connected host
1836 'router' => 0 // connected gateway
1837 );
1838 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1839 $refc[$a['type']]++;
1840 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
1841 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1842 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
1843
1844 if ($nrealms == 1)
1845 $addrlist[$ip_bin]['class'] = 'trbusy';
1846 elseif ($nrealms > 1)
1847 $addrlist[$ip_bin]['class'] = 'trerror';
1848 else
1849 $addrlist[$ip_bin]['class'] = '';
1850 }
1851 }
1852
1853 // Scan the given address list (returned by scanIPv4Space/scanIPv6Space) and return a list of all routers found.
1854 function findRouters ($addrlist)
1855 {
1856 $ret = array();
1857 foreach ($addrlist as $addr)
1858 foreach ($addr['allocs'] as $alloc)
1859 if ($alloc['type'] == 'router')
1860 $ret[] = array
1861 (
1862 'id' => $alloc['object_id'],
1863 'iface' => $alloc['name'],
1864 'dname' => $alloc['object_name'],
1865 'addr' => $addr['ip']
1866 );
1867 return $ret;
1868 }
1869
1870 // Assist in tag chain sorting.
1871 function taginfoCmp ($tagA, $tagB)
1872 {
1873 return $tagA['ci'] - $tagB['ci'];
1874 }
1875
1876 // Compare networks. When sorting a tree, the records on the list will have
1877 // distinct base IP addresses.
1878 // "The comparison function must return an integer less than, equal to, or greater
1879 // than zero if the first argument is considered to be respectively less than,
1880 // equal to, or greater than the second." (c) PHP manual
1881 function IPv4NetworkCmp ($netA, $netB)
1882 {
1883 // On 64-bit systems this function can be reduced to just this:
1884 if (PHP_INT_SIZE == 8)
1885 return $netA['ip_bin'] - $netB['ip_bin'];
1886 // There's a problem just substracting one u32 integer from another,
1887 // because the result may happen big enough to become a negative i32
1888 // integer itself (PHP tries to cast everything it sees to signed int)
1889 // The comparison below must treat positive and negative values of both
1890 // arguments.
1891 // Equal values give instant decision regardless of their [equal] sign.
1892 if ($netA['ip_bin'] == $netB['ip_bin'])
1893 return 0;
1894 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1895 // 0x00000001~0x7fffffff 1~2147483647
1896 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1897 // 0x80000000~0xffffffff -2147483648~-1
1898 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1899 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1900 if ($signA == $signB)
1901 {
1902 if ($netA['ip_bin'] > $netB['ip_bin'])
1903 return 1;
1904 else
1905 return -1;
1906 }
1907 else // With only one of two values being negative, it... wins!
1908 {
1909 if ($netA['ip_bin'] < $netB['ip_bin'])
1910 return 1;
1911 else
1912 return -1;
1913 }
1914 }
1915
1916 function IPv6NetworkCmp ($netA, $netB)
1917 {
1918 return strcmp ($netA['ip_bin'], $netB['ip_bin']);
1919 }
1920
1921 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1922 function sortTree (&$tree, $sortfunc = '')
1923 {
1924 if (!strlen ($sortfunc))
1925 return;
1926 $self = __FUNCTION__;
1927 usort ($tree, $sortfunc);
1928 // Don't make a mistake of directly iterating over the items of current level, because this way
1929 // the sorting will be performed on a _copy_ if each item, not the item itself.
1930 foreach (array_keys ($tree) as $tagid)
1931 $self ($tree[$tagid]['kids'], $sortfunc);
1932 }
1933
1934 function iptree_fill (&$netdata)
1935 {
1936 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
1937 return;
1938 // If we really have nested prefixes, they must fit into the tree.
1939 $worktree = array
1940 (
1941 'ip_bin' => $netdata['ip_bin'],
1942 'mask' => $netdata['mask']
1943 );
1944 foreach ($netdata['kids'] as $pfx)
1945 iptree_embed ($worktree, $pfx);
1946 $netdata['kids'] = iptree_construct ($worktree);
1947 $netdata['kidc'] = count ($netdata['kids']);
1948 }
1949
1950 function ipv6tree_fill (&$netdata)
1951 {
1952 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
1953 return;
1954 // If we really have nested prefixes, they must fit into the tree.
1955 $worktree = array
1956 (
1957 'ip_bin' => $netdata['ip_bin'],
1958 'mask' => $netdata['mask']
1959 );
1960 foreach ($netdata['kids'] as $pfx)
1961 ipv6tree_embed ($worktree, $pfx);
1962 $netdata['kids'] = ipv6tree_construct ($worktree);
1963 $netdata['kidc'] = count ($netdata['kids']);
1964 }
1965
1966 function iptree_construct ($node)
1967 {
1968 $self = __FUNCTION__;
1969
1970 if (!isset ($node['right']))
1971 {
1972 if (!isset ($node['ip']))
1973 {
1974 $node['ip'] = long2ip ($node['ip_bin']);
1975 $node['kids'] = array();
1976 $node['kidc'] = 0;
1977 $node['name'] = '';
1978 }
1979 return array ($node);
1980 }
1981 else
1982 return array_merge ($self ($node['left']), $self ($node['right']));
1983 }
1984
1985 function ipv6tree_construct ($node)
1986 {
1987 $self = __FUNCTION__;
1988
1989 if (!isset ($node['right']))
1990 {
1991 if (!isset ($node['ip']))
1992 {
1993 $node['ip'] = $node['ip_bin']->format();
1994 $node['kids'] = array();
1995 $node['kidc'] = 0;
1996 $node['name'] = '';
1997 }
1998 return array ($node);
1999 }
2000 else
2001 return array_merge ($self ($node['left']), $self ($node['right']));
2002 }
2003
2004 function iptree_embed (&$node, $pfx)
2005 {
2006 $self = __FUNCTION__;
2007
2008 // hit?
2009 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
2010 {
2011 $node = $pfx;
2012 return;
2013 }
2014 if ($node['mask'] == $pfx['mask'])
2015 throw new RackTablesError ('the recurring loop lost control', RackTablesError::INTERNAL);
2016
2017 // split?
2018 if (!isset ($node['right']))
2019 {
2020 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
2021 $node['left']['mask'] = $node['mask'] + 1;
2022 $node['left']['ip_bin'] = $node['ip_bin'];
2023 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
2024 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] | binInvMaskFromDec ($node['left']['mask']));
2025
2026 $node['right']['mask'] = $node['mask'] + 1;
2027 $node['right']['ip_bin'] = $node['ip_bin'] + binInvMaskFromDec ($node['mask'] + 1) + 1;
2028 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
2029 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] | binInvMaskFromDec ($node['right']['mask']));
2030 }
2031
2032 // repeat!
2033 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
2034 $self ($node['left'], $pfx);
2035 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
2036 $self ($node['right'], $pfx);
2037 else
2038 throw new RackTablesError ('cannot decide between left and right', RackTablesError::INTERNAL);
2039 }
2040
2041 function ipv6tree_embed (&$node, $pfx)
2042 {
2043 $self = __FUNCTION__;
2044
2045 // hit?
2046 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
2047 {
2048 $node = $pfx;
2049 return;
2050 }
2051 if ($node['mask'] == $pfx['mask'])
2052 throw new RackTablesError ('the recurring loop lost control', RackTablesError::INTERNAL);
2053
2054 // split?
2055 if (!isset ($node['right']))
2056 {
2057 $node['left']['mask'] = $node['mask'] + 1;
2058 $node['left']['ip_bin'] = $node['ip_bin'];
2059 $node['left']['db_first'] = $node['ip_bin']->get_first_subnet_address ($node['mask'] + 1);
2060 $node['left']['db_last'] = $node['ip_bin']->get_last_subnet_address ($node['mask'] + 1);
2061
2062 $node['right']['mask'] = $node['mask'] + 1;
2063 $node['right']['ip_bin'] = $node['ip_bin']->get_last_subnet_address ($node['mask'] + 1)->next();
2064 $node['right']['db_first'] = $node['right']['ip_bin'];
2065 $node['right']['db_last'] = $node['right']['ip_bin']->get_last_subnet_address ($node['mask'] + 1);
2066 }
2067
2068 // repeat!
2069 if ($node['left']['db_first'] == $pfx['ip_bin']->get_first_subnet_address ($node['left']['mask']))
2070 $self ($node['left'], $pfx);
2071 elseif ($node['right']['db_first'] == $pfx['ip_bin']->get_first_subnet_address ($node['left']['mask']))
2072 $self ($node['right'], $pfx);
2073 else
2074 throw new RackTablesError ('cannot decide between left and right', RackTablesError::INTERNAL);
2075 }
2076
2077 function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
2078 {
2079 if (!strlen ($func))
2080 return;
2081 $self = __FUNCTION__;
2082 foreach (array_keys ($tree) as $key)
2083 {
2084 $func ($tree[$key]);
2085 if (strlen ($stopfunc) and $stopfunc ($tree[$key]))
2086 continue;
2087 $self ($tree[$key]['kids'], $func);
2088 }
2089 }
2090
2091 function loadIPv4AddrList (&$netinfo)
2092 {
2093 loadOwnIPv4Addresses ($netinfo);
2094 markupIPAddrList ($netinfo['addrlist']);
2095 }
2096
2097 function countOwnIPv4Addresses (&$node)
2098 {
2099 $node['addrt'] = 0;
2100 if (empty ($node['kids']))
2101 $node['addrt'] = binInvMaskFromDec ($node['mask']) + 1;
2102 else
2103 foreach ($node['kids'] as $nested)
2104 if (!isset ($nested['id'])) // spare
2105 $node['addrt'] += binInvMaskFromDec ($nested['mask']) + 1;
2106 }
2107
2108 function nodeIsCollapsed ($node)
2109 {
2110 return $node['symbol'] == 'node-collapsed';
2111 }
2112
2113 // implies countOwnIPv4Addresses
2114 function loadOwnIPv4Addresses (&$node)
2115 {
2116 $toscan = array();
2117 $node['addrt'] = 0;
2118 if (!isset ($node['kids']) or !count ($node['kids']))
2119 {
2120 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
2121 $node['addrt'] = $node['db_last'] - $node['db_first'] + 1;
2122 }
2123 else
2124 {
2125 $node['addrt'] = 0;
2126 foreach ($node['kids'] as $nested)
2127 if (!isset ($nested['id'])) // spare
2128 {
2129 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
2130 $node['addrt'] += $node['db_last'] - $node['db_first'] + 1;
2131 }
2132 }
2133 $node['addrlist'] = scanIPv4Space ($toscan);
2134 $node['addrc'] = count ($node['addrlist']);
2135 }
2136
2137 function loadIPv6AddrList (&$netinfo)
2138 {
2139 loadOwnIPv6Addresses ($netinfo);
2140 markupIPAddrList ($netinfo['addrlist']);
2141 }
2142
2143 function loadOwnIPv6Addresses (&$node)
2144 {
2145 $toscan = array();
2146 $node['addrt'] = 0;
2147 if (empty ($node['kids']))
2148 $toscan[] = array ('first' => $node['ip_bin'], 'last' => $node['ip_bin']->get_last_subnet_address ($node['mask']));
2149 else
2150 foreach ($node['kids'] as $nested)
2151 if (!isset ($nested['id'])) // spare
2152 $toscan[] = array ('first' => $nested['ip_bin'], 'last' => $nested['ip_bin']->get_last_subnet_address ($nested['mask']));
2153 $node['addrlist'] = scanIPv6Space ($toscan);
2154 $node['addrc'] = count ($node['addrlist']);
2155 }
2156
2157 function prepareIPv4Tree ($netlist, $expanded_id = 0)
2158 {
2159 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
2160 // so perform necessary pre-processing to make orphans belong to root. This trick
2161 // was earlier performed by getIPv4NetworkList().
2162 $netids = array_keys ($netlist);
2163 foreach ($netids as $cid)
2164 if (!in_array ($netlist[$cid]['parent_id'], $netids))
2165 $netlist[$cid]['parent_id'] = NULL;
2166 $tree = treeFromList ($netlist); // medium call
2167 sortTree ($tree, 'IPv4NetworkCmp');
2168 // complement the tree before markup to make the spare networks have "symbol" set
2169 treeApplyFunc ($tree, 'iptree_fill');
2170 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
2171 // count addresses after the markup to skip computation for hidden tree nodes
2172 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
2173 return $tree;
2174 }
2175
2176 function prepareIPv6Tree ($netlist, $expanded_id = 0)
2177 {
2178 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
2179 // so perform necessary pre-processing to make orphans belong to root. This trick
2180 // was earlier performed by getIPv4NetworkList().
2181 $netids = array_keys ($netlist);
2182 foreach ($netids as $cid)
2183 if (!in_array ($netlist[$cid]['parent_id'], $netids))
2184 $netlist[$cid]['parent_id'] = NULL;
2185 $tree = treeFromList ($netlist); // medium call
2186 sortTree ($tree, 'IPv6NetworkCmp');
2187 // complement the tree before markup to make the spare networks have "symbol" set
2188 treeApplyFunc ($tree, 'ipv6tree_fill');
2189 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
2190 return $tree;
2191 }
2192
2193 // Check all items of the tree recursively, until the requested target id is
2194 // found. Mark all items leading to this item as "expanded", collapsing all
2195 // the rest, which exceed the given threshold (if the threshold is given).
2196 function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
2197 {
2198 $self = __FUNCTION__;
2199 $ret = FALSE;
2200 foreach (array_keys ($tree) as $key)
2201 {
2202 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
2203 $below = $self ($tree[$key]['kids'], $threshold, $target);
2204 if (!$tree[$key]['kidc']) // terminal node
2205 $tree[$key]['symbol'] = 'spacer';
2206 elseif ($tree[$key]['kidc'] < $threshold)
2207 $tree[$key]['symbol'] = 'node-expanded-static';
2208 elseif ($here or $below)
2209 $tree[$key]['symbol'] = 'node-expanded';
2210 else
2211 $tree[$key]['symbol'] = 'node-collapsed';
2212 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
2213 }
2214 return $ret;
2215 }
2216
2217 // Convert entity name to human-readable value
2218 function formatEntityName ($name) {
2219 switch ($name)
2220 {
2221 case 'ipv4net':
2222 return 'IPv4 Network';
2223 case 'ipv4rspool':
2224 return 'IPv4 RS Pool';
2225 case 'ipv4vs':
2226 return 'IPv4 Virtual Service';
2227 case 'object':
2228 return 'Object';
2229 case 'rack':
2230 return 'Rack';
2231 case 'user':
2232 return 'User';
2233 }
2234 return 'invalid';
2235 }
2236
2237 // Take a MySQL or other generic timestamp and make it prettier
2238 function formatTimestamp ($timestamp) {
2239 return date('n/j/y g:iA', strtotime($timestamp));
2240 }
2241
2242 // Display hrefs for all of a file's parents. If scissors are requested,
2243 // prepend cutting button to each of them.
2244 function serializeFileLinks ($links, $scissors = FALSE)
2245 {
2246 $comma = '';
2247 $ret = '';
2248 foreach ($links as $link_id => $li)
2249 {
2250 switch ($li['entity_type'])
2251 {
2252 case 'ipv4net':
2253 $params = "page=ipv4net&id=";
2254 break;
2255 case 'ipv4rspool':
2256 $params = "page=ipv4rspool&pool_id=";
2257 break;
2258 case 'ipv4vs':
2259 $params = "page=ipv4vs&vs_id=";
2260 break;
2261 case 'object':
2262 $params = "page=object&object_id=";
2263 break;
2264 case 'rack':
2265 $params = "page=rack&rack_id=";
2266 break;
2267 case 'user':
2268 $params = "page=user&user_id=";
2269 break;
2270 }
2271 $ret .= $comma;
2272 if ($scissors)
2273 {
2274 $ret .= "<a href='" . makeHrefProcess(array('op'=>'unlinkFile', 'link_id'=>$link_id)) . "'";
2275 $ret .= getImageHREF ('cut') . '</a> ';
2276 }
2277 $ret .= sprintf("<a href='index.php?%s%s'>%s</a>", $params, $li['entity_id'], $li['name']);
2278 $comma = '<br>';
2279 }
2280 return $ret;
2281 }
2282
2283 // Convert filesize to appropriate unit and make it human-readable
2284 function formatFileSize ($bytes) {
2285 // bytes
2286 if($bytes < 1024) // bytes
2287 return "${bytes} bytes";
2288
2289 // kilobytes
2290 if ($bytes < 1024000)
2291 return sprintf ("%.1fk", round (($bytes / 1024), 1));
2292
2293 // megabytes
2294 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
2295 }
2296
2297 // Reverse of formatFileSize, it converts human-readable value to bytes
2298 function convertToBytes ($value) {
2299 $value = trim($value);
2300 $last = strtolower($value[strlen($value)-1]);
2301 switch ($last)
2302 {
2303 case 'g':
2304 $value *= 1024;
2305 case 'm':
2306 $value *= 1024;
2307 case 'k':
2308 $value *= 1024;
2309 }
2310
2311 return $value;
2312 }
2313
2314 function ip_quad2long ($ip)
2315 {
2316 return sprintf("%u", ip2long($ip));
2317 }
2318
2319 function ip_long2quad ($quad)
2320 {
2321 return long2ip($quad);
2322 }
2323
2324 function mkA ($text, $nextpage, $bypass = NULL, $nexttab = NULL)
2325 {
2326 global $page, $tab;
2327 if (!mb_strlen ($text))
2328 throw new InvalidArgException ('text', $text);
2329 if (!array_key_exists ($nextpage, $page))
2330 throw new InvalidArgException ('nextpage', $nextpage);
2331 $args = array ('page' => $nextpage);
2332 if ($nexttab !== NULL)
2333 {
2334 if (!array_key_exists ($nexttab, $tab[$nextpage]))
2335 throw new InvalidArgException ('nexttab', $nexttab);
2336 $args['tab'] = $nexttab;
2337 }
2338 if (array_key_exists ('bypass', $page[$nextpage]))
2339 {
2340 if ($bypass === NULL)
2341 throw new InvalidArgException ('bypass', $bypass);
2342 $args[$page[$nextpage]['bypass']] = $bypass;
2343 }
2344 return '<a href="' . makeHref ($args) . '">' . $text . '</a>';
2345 }
2346
2347 function makeHref($params = array())
2348 {
2349 $ret = 'index.php?';
2350 $first = true;
2351 foreach($params as $key=>$value)
2352 {
2353 if (!$first)
2354 $ret.='&';
2355 $ret .= urlencode($key).'='.urlencode($value);
2356 $first = false;
2357 }
2358 return $ret;
2359 }
2360
2361 function makeHrefProcess($params = array())
2362 {
2363 global $pageno, $tabno;
2364 $ret = 'process.php?';
2365 $first = true;
2366 if (!isset($params['page']))
2367 $params['page'] = $pageno;
2368 if (!isset($params['tab']))
2369 $params['tab'] = $tabno;
2370 foreach($params as $key=>$value)
2371 {
2372 if (!$first)
2373 $ret.='&';
2374 $ret .= urlencode($key).'='.urlencode($value);
2375 $first = false;
2376 }
2377 return $ret;
2378 }
2379
2380 function makeHrefForHelper ($helper_name, $params = array())
2381 {
2382 $ret = 'popup.php?helper=' . $helper_name;
2383 foreach($params as $key=>$value)
2384 $ret .= '&'.urlencode($key).'='.urlencode($value);
2385 return $ret;
2386 }
2387
2388 // Process the given list of records to build data suitable for printNiftySelect()
2389 // (like it was formerly executed by printSelect()). Screen out vendors according
2390 // to VENDOR_SIEVE, if object type ID is provided. However, the OPTGROUP with already
2391 // selected OPTION is protected from being screened.
2392 function cookOptgroups ($recordList, $object_type_id = 0, $existing_value = 0)
2393 {
2394 $ret = array();
2395 // Always keep "other" OPTGROUP at the SELECT bottom.
2396 $therest = array();
2397 foreach ($recordList as $dict_key => $dict_value)
2398 if (strpos ($dict_value, '%GSKIP%') !== FALSE)
2399 {
2400 $tmp = explode ('%GSKIP%', $dict_value, 2);
2401 $ret[$tmp[0]][$dict_key] = $tmp[1];
2402 }
2403 elseif (strpos ($dict_value, '%GPASS%') !== FALSE)
2404 {
2405 $tmp = explode ('%GPASS%', $dict_value, 2);
2406 $ret[$tmp[0]][$dict_key] = $tmp[1];
2407 }
2408 else
2409 $therest[$dict_key] = $dict_value;
2410 if ($object_type_id != 0)
2411 {
2412 $screenlist = array();
2413 foreach (explode (';', getConfigVar ('VENDOR_SIEVE')) as $sieve)
2414 if (preg_match ("/^([^@]+)(@${object_type_id})?\$/", trim ($sieve), $regs)){
2415 $screenlist[] = $regs[1];
2416 }
2417 foreach (array_keys ($ret) as $vendor)
2418 if (in_array ($vendor, $screenlist))
2419 {
2420 $ok_to_screen = TRUE;
2421 if ($existing_value)
2422 foreach (array_keys ($ret[$vendor]) as $recordkey)
2423 if ($recordkey == $existing_value)
2424 {
2425 $ok_to_screen = FALSE;
2426 break;
2427 }
2428 if ($ok_to_screen)
2429 unset ($ret[$vendor]);
2430 }
2431 }
2432 $ret['other'] = $therest;
2433 return $ret;
2434 }
2435
2436 function dos2unix ($text)
2437 {
2438 return str_replace ("\r\n", "\n", $text);
2439 }
2440
2441 function unix2dos ($text)
2442 {
2443 return str_replace ("\n", "\r\n", $text);
2444 }
2445
2446 function buildPredicateTable ($parsetree)
2447 {
2448 $ret = array();
2449 foreach ($parsetree as $sentence)
2450 if ($sentence['type'] == 'SYNT_DEFINITION')
2451 $ret[$sentence['term']] = $sentence['definition'];
2452 // Now we have predicate table filled in with the latest definitions of each
2453 // particular predicate met. This isn't as chik, as on-the-fly predicate
2454 // overloading during allow/deny scan, but quite sufficient for this task.
2455 return $ret;
2456 }
2457
2458 // Take a list of records and filter against given RackCode expression. Return
2459 // the original list intact, if there was no filter requested, but return an
2460 // empty list, if there was an error.
2461 function filterCellList ($list_in, $expression = array())
2462 {
2463 if ($expression === NULL)
2464 return array();
2465 if (!count ($expression))
2466 return $list_in;
2467 $list_out = array();
2468 foreach ($list_in as $item_key => $item_value)
2469 if (TRUE === judgeCell ($item_value, $expression))
2470 $list_out[$item_key] = $item_value;
2471 return $list_out;
2472 }
2473
2474 function eval_expression ($expr, $tagchain, $ptable, $silent = FALSE)
2475 {
2476 $self = __FUNCTION__;
2477 switch ($expr['type'])
2478 {
2479 // Return true, if given tag is present on the tag chain.
2480 case 'LEX_TAG':
2481 case 'LEX_AUTOTAG':
2482 foreach ($tagchain as $tagInfo)
2483 if ($expr['load'] == $tagInfo['tag'])
2484 return TRUE;
2485 return FALSE;
2486 case 'LEX_PREDICATE': // Find given predicate in the symbol table and evaluate it.
2487 $pname = $expr['load'];
2488 if (!isset ($ptable[$pname]))
2489 {
2490 if (!$silent)
2491 showWarning ("Predicate '${pname}' is referenced before declaration");
2492 return NULL;
2493 }
2494 return $self ($ptable[$pname], $tagchain, $ptable);
2495 case 'LEX_TRUE':
2496 return TRUE;
2497 case 'LEX_FALSE':
2498 return FALSE;
2499 case 'SYNT_NOT_EXPR':
2500 $tmp = $self ($expr['load'], $tagchain, $ptable);
2501 if ($tmp === TRUE)
2502 return FALSE;
2503 elseif ($tmp === FALSE)
2504 return TRUE;
2505 else
2506 return $tmp;
2507 case 'SYNT_AND_EXPR': // binary AND
2508 if (FALSE == $self ($expr['left'], $tagchain, $ptable))
2509 return FALSE; // early failure
2510 return $self ($expr['right'], $tagchain, $ptable);
2511 case 'SYNT_EXPR': // binary OR
2512 if (TRUE == $self ($expr['left'], $tagchain, $ptable))
2513 return TRUE; // early success
2514 return $self ($expr['right'], $tagchain, $ptable);
2515 default:
2516 if (!$silent)
2517 showWarning ("Evaluation error, cannot process expression type '${expr['type']}'");
2518 return NULL;
2519 break;
2520 }
2521 }
2522
2523 // Tell, if the given expression is true for the given entity. Take complete record on input.
2524 function judgeCell ($cell, $expression)
2525 {
2526 global $pTable;
2527 return eval_expression
2528 (
2529 $expression,
2530 array_merge
2531 (
2532 $cell['etags'],
2533 $cell['itags'],
2534 $cell['atags']
2535 ),
2536 $pTable,
2537 TRUE
2538 );
2539 }
2540
2541 // Tell, if a constraint from config option permits given record.
2542 function considerConfiguredConstraint ($cell, $varname)
2543 {
2544 if (!strlen (getConfigVar ($varname)))
2545 return TRUE; // no restriction
2546 global $parseCache;
2547 if (!isset ($parseCache[$varname]))
2548 // getConfigVar() doesn't re-read the value from DB because of its
2549 // own cache, so there is no race condition here between two calls.
2550 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
2551 if ($parseCache[$varname]['result'] != 'ACK')
2552 return FALSE; // constraint set, but cannot be used due to compilation error
2553 return judgeCell ($cell, $parseCache[$varname]['load']);
2554 }
2555
2556 // Return list of records in the given realm, which conform to
2557 // the given RackCode expression. If the realm is unknown or text
2558 // doesn't validate as a RackCode expression, return NULL.
2559 // Otherwise (successful scan) return a list of all matched
2560 // records, even if the list is empty (array() !== NULL). If the
2561 // text is an empty string, return all found records in the given
2562 // realm.
2563 function scanRealmByText ($realm = NULL, $ftext = '')
2564 {
2565 switch ($realm)
2566 {
2567 case 'object':
2568 case 'user':
2569 case 'ipv4net':
2570 case 'file':
2571 case 'ipv4vs':
2572 case 'ipv4rspool':
2573 if (!strlen ($ftext = trim ($ftext)))
2574 $fexpr = array();
2575 else
2576 {
2577 $fparse = spotPayload ($ftext, 'SYNT_EXPR');
2578 if ($fparse['result'] != 'ACK')
2579 return NULL;
2580 $fexpr = $fparse['load'];
2581 }
2582 return filterCellList (listCells ($realm), $fexpr);
2583 default:
2584 throw new InvalidArgException ('$realm', $realm);
2585 }
2586
2587 }
2588
2589 function getIPv4VSOptions ()
2590 {
2591 $ret = array();
2592 foreach (listCells ('ipv4vs') as $vsid => $vsinfo)
2593 $ret[$vsid] = $vsinfo['dname'] . (!strlen ($vsinfo['name']) ? '' : " (${vsinfo['name']})");
2594 return $ret;
2595 }
2596
2597 function getIPv4RSPoolOptions ()
2598 {
2599 $ret = array();
2600 foreach (listCells ('ipv4rspool') as $pool_id => $poolInfo)
2601 $ret[$pool_id] = $poolInfo['name'];
2602 return $ret;
2603 }
2604
2605 // Derive a complete cell structure from the given username regardless
2606 // if it is a local account or not.
2607 function constructUserCell ($username)
2608 {
2609 if (NULL !== ($userid = getUserIDByUsername ($username)))
2610 return spotEntity ('user', $userid);
2611 $ret = array
2612 (
2613 'realm' => 'user',
2614 'user_name' => $username,
2615 'user_realname' => '',
2616 'etags' => array(),
2617 'itags' => array(),
2618 );
2619 $ret['atags'] = generateEntityAutoTags ($ret);
2620 return $ret;
2621 }
2622
2623 // Let's have this debug helper here to enable debugging of process.php w/o interface.php.
2624 function dump ($var)
2625 {
2626 echo '<div align=left><pre>';
2627 print_r ($var);
2628 echo '</pre></div>';
2629 }
2630
2631 function getTagChart ($limit = 0, $realm = 'total', $special_tags = array())
2632 {
2633 global $taglist;
2634 // first build top-N chart...
2635 $toplist = array();
2636 foreach ($taglist as $taginfo)
2637 if (isset ($taginfo['refcnt'][$realm]))
2638 $toplist[$taginfo['id']] = $taginfo['refcnt'][$realm];
2639 arsort ($toplist, SORT_NUMERIC);
2640 $ret = array();
2641 $done = 0;
2642 foreach (array_keys ($toplist) as $tag_id)
2643 {
2644 $ret[$tag_id] = $taglist[$tag_id];
2645 if (++$done == $limit)
2646 break;
2647 }
2648 // ...then make sure, that every item of the special list is shown
2649 // (using the same sort order)
2650 $extra = array();
2651 foreach ($special_tags as $taginfo)
2652 if (!array_key_exists ($taginfo['id'], $ret))
2653 $extra[$taginfo['id']] = $taglist[$taginfo['id']]['refcnt'][$realm];
2654 arsort ($extra, SORT_NUMERIC);
2655 foreach (array_keys ($extra) as $tag_id)
2656 $ret[] = $taglist[$tag_id];
2657 return $ret;
2658 }
2659
2660 function decodeObjectType ($objtype_id, $style = 'r')
2661 {
2662 static $types = array();
2663 if (!count ($types))
2664 $types = array
2665 (
2666 'r' => readChapter (CHAP_OBJTYPE),
2667 'a' => readChapter (CHAP_OBJTYPE, 'a'),
2668 'o' => readChapter (CHAP_OBJTYPE, 'o')
2669 );
2670 return $types[$style][$objtype_id];
2671 }
2672
2673 function isolatedPermission ($p, $t, $cell)
2674 {
2675 // This function is called from both "file" page and a number of other pages,
2676 // which have already fixed security context and authorized the user for it.
2677 // OTOH, it is necessary here to authorize against the current file, which
2678 // means saving the current context and building a new one.
2679 global
2680 $expl_tags,
2681 $impl_tags,
2682 $target_given_tags,
2683 $auto_tags;
2684 // push current context
2685 $orig_expl_tags = $expl_tags;
2686 $orig_impl_tags = $impl_tags;
2687 $orig_target_given_tags = $target_given_tags;
2688 $orig_auto_tags = $auto_tags;
2689 // retarget
2690 fixContext ($cell);
2691 // remember decision
2692 $ret = permitted ($p, $t);
2693 // pop context
2694 $expl_tags = $orig_expl_tags;
2695 $impl_tags = $orig_impl_tags;
2696 $target_given_tags = $orig_target_given_tags;
2697 $auto_tags = $orig_auto_tags;
2698 return $ret;
2699 }
2700
2701 function getPortListPrefs()
2702 {
2703 $ret = array();
2704 if (0 >= ($ret['iif_pick'] = getConfigVar ('DEFAULT_PORT_IIF_ID')))
2705 $ret['iif_pick'] = 1;
2706 $ret['oif_picks'] = array();
2707 foreach (explode (';', getConfigVar ('DEFAULT_PORT_OIF_IDS')) as $tmp)
2708 {
2709 $tmp = explode ('=', trim ($tmp));
2710 if (count ($tmp) == 2 and $tmp[0] > 0 and $tmp[1] > 0)
2711 $ret['oif_picks'][$tmp[0]] = $tmp[1];
2712 }
2713 // enforce default value
2714 if (!array_key_exists (1, $ret['oif_picks']))
2715 $ret['oif_picks'][1] = 24;
2716 $ret['selected'] = $ret['iif_pick'] . '-' . $ret['oif_picks'][$ret['iif_pick']];
2717 return $ret;
2718 }
2719
2720 // Return data for printNiftySelect() with port type options. All OIF options
2721 // for the default IIF will be shown, but only the default OIFs will be present
2722 // for each other IIFs. IIFs, for which there is no default OIF, will not
2723 // be listed.
2724 // This SELECT will be used for the "add new port" form.
2725 function getNewPortTypeOptions()
2726 {
2727 $ret = array();
2728 $prefs = getPortListPrefs();
2729 foreach (getPortInterfaceCompat() as $row)
2730 {
2731 if ($row['iif_id'] == $prefs['iif_pick'])
2732 $optgroup = $row['iif_name'];
2733 elseif (array_key_exists ($row['iif_id'], $prefs['oif_picks']) and $prefs['oif_picks'][$row['iif_id']] == $row['oif_id'])
2734 $optgroup = 'other';
2735 else
2736 continue;
2737 if (!array_key_exists ($optgroup, $ret))
2738 $ret[$optgroup] = array();
2739 $ret[$optgroup][$row['iif_id'] . '-' . $row['oif_id']] = $row['oif_name'];
2740 }
2741 return $ret;
2742 }
2743
2744 // Return a serialized version of VLAN configuration for a port.
2745 // If a native VLAN is defined, print it first. All other VLANs
2746 // are tagged and are listed after a plus sign. When no configuration
2747 // is set for a port, return "default" string.
2748 function serializeVLANPack ($vlanport)
2749 {
2750 if (!array_key_exists ('mode', $vlanport))
2751 return 'error';
2752 switch ($vlanport['mode'])
2753 {
2754 case 'none':
2755 return 'none';
2756 case 'access':
2757 $ret = 'A';
2758 break;
2759 case 'trunk':
2760 $ret = 'T';
2761 break;
2762 case 'uplink':
2763 $ret = 'U';
2764 break;
2765 case 'downlink':
2766 $ret = 'D';
2767 break;
2768 default:
2769 return 'error';
2770 }
2771 $tagged = array();
2772 foreach ($vlanport['allowed'] as $vlan_id)
2773 if ($vlan_id != $vlanport['native'])
2774 $tagged[] = $vlan_id;
2775 sort ($tagged);
2776 $ret .= $vlanport['native'] ? $vlanport['native'] : '';
2777 $tagged_bits = array();
2778 $id_from = $id_to = 0;
2779 foreach ($tagged as $next_id)
2780 {
2781 if ($id_to)
2782 {
2783 if ($next_id == $id_to + 1) // merge
2784 {
2785 $id_to = $next_id;
2786 continue;
2787 }
2788 // flush
2789 $tagged_bits[] = $id_from == $id_to ? $id_from : "${id_from}-${id_to}";
2790 }
2791 $id_from = $id_to = $next_id; // start next pair
2792 }
2793 // pull last pair
2794 if ($id_to)
2795 $tagged_bits[] = $id_from == $id_to ? $id_from : "${id_from}-${id_to}";
2796 if (count ($tagged))
2797 $ret .= '+' . implode (', ', $tagged_bits);
2798 return strlen ($ret) ? $ret : 'default';
2799 }
2800
2801 // Decode VLAN compound key (which is a string formatted DOMAINID-VLANID) and
2802 // return the numbers as an array of two.
2803 function decodeVLANCK ($string)
2804 {
2805 $matches = array();
2806 if (1 != preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $string, $matches))
2807 throw new InvalidArgException ('VLAN compound key', $string);
2808 return array ($matches[1], $matches[2]);
2809 }
2810
2811 // Return VLAN name formatted for HTML output (note, that input
2812 // argument comes from database unescaped).
2813 function formatVLANName ($vlaninfo, $context = 'markup long')
2814 {
2815 switch ($context)
2816 {
2817 case 'option':
2818 $ret = $vlaninfo['vlan_id'];
2819 if ($vlaninfo['vlan_descr'] != '')
2820 $ret .= ' ' . niftyString ($vlaninfo['vlan_descr']);
2821 return $ret;
2822 case 'label':
2823 $ret = $vlaninfo['vlan_id'];
2824 if ($vlaninfo['vlan_descr'] != '')
2825 $ret .= ' <i>(' . niftyString ($vlaninfo['vlan_descr']) . ')</i>';
2826 return $ret;
2827 case 'plain long':
2828 $ret = 'VLAN' . $vlaninfo['vlan_id'];
2829 if ($vlaninfo['vlan_descr'] != '')
2830 $ret .= ' (' . niftyString ($vlaninfo['vlan_descr'], 20, FALSE) . ')';
2831 return $ret;
2832 case 'hyperlink':
2833 $ret = '<a href="';
2834 $ret .= makeHref (array ('page' => 'vlan', 'vlan_ck' => $vlaninfo['domain_id'] . '-' . $vlaninfo['vlan_id']));
2835 $ret .= '">' . formatVLANName ($vlaninfo, 'markup long') . '</a>';
2836 return $ret;
2837 case 'markup long':
2838 default:
2839 $ret = 'VLAN' . $vlaninfo['vlan_id'];
2840 $ret .= ' @' . niftyString ($vlaninfo['domain_descr']);
2841 if ($vlaninfo['vlan_descr'] != '')
2842 $ret .= ' <i>(' . niftyString ($vlaninfo['vlan_descr']) . ')</i>';
2843 return $ret;
2844 }
2845 }
2846
2847 // map interface name
2848 function ios12ShortenIfName ($ifname)
2849 {
2850 $ifname = preg_replace ('@^Eth(?:ernet)?(.+)$@', 'e\\1', $ifname);
2851 $ifname = preg_replace ('@^FastEthernet(.+)$@', 'fa\\1', $ifname);
2852 $ifname = preg_replace ('@^(?:GigabitEthernet|GE)(.+)$@', 'gi\\1', $ifname);
2853 $ifname = preg_replace ('@^TenGigabitEthernet(.+)$@', 'te\\1', $ifname);
2854 $ifname = preg_replace ('@^Port-channel(.+)$@', 'po\\1', $ifname);
2855 $ifname = preg_replace ('@^(?:XGigabitEthernet|XGE)(.+)$@', 'xg\\1', $ifname);
2856 $ifname = strtolower ($ifname);
2857 return $ifname;
2858 }
2859
2860 function iosParseVLANString ($string)
2861 {
2862 $ret = array();
2863 foreach (explode (',', $string) as $item)
2864 {
2865 $matches = array();
2866 $item = trim ($item, ' ');
2867 if (preg_match ('/^([[:digit:]]+)$/', $item, $matches))
2868 $ret[] = $matches[1];
2869 elseif (preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $item, $matches))
2870 $ret = array_merge ($ret, range ($matches[1], $matches[2]));
2871 }
2872 return $ret;
2873 }
2874
2875 // Scan given array and return the key, which addresses the first item
2876 // with requested column set to given value (or NULL if there is none such).
2877 // Note that 0 and NULL mean completely different things and thus
2878 // require strict checking (=== and !===).
2879 function scanArrayForItem ($table, $scan_column, $scan_value)
2880 {
2881 foreach ($table as $key => $row)
2882 if ($row[$scan_column] == $scan_value)
2883 return $key;
2884 return NULL;
2885 }
2886
2887 // Return TRUE, if every value of A1 is present in A2 and vice versa,
2888 // regardless of each array's sort order and indexing.
2889 function array_values_same ($a1, $a2)
2890 {
2891 return !count (array_diff ($a1, $a2)) and !count (array_diff ($a2, $a1));
2892 }
2893
2894 // Use the VLAN switch template to set VST role for each port of
2895 // the provided list. Return resulting list.
2896 function apply8021QOrder ($vst_id, $portlist)
2897 {
2898 $vst = getVLANSwitchTemplate ($vst_id);
2899 foreach (array_keys ($portlist) as $port_name)
2900 {
2901 foreach ($vst['rules'] as $rule)
2902 if (preg_match ($rule['port_pcre'], $port_name))
2903 {
2904 $portlist[$port_name]['vst_role'] = $rule['port_role'];
2905 $portlist[$port_name]['wrt_vlans'] = buildVLANFilter ($rule['port_role'], $rule['wrt_vlans']);
2906 continue 2;
2907 }
2908 $portlist[$port_name]['vst_role'] = 'none';
2909 }
2910 return $portlist;
2911 }
2912
2913 // return a sequence of ranges for given string form and port role
2914 function buildVLANFilter ($role, $string)
2915 {
2916 // set base
2917 switch ($role)
2918 {
2919 case 'access': // 1-4094
2920 $min = VLAN_MIN_ID;
2921 $max = VLAN_MAX_ID;
2922 break;
2923 case 'trunk': // 2-4094
2924 case 'uplink':
2925 case 'downlink':
2926 case 'anymode':
2927 $min = VLAN_MIN_ID + 1;
2928 $max = VLAN_MAX_ID;
2929 break;
2930 default: // none
2931 return array();
2932 }
2933 if ($string == '') // fast track
2934 return array (array ('from' => $min, 'to' => $max));
2935 // transform
2936 $vlanidlist = array();
2937 foreach (iosParseVLANString ($string) as $vlan_id)
2938 if ($min <= $vlan_id and $vlan_id <= $max)
2939 $vlanidlist[] = $vlan_id;
2940 return listToRanges ($vlanidlist);
2941 }
2942
2943 // pack set of integers into list of integer ranges
2944 // e.g. (1, 2, 3, 5, 6, 7, 9, 11) => ((1, 3), (5, 7), (9, 9), (11, 11))
2945 // The second argument, when it is different from 0, limits amount of
2946 // items in each generated range.
2947 function listToRanges ($vlanidlist, $limit = 0)
2948 {
2949 sort ($vlanidlist);
2950 $ret = array();
2951 $from = $to = NULL;
2952 foreach ($vlanidlist as $vlan_id)
2953 if ($from == NULL)
2954 {
2955 if ($limit == 1)
2956 $ret[] = array ('from' => $vlan_id, 'to' => $vlan_id);
2957 else
2958 $from = $to = $vlan_id;
2959 }
2960 elseif ($to + 1 == $vlan_id)
2961 {
2962 $to = $vlan_id;
2963 if ($to - $from + 1 == $limit)
2964 {
2965 // cut accumulated range and start over
2966 $ret[] = array ('from' => $from, 'to' => $to);
2967 $from = $to = NULL;
2968 }
2969 }
2970 else
2971 {
2972 $ret[] = array ('from' => $from, 'to' => $to);
2973 $from = $to = $vlan_id;
2974 }
2975 if ($from != NULL)
2976 $ret[] = array ('from' => $from, 'to' => $to);
2977 return $ret;
2978 }
2979
2980 // return TRUE, if given VLAN ID belongs to one of filter's ranges
2981 function matchVLANFilter ($vlan_id, $vfilter)
2982 {
2983 foreach ($vfilter as $range)
2984 if ($range['from'] <= $vlan_id and $vlan_id <= $range['to'])
2985 return TRUE;
2986 return FALSE;
2987 }
2988
2989 function generate8021QDeployOps ($domain_vlanlist, $device_vlanlist, $before, $changes)
2990 {
2991 // only ignore VLANs, which exist and are explicitly shown as "alien"
2992 $old_managed_vlans = array();
2993 foreach ($device_vlanlist as $vlan_id)
2994 if
2995 (
2996 !array_key_exists ($vlan_id, $domain_vlanlist) or
2997 $domain_vlanlist[$vlan_id]['vlan_type'] != 'alien'
2998 )
2999 $old_managed_vlans[] = $vlan_id;
3000 $ports_to_do = array();
3001 $after = $before;
3002 foreach ($changes as $port_name => $port)
3003 {
3004 $ports_to_do[$port_name] = array
3005 (
3006 'old_mode' => $before[$port_name]['mode'],
3007 'old_allowed' => $before[$port_name]['allowed'],
3008 'old_native' => $before[$port_name]['native'],
3009 'new_mode' => $port['mode'],
3010 'new_allowed' => $port['allowed'],
3011 'new_native' => $port['native'],
3012 );
3013 $after[$port_name] = $port;
3014 }
3015 // New VLAN table is a union of:
3016 // 1. all compulsory VLANs
3017 // 2. all "current" non-alien allowed VLANs of those ports, which are left
3018 // intact (regardless if a VLAN exists in VLAN domain, but looking,
3019 // if it is present in device's own VLAN table)
3020 // 3. all "new" allowed VLANs of those ports, which we do "push" now
3021 // Like for old_managed_vlans, a VLANs is never listed, only if it
3022 // exists and belongs to "alien" type.
3023 $new_managed_vlans = array();
3024 // 1
3025 foreach ($domain_vlanlist as $vlan_id => $vlan)
3026 if ($vlan['vlan_type'] == 'compulsory')
3027 $new_managed_vlans[] = $vlan_id;
3028 // 2
3029 foreach ($before as $port_name => $port)
3030 if (!array_key_exists ($port_name, $changes))
3031 foreach ($port['allowed'] as $vlan_id)
3032 {
3033 if (in_array ($vlan_id, $new_managed_vlans))
3034 continue;
3035 if
3036 (
3037 array_key_exists ($vlan_id, $domain_vlanlist) and
3038 $domain_vlanlist[$vlan_id]['vlan_type'] == 'alien'
3039 )
3040 continue;
3041 if (in_array ($vlan_id, $device_vlanlist))
3042 $new_managed_vlans[] = $vlan_id;
3043 }
3044 // 3
3045 foreach ($changes as $port)
3046 foreach ($port['allowed'] as $vlan_id)
3047 if
3048 (
3049 $domain_vlanlist[$vlan_id]['vlan_type'] == 'ondemand' and
3050 !in_array ($vlan_id, $new_managed_vlans)
3051 )
3052 $new_managed_vlans[] = $vlan_id;
3053 $crq = array();
3054 // Before removing each old VLAN as such it is necessary to unassign
3055 // ports from it (to remove VLAN from each ports' list of "allowed"
3056 // VLANs). This change in turn requires, that a port's "native"
3057 // VLAN isn't set to the one being removed from its "allowed" list.
3058 foreach ($ports_to_do as $port_name => $port)
3059 switch ($port['old_mode'] . '->' . $port['new_mode'])
3060 {
3061 case 'trunk->trunk':
3062 // "old" native is set and differs from the "new" native
3063 if ($port['old_native'] and $port['old_native'] != $port['new_native'])
3064 $crq[] = array
3065 (
3066 'opcode' => 'unset native',
3067 'arg1' => $port_name,
3068 'arg2' => $port['old_native'],
3069 );
3070 if (count ($tmp = array_diff ($port['old_allowed'], $port['new_allowed'])))
3071 $crq[] = array
3072 (
3073 'opcode' => 'rem allowed',
3074 'port' => $port_name,
3075 'vlans' => $tmp,
3076 );
3077 break;
3078 case 'access->access':
3079 if ($port['old_native'] and $port['old_native'] != $port['new_native'])
3080 $crq[] = array
3081 (
3082 'opcode' => 'unset access',
3083 'arg1' => $port_name,
3084 'arg2' => $port['old_native'],
3085 );
3086 break;
3087 case 'access->trunk':
3088 $crq[] = array
3089 (
3090 'opcode' => 'unset access',
3091 'arg1' => $port_name,
3092 'arg2' => $port['old_native'],
3093 );
3094 break;
3095 case 'trunk->access':
3096 if ($port['old_native'])
3097 $crq[] = array
3098 (
3099 'opcode' => 'unset native',
3100 'arg1' => $port_name,
3101 'arg2' => $port['old_native'],
3102 );
3103 if (count ($port['old_allowed']))
3104 $crq[] = array
3105 (
3106 'opcode' => 'rem allowed',
3107 'port' => $port_name,
3108 'vlans' => $port['old_allowed'],
3109 );
3110 break;
3111 default:
3112 throw new InvalidArgException ('ports_to_do', '(hidden)', 'error in structure');
3113 }
3114 // Now it is safe to unconfigure VLANs, which still exist on device,
3115 // but are not present on the "new" list.
3116 // FIXME: put all IDs into one pseudo-command to make it easier
3117 // for translators to create/destroy VLANs in batches, where
3118 // target platform allows them to do.
3119 foreach (array_diff ($old_managed_vlans, $new_managed_vlans) as $vlan_id)
3120 $crq[] = array
3121 (
3122 'opcode' => 'destroy VLAN',
3123 'arg1' => $vlan_id,
3124 );
3125 // Configure VLANs, which must be present on the device, but are not yet.
3126 foreach (array_diff ($new_managed_vlans, $old_managed_vlans) as $vlan_id)
3127 $crq[] = array
3128 (
3129 'opcode' => 'create VLAN',
3130 'arg1' => $vlan_id,
3131 );
3132 // Now, when all new VLANs are created (queued), it is safe to assign (queue)
3133 // ports to the new VLANs.
3134 foreach ($ports_to_do as $port_name => $port)
3135 switch ($port['old_mode'] . '->' . $port['new_mode'])
3136 {
3137 case 'trunk->trunk':
3138 // For each allowed VLAN, which is present on the "new" list and missing from
3139 // the "old" one, queue a command to assign current port to that VLAN.
3140 if (count ($tmp = array_diff ($port['new_allowed'], $port['old_allowed'])))
3141 $crq[] = array
3142 (
3143 'opcode' => 'add allowed',
3144 'port' => $port_name,
3145 'vlans' => $tmp,
3146 );
3147 // One of the "allowed" VLANs for this port may probably be "native".
3148 // "new native" is set and differs from "old native"
3149 if ($port['new_native'] and $port['new_native'] != $port['old_native'])
3150 $crq[] = array
3151 (
3152 'opcode' => 'set native',
3153 'arg1' => $port_name,
3154 'arg2' => $port['new_native'],
3155 );
3156 break;
3157 case 'access->access':
3158 if ($port['new_native'] and $port['new_native'] != $port['old_native'])
3159 $crq[] = array
3160 (
3161 'opcode' => 'set access',
3162 'arg1' => $port_name,
3163 'arg2' => $port['new_native'],
3164 );
3165 break;
3166 case 'access->trunk':
3167 $crq[] = array
3168 (
3169 'opcode' => 'set mode',
3170 'arg1' => $port_name,
3171 'arg2' => $port['new_mode'],
3172 );
3173 if (count ($port['new_allowed']))
3174 $crq[] = array
3175 (
3176 'opcode' => 'add allowed',
3177 'port' => $port_name,
3178 'vlans' => $port['new_allowed'],
3179 );
3180 if ($port['new_native'])
3181 $crq[] = array
3182 (
3183 'opcode' => 'set native',
3184 'arg1' => $port_name,
3185 'arg2' => $port['new_native'],
3186 );
3187 break;
3188 case 'trunk->access':
3189 $crq[] = array
3190 (
3191 'opcode' => 'set mode',
3192 'arg1' => $port_name,
3193 'arg2' => $port['new_mode'],
3194 );
3195 $crq[] = array
3196 (
3197 'opcode' => 'set access',
3198 'arg1' => $port_name,
3199 'arg2' => $port['new_native'],
3200 );
3201 break;
3202 default:
3203 throw new InvalidArgException ('ports_to_do', '(hidden)', 'error in structure');
3204 }
3205 return $crq;
3206 }
3207
3208 function exportSwitch8021QConfig
3209 (
3210 $vswitch,
3211 $device_vlanlist,
3212 $before,
3213 $changes
3214 )
3215 {
3216 $domain_vlanlist = getDomainVLANs ($vswitch['domain_id']);
3217 $crq = generate8021QDeployOps ($domain_vlanlist, $device_vlanlist, $before,