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