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