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