r3314 repeat Tyler's patch for trunk
[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
e673ee24
DO
162// Objects of some types should be explicitly shown as
163// anonymous (labelless). This function is a single place where the
164// decision about displayed name is made.
cfa8f3cf 165function setDisplayedName (&$cell)
e673ee24 166{
cfa8f3cf
DO
167 if ($cell['name'] != '')
168 $cell['dname'] = $cell['name'];
e673ee24 169 else
212c9d8a 170 {
cfa8f3cf
DO
171 $cell['atags'][] = array ('tag' => '$nameless');
172 if (considerConfiguredConstraint ($cell, 'NAMEWARN_LISTSRC'))
7fa7047a 173 $cell['dname'] = 'ANONYMOUS ' . decodeObjectType ($cell['objtype_id'], 'o');
212c9d8a 174 else
7fa7047a 175 $cell['dname'] = '[' . decodeObjectType ($cell['objtype_id'], 'o') . ']';
212c9d8a 176 }
e673ee24
DO
177}
178
179// This function finds height of solid rectangle of atoms, which are all
180// assigned to the same object. Rectangle base is defined by specified
181// template.
182function rectHeight ($rackData, $startRow, $template_idx)
183{
184 $height = 0;
185 // The first met object_id is used to match all the folowing IDs.
186 $object_id = 0;
187 global $template;
188 do
189 {
190 for ($locidx = 0; $locidx < 3; $locidx++)
191 {
192 // At least one value in template is TRUE, but the following block
193 // can meet 'skipped' atoms. Let's ensure we have something after processing
194 // the first row.
195 if ($template[$template_idx][$locidx])
196 {
197 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
198 break 2;
93e02204
DO
199 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
200 break 2;
201 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
202 break 2;
e673ee24
DO
203 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
204 break 2;
205 if ($object_id == 0)
206 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
207 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
208 break 2;
209 }
210 }
211 // If the first row can't offer anything, bail out.
212 if ($height == 0 and $object_id == 0)
213 break;
214 $height++;
215 }
216 while ($startRow - $height > 0);
93e02204
DO
217# echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
218# echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
219# echo ") height==${height}<br>\n";
e673ee24
DO
220 return $height;
221}
222
223// This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
224// attributes.
225function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
226{
227 global $template, $templateWidth;
228 $colspan = 0;
229 for ($height = 0; $height < $maxheight; $height++)
230 {
231 for ($locidx = 0; $locidx < 3; $locidx++)
232 {
233 if ($template[$template_idx][$locidx])
234 {
235 // Add colspan/rowspan to the first row met and mark the following ones to skip.
93e02204
DO
236 // Explicitly show even single-cell spanned atoms, because rectHeight()
237 // is expeciting this data for correct calculation.
e673ee24
DO
238 if ($colspan != 0)
239 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
240 else
241 {
242 $colspan = $templateWidth[$template_idx];
93e02204 243 if ($colspan >= 1)
e673ee24 244 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
93e02204 245 if ($maxheight >= 1)
e673ee24
DO
246 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
247 }
248 }
249 }
250 }
251 return;
252}
253
93e02204
DO
254// This function sets rowspan/solspan/skipped atom attributes for renderRack()
255// What we actually have to do is to find _all_ possible rectangles for each unit
256// and then select the widest of those with the maximal square.
e673ee24
DO
257function markAllSpans (&$rackData = NULL)
258{
259 if ($rackData == NULL)
260 {
0cc24e9a 261 showWarning ('Invalid rackData', __FUNCTION__);
e673ee24
DO
262 return;
263 }
264 for ($i = $rackData['height']; $i > 0; $i--)
93e02204
DO
265 while (markBestSpan ($rackData, $i));
266}
267
268// Calculate height of 6 possible span templates (array is presorted by width
269// descending) and mark the best (if any).
270function markBestSpan (&$rackData, $i)
271{
272 global $template, $templateWidth;
273 for ($j = 0; $j < 6; $j++)
e673ee24 274 {
93e02204
DO
275 $height[$j] = rectHeight ($rackData, $i, $j);
276 $square[$j] = $height[$j] * $templateWidth[$j];
277 }
278 // find the widest rectangle of those with maximal height
279 $maxsquare = max ($square);
280 if (!$maxsquare)
281 return FALSE;
282 $best_template_index = 0;
283 for ($j = 0; $j < 6; $j++)
284 if ($square[$j] == $maxsquare)
e673ee24 285 {
93e02204
DO
286 $best_template_index = $j;
287 $bestheight = $height[$j];
288 break;
e673ee24 289 }
93e02204
DO
290 // distribute span marks
291 markSpan ($rackData, $i, $bestheight, $best_template_index);
292 return TRUE;
e673ee24
DO
293}
294
e673ee24
DO
295// We can mount 'F' atoms and unmount our own 'T' atoms.
296function applyObjectMountMask (&$rackData, $object_id)
297{
298 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
299 for ($locidx = 0; $locidx < 3; $locidx++)
300 switch ($rackData[$unit_no][$locidx]['state'])
301 {
302 case 'F':
303 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
304 break;
305 case 'T':
306 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
307 break;
308 default:
309 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
310 }
311}
312
313// Design change means transition between 'F' and 'A' and back.
314function applyRackDesignMask (&$rackData)
315{
316 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
317 for ($locidx = 0; $locidx < 3; $locidx++)
318 switch ($rackData[$unit_no][$locidx]['state'])
319 {
320 case 'F':
321 case 'A':
322 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
323 break;
324 default:
325 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
326 }
327}
328
329// The same for 'F' and 'U'.
330function applyRackProblemMask (&$rackData)
331{
332 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
333 for ($locidx = 0; $locidx < 3; $locidx++)
334 switch ($rackData[$unit_no][$locidx]['state'])
335 {
336 case 'F':
337 case 'U':
338 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
339 break;
340 default:
341 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
342 }
343}
344
e673ee24
DO
345// This function highlights specified object (and removes previous highlight).
346function highlightObject (&$rackData, $object_id)
347{
348 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
349 for ($locidx = 0; $locidx < 3; $locidx++)
350 if
351 (
352 $rackData[$unit_no][$locidx]['state'] == 'T' and
353 $rackData[$unit_no][$locidx]['object_id'] == $object_id
354 )
355 $rackData[$unit_no][$locidx]['hl'] = 'h';
356 else
357 unset ($rackData[$unit_no][$locidx]['hl']);
358}
359
360// This function marks atoms to selected or not depending on their current state.
361function markupAtomGrid (&$data, $checked_state)
362{
363 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
364 for ($locidx = 0; $locidx < 3; $locidx++)
365 {
366 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
367 continue;
368 if ($data[$unit_no][$locidx]['state'] == $checked_state)
369 $data[$unit_no][$locidx]['checked'] = ' checked';
370 else
371 $data[$unit_no][$locidx]['checked'] = '';
372 }
373}
374
375// This function is almost a clone of processGridForm(), but doesn't save anything to database
376// Return value is the changed rack data.
377// Here we assume that correct filter has already been applied, so we just
378// set or unset checkbox inputs w/o changing atom state.
379function mergeGridFormToRack (&$rackData)
380{
381 $rack_id = $rackData['id'];
382 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
383 for ($locidx = 0; $locidx < 3; $locidx++)
384 {
385 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
386 continue;
387 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
388 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
389 $rackData[$unit_no][$locidx]['checked'] = ' checked';
390 else
391 $rackData[$unit_no][$locidx]['checked'] = '';
392 }
393}
394
bb0a44e9 395// netmask conversion from length to number
e673ee24
DO
396function binMaskFromDec ($maskL)
397{
bb0a44e9
DO
398 $map_straight = array (
399 0 => 0x00000000,
400 1 => 0x80000000,
401 2 => 0xc0000000,
402 3 => 0xe0000000,
403 4 => 0xf0000000,
404 5 => 0xf8000000,
405 6 => 0xfc000000,
406 7 => 0xfe000000,
407 8 => 0xff000000,
408 9 => 0xff800000,
409 10 => 0xffc00000,
410 11 => 0xffe00000,
411 12 => 0xfff00000,
412 13 => 0xfff80000,
413 14 => 0xfffc0000,
414 15 => 0xfffe0000,
415 16 => 0xffff0000,
416 17 => 0xffff8000,
417 18 => 0xffffc000,
418 19 => 0xffffe000,
419 20 => 0xfffff000,
420 21 => 0xfffff800,
421 22 => 0xfffffc00,
422 23 => 0xfffffe00,
423 24 => 0xffffff00,
424 25 => 0xffffff80,
425 26 => 0xffffffc0,
426 27 => 0xffffffe0,
427 28 => 0xfffffff0,
428 29 => 0xfffffff8,
429 30 => 0xfffffffc,
430 31 => 0xfffffffe,
431 32 => 0xffffffff,
432 );
433 return $map_straight[$maskL];
e673ee24
DO
434}
435
bb0a44e9 436// complementary value
e673ee24
DO
437function binInvMaskFromDec ($maskL)
438{
bb0a44e9
DO
439 $map_compl = array (
440 0 => 0xffffffff,
441 1 => 0x7fffffff,
442 2 => 0x3fffffff,
443 3 => 0x1fffffff,
444 4 => 0x0fffffff,
445 5 => 0x07ffffff,
446 6 => 0x03ffffff,
447 7 => 0x01ffffff,
448 8 => 0x00ffffff,
449 9 => 0x007fffff,
450 10 => 0x003fffff,
451 11 => 0x001fffff,
452 12 => 0x000fffff,
453 13 => 0x0007ffff,
454 14 => 0x0003ffff,
455 15 => 0x0001ffff,
456 16 => 0x0000ffff,
457 17 => 0x00007fff,
458 18 => 0x00003fff,
459 19 => 0x00001fff,
460 20 => 0x00000fff,
461 21 => 0x000007ff,
462 22 => 0x000003ff,
463 23 => 0x000001ff,
464 24 => 0x000000ff,
465 25 => 0x0000007f,
466 26 => 0x0000003f,
467 27 => 0x0000001f,
468 28 => 0x0000000f,
469 29 => 0x00000007,
470 30 => 0x00000003,
471 31 => 0x00000001,
472 32 => 0x00000000,
473 );
474 return $map_compl[$maskL];
e673ee24
DO
475}
476
e673ee24
DO
477// This function looks up 'has_problems' flag for 'T' atoms
478// and modifies 'hl' key. May be, this should be better done
61a1d996 479// in amplifyCell(). We don't honour 'skipped' key, because
e673ee24
DO
480// the function is also used for thumb creation.
481function markupObjectProblems (&$rackData)
482{
483 for ($i = $rackData['height']; $i > 0; $i--)
484 for ($locidx = 0; $locidx < 3; $locidx++)
485 if ($rackData[$i][$locidx]['state'] == 'T')
486 {
6297d584 487 $object = spotEntity ('object', $rackData[$i][$locidx]['object_id']);
e673ee24
DO
488 if ($object['has_problems'] == 'yes')
489 {
490 // Object can be already highlighted.
491 if (isset ($rackData[$i][$locidx]['hl']))
492 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
493 else
494 $rackData[$i][$locidx]['hl'] = 'w';
495 }
496 }
497}
498
d516d719
DO
499// Return a uniformly (010203040506 or 0102030405060708) formatted address, if it is present
500// in the provided string, an empty string for an empty string or NULL for error.
e673ee24
DO
501function l2addressForDatabase ($string)
502{
e673ee24 503 $string = strtoupper ($string);
05771508
DO
504 switch (TRUE)
505 {
d516d719 506 case ($string == '' or preg_match (RE_L2_SOLID, $string) or preg_match (RE_L2_WWN_SOLID, $string)):
05771508 507 return $string;
d516d719
DO
508 case (preg_match (RE_L2_IFCFG, $string) or preg_match (RE_L2_WWN_COLON, $string)):
509 // reformat output of SunOS ifconfig
510 $ret = '';
511 foreach (explode (':', $string) as $byte)
512 $ret .= (strlen ($byte) == 1 ? '0' : '') . $byte;
513 return $ret;
05771508 514 case (preg_match (RE_L2_CISCO, $string)):
d516d719
DO
515 return str_replace ('.', '', $string);
516 case (preg_match (RE_L2_IPCFG, $string) or preg_match (RE_L2_WWN_HYPHEN, $string)):
517 return str_replace ('-', '', $string);
05771508
DO
518 default:
519 return NULL;
520 }
e673ee24
DO
521}
522
523function l2addressFromDatabase ($string)
524{
525 switch (strlen ($string))
526 {
527 case 12: // Ethernet
d516d719 528 case 16: // FireWire/Fibre Channel
e673ee24
DO
529 $ret = implode (':', str_split ($string, 2));
530 break;
531 default:
532 $ret = $string;
533 break;
534 }
535 return $ret;
536}
537
538// The following 2 functions return previous and next rack IDs for
539// a given rack ID. The order of racks is the same as in renderRackspace()
540// or renderRow().
541function getPrevIDforRack ($row_id = 0, $rack_id = 0)
542{
543 if ($row_id <= 0 or $rack_id <= 0)
544 {
0cc24e9a 545 showWarning ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
546 return NULL;
547 }
a8efc03e 548 $rackList = listCells ('rack', $row_id);
e673ee24
DO
549 doubleLink ($rackList);
550 if (isset ($rackList[$rack_id]['prev_key']))
551 return $rackList[$rack_id]['prev_key'];
552 return NULL;
553}
554
555function getNextIDforRack ($row_id = 0, $rack_id = 0)
556{
557 if ($row_id <= 0 or $rack_id <= 0)
558 {
0cc24e9a 559 showWarning ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
560 return NULL;
561 }
a8efc03e 562 $rackList = listCells ('rack', $row_id);
e673ee24
DO
563 doubleLink ($rackList);
564 if (isset ($rackList[$rack_id]['next_key']))
565 return $rackList[$rack_id]['next_key'];
566 return NULL;
567}
568
569// This function finds previous and next array keys for each array key and
570// modifies its argument accordingly.
571function doubleLink (&$array)
572{
573 $prev_key = NULL;
574 foreach (array_keys ($array) as $key)
575 {
576 if ($prev_key)
577 {
578 $array[$key]['prev_key'] = $prev_key;
579 $array[$prev_key]['next_key'] = $key;
580 }
581 $prev_key = $key;
582 }
583}
584
e673ee24
DO
585function sortTokenize ($a, $b)
586{
587 $aold='';
588 while ($a != $aold)
589 {
590 $aold=$a;
591 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
592 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
593 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
594 }
595
596 $bold='';
597 while ($b != $bold)
598 {
599 $bold=$b;
600 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
601 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
602 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
603 }
604
605
606
607 $ar = explode(' ', $a);
608 $br = explode(' ', $b);
609 for ($i=0; $i<count($ar) && $i<count($br); $i++)
610 {
611 $ret = 0;
612 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
613 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
614 else
615 $ret = strcasecmp($ar[$i], $br[$i]);
616 if ($ret != 0)
617 return $ret;
618 }
619 if ($i<count($ar))
620 return 1;
621 if ($i<count($br))
622 return -1;
623 return 0;
624}
625
626function sortByName ($a, $b)
627{
628 return sortTokenize($a['name'], $b['name']);
629}
630
e673ee24
DO
631function sortObjectAddressesAndNames ($a, $b)
632{
633 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
634 if ($objname_cmp == 0)
635 {
79f22c3d
DO
636 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
637 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
638 $objname_cmp = sortTokenize($name_a, $name_b);
e673ee24 639 if ($objname_cmp == 0)
e673ee24 640 sortTokenize($a['ip'], $b['ip']);
e673ee24
DO
641 return $objname_cmp;
642 }
643 return $objname_cmp;
644}
645
c31cd72c 646// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
647// if FQDN is set. The next choice is object's common name, if it looks like a
648// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 649// object is returned (which may appear 0 and more elements long).
f321b50a 650function findAllEndpoints ($object_id, $fallback = '')
c31cd72c 651{
7fa7047a
DO
652 foreach (getAttrValues ($object_id) as $record)
653 if ($record['id'] == 3 && strlen ($record['value'])) // FQDN
c31cd72c 654 return array ($record['value']);
c31cd72c 655 $regular = array();
85970da2
DO
656 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
657 if ($alloc['type'] == 'regular')
658 $regular[] = $dottedquad;
59a83bd8 659 if (!count ($regular) && strlen ($fallback))
f321b50a 660 return array ($fallback);
c31cd72c
DO
661 return $regular;
662}
663
83ba6670
DO
664// Some records in the dictionary may be written as plain text or as Wiki
665// link in the following syntax:
666// 1. word
667// 2. [[word URL]] // FIXME: this isn't working
668// 3. [[word word word | URL]]
669// This function parses the line and returns text suitable for either A
670// (rendering <A HREF>) or O (for <OPTION>).
7fa7047a 671function parseWikiLink ($line, $which)
83ba6670 672{
010231c2 673 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af 674 {
7fa7047a
DO
675 // always strip the marker for A-data, but let cookOptgroup()
676 // do this later (otherwise it can't sort groups out)
677 if ($which == 'a')
f0b540a3 678 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
24cbe8af
DO
679 else
680 return $line;
681 }
010231c2
DO
682 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
683 $s = explode ('|', $line);
83ba6670 684 $o_value = trim ($s[0]);
83ba6670
DO
685 if ($which == 'o')
686 return $o_value;
7fa7047a
DO
687 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
688 $a_value = trim ($s[1]);
689 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
690}
691
c9edf725
DO
692// FIXME: should this be saved as "P-data"?
693function execGMarker ($line)
694{
695 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
696}
697
177b1e9b
DO
698// rackspace usage for a single rack
699// (T + W + U) / (height * 3 - A)
11df133a 700function getRSUforRack ($data = NULL)
177b1e9b 701{
11df133a 702 if ($data == NULL)
177b1e9b 703 {
0cc24e9a 704 showWarning ('Invalid argument', __FUNCTION__);
177b1e9b
DO
705 return NULL;
706 }
6ffba290 707 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
708 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
709 for ($locidx = 0; $locidx < 3; $locidx++)
710 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 711 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
712}
713
11df133a
DO
714// Same for row.
715function getRSUforRackRow ($rowData = NULL)
716{
bb26a59e 717 if ($rowData === NULL)
11df133a 718 {
0cc24e9a 719 showWarning ('Invalid argument', __FUNCTION__);
11df133a
DO
720 return NULL;
721 }
bb26a59e
DO
722 if (!count ($rowData))
723 return 0;
11df133a 724 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 725 $total_height = 0;
dfa3c075
DO
726 foreach (array_keys ($rowData) as $rack_id)
727 {
61a1d996
DO
728 $data = spotEntity ('rack', $rack_id);
729 amplifyCell ($data);
dfa3c075 730 $total_height += $data['height'];
11df133a
DO
731 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
732 for ($locidx = 0; $locidx < 3; $locidx++)
733 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
734 }
735 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
736}
737
9af110b4
DO
738// Make sure the string is always wrapped with LF characters
739function lf_wrap ($str)
740{
741 $ret = trim ($str, "\r\n");
59a83bd8 742 if (strlen ($ret))
9af110b4
DO
743 $ret .= "\n";
744 return $ret;
745}
746
e6e7d8b3
DO
747// Adopted from Mantis BTS code.
748function string_insert_hrefs ($s)
749{
750 if (getConfigVar ('DETECT_URLS') != 'yes')
751 return $s;
752 # Find any URL in a string and replace it by a clickable link
753 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
754 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
755 $s);
756 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
757 '<a href="mailto:\0">\0</a>',
758 $s);
759 return $s;
760}
761
762// Idem.
763function email_regex_simple ()
764{
765 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
766 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
767}
768
118e4c38
DO
769// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
770// for the requested object_type_id.
771function getAutoPorts ($type_id)
772{
773 $ret = array();
774 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
775 foreach ($typemap as $equation)
776 {
777 $tmp = explode ('=', $equation);
778 if (count ($tmp) != 2)
779 continue;
780 $objtype_id = $tmp[0];
781 if ($objtype_id != $type_id)
782 continue;
783 $portlist = $tmp[1];
784 foreach (explode ('+', $portlist) as $product)
785 {
786 $tmp = explode ('*', $product);
787 if (count ($tmp) != 3)
788 continue;
789 $nports = $tmp[0];
790 $port_type = $tmp[1];
791 $format = $tmp[2];
792 for ($i = 0; $i < $nports; $i++)
793 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
794 }
795 }
796 return $ret;
797}
798
86256b96
DO
799// Use pre-served trace to traverse the tree, then place given node where it belongs.
800function pokeNode (&$tree, $trace, $key, $value, $threshold = 0)
801{
802 // This function needs the trace to be followed FIFO-way. The fastest
803 // way to do so is to use array_push() for putting values into the
804 // list and array_shift() for getting them out. This exposed up to 11%
805 // performance gain compared to other patterns of array_push/array_unshift/
806 // array_reverse/array_pop/array_shift conjunction.
807 $myid = array_shift ($trace);
808 if (!count ($trace)) // reached the target
9dfd4cc9 809 {
86256b96
DO
810 if (!$threshold or ($threshold and $tree[$myid]['kidc'] + 1 < $threshold))
811 $tree[$myid]['kids'][$key] = $value;
812 // Reset accumulated records once, when the limit is reached, not each time
813 // after that.
814 if (++$tree[$myid]['kidc'] == $threshold)
815 $tree[$myid]['kids'] = array();
816 }
817 else // not yet
818 {
819 $self = __FUNCTION__;
820 $self ($tree[$myid]['kids'], $trace, $key, $value, $threshold);
9dfd4cc9 821 }
9dfd4cc9
DO
822}
823
0ba76ca2
DO
824// Likewise traverse the tree with the trace and return the final node.
825function peekNode ($tree, $trace, $target_id)
826{
827 $self = __FUNCTION__;
828 if (NULL === ($next = array_shift ($trace))) // warm
829 {
830 foreach ($tree as $node)
f1e27fe5 831 if (array_key_exists ('id', $node) and $node['id'] == $target_id) // hot
0ba76ca2
DO
832 return $node;
833 }
834 else // cold
835 {
836 foreach ($tree as $node)
3e576410 837 if (array_key_exists ('id', $node) and $node['id'] == $next) // warmer
0ba76ca2
DO
838 return $self ($node['kids'], $trace, $target_id);
839 }
840 // HCF
841 return NULL;
842}
843
d65353ad
DO
844// Build a tree from the item list and return it. Input and output data is
845// indexed by item id (nested items in output are recursively stored in 'kids'
51b6651a
DO
846// key, which is in turn indexed by id. Functions, which are ready to handle
847// tree collapsion/expansion themselves, may request non-zero threshold value
848// for smaller resulting tree.
3fb336f6 849function treeFromList (&$orig_nodelist, $threshold = 0, $return_main_payload = TRUE)
d65353ad 850{
86256b96 851 $tree = array();
3fb336f6 852 $nodelist = $orig_nodelist;
86256b96
DO
853 // Array equivalent of traceEntity() function.
854 $trace = array();
855 // set kidc and kids only once
856 foreach (array_keys ($nodelist) as $nodeid)
857 {
858 $nodelist[$nodeid]['kidc'] = 0;
859 $nodelist[$nodeid]['kids'] = array();
860 }
861 do
9dfd4cc9 862 {
86256b96
DO
863 $nextpass = FALSE;
864 foreach (array_keys ($nodelist) as $nodeid)
9dfd4cc9 865 {
86256b96
DO
866 // When adding a node to the working tree, book another
867 // iteration, because the new item could make a way for
868 // others onto the tree. Also remove any item added from
869 // the input list, so iteration base shrinks.
870 // First check if we can assign directly.
871 if ($nodelist[$nodeid]['parent_id'] == NULL)
9dfd4cc9 872 {
86256b96
DO
873 $tree[$nodeid] = $nodelist[$nodeid];
874 $trace[$nodeid] = array(); // Trace to root node is empty
875 unset ($nodelist[$nodeid]);
876 $nextpass = TRUE;
9dfd4cc9 877 }
86256b96
DO
878 // Now look if it fits somewhere on already built tree.
879 elseif (isset ($trace[$nodelist[$nodeid]['parent_id']]))
9dfd4cc9 880 {
86256b96
DO
881 // Trace to a node is a trace to its parent plus parent id.
882 $trace[$nodeid] = $trace[$nodelist[$nodeid]['parent_id']];
883 $trace[$nodeid][] = $nodelist[$nodeid]['parent_id'];
884 pokeNode ($tree, $trace[$nodeid], $nodeid, $nodelist[$nodeid], $threshold);
885 // path to any other node is made of all parent nodes plus the added node itself
886 unset ($nodelist[$nodeid]);
887 $nextpass = TRUE;
9dfd4cc9
DO
888 }
889 }
9dfd4cc9 890 }
86256b96 891 while ($nextpass);
3fb336f6 892 if (!$return_main_payload)
86256b96 893 return $nodelist;
3fb336f6
DO
894 // update each input node with its backtrace route
895 foreach ($trace as $nodeid => $route)
896 $orig_nodelist[$nodeid]['trace'] = $route;
897 return $tree;
9dfd4cc9
DO
898}
899
49fb1027 900// Build a tree from the tag list and return everything _except_ the tree.
573214e0
DO
901// IOW, return taginfo items, which have parent_id set and pointing outside
902// of the "normal" tree, which originates from the root.
49fb1027
DO
903function getOrphanedTags ()
904{
905 global $taglist;
86256b96 906 return treeFromList ($taglist, 0, FALSE);
49fb1027
DO
907}
908
6e49bd1f 909function serializeTags ($chain, $baseurl = '')
ba93bd98
DO
910{
911 $comma = '';
912 $ret = '';
6e49bd1f 913 foreach ($chain as $taginfo)
ba93bd98 914 {
e2ac59cf 915 $ret .= $comma .
a8efc03e 916 ($baseurl == '' ? '' : "<a href='${baseurl}cft[]=${taginfo['id']}'>") .
e2ac59cf
DO
917 $taginfo['tag'] .
918 ($baseurl == '' ? '' : '</a>');
ba93bd98
DO
919 $comma = ', ';
920 }
921 return $ret;
922}
923
ba93bd98
DO
924// Return the list of missing implicit tags.
925function getImplicitTags ($oldtags)
926{
3fb336f6
DO
927 global $taglist;
928 $tmp = array();
929 foreach ($oldtags as $taginfo)
930 $tmp = array_merge ($tmp, $taglist[$taginfo['id']]['trace']);
931 // don't call array_unique here, it is in the function we will call now
932 return buildTagChainFromIds ($tmp);
ba93bd98
DO
933}
934
6e49bd1f 935// Minimize the chain: exclude all implicit tags and return the result.
5fd2a004
DO
936// This function makes use of an external cache with a miss/hit ratio
937// about 3/7 (ticket:255).
3fb336f6 938function getExplicitTagsOnly ($chain)
ab379543 939{
5fd2a004 940 global $taglist, $tagRelCache;
ab379543 941 $ret = array();
5fd2a004
DO
942 foreach (array_keys ($chain) as $keyA) // check each A
943 {
944 $tagidA = $chain[$keyA]['id'];
945 // do not include A in result, if A is seen on the trace of any B!=A
946 foreach (array_keys ($chain) as $keyB)
947 {
948 $tagidB = $chain[$keyB]['id'];
949 if ($tagidA == $tagidB)
950 continue;
951 if (!isset ($tagRelCache[$tagidA][$tagidB]))
0745db4d 952 $tagRelCache[$tagidA][$tagidB] = in_array ($tagidA, $taglist[$tagidB]['trace']);
5fd2a004
DO
953 if ($tagRelCache[$tagidA][$tagidB] === TRUE) // A is ancestor of B
954 continue 2; // skip this A
955 }
956 $ret[] = $chain[$keyA];
957 }
74ccacff
DO
958 return $ret;
959}
960
2c21a10c 961// Universal autotags generator, a complementing function for loadEntityTags().
2c21a10c 962// Bypass key isn't strictly typed, but interpreted depending on the realm.
d16af52f 963function generateEntityAutoTags ($cell)
cce6b057 964{
cce6b057 965 $ret = array();
d16af52f 966 switch ($cell['realm'])
2c21a10c
DO
967 {
968 case 'rack':
d16af52f 969 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
2c21a10c
DO
970 $ret[] = array ('tag' => '$any_rack');
971 break;
4c9d35ec 972 case 'object':
d16af52f
DO
973 $ret[] = array ('tag' => '$id_' . $cell['id']);
974 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
2c21a10c 975 $ret[] = array ('tag' => '$any_object');
588b2b79 976 if (validTagName ('$cn_' . $cell['name'], TRUE))
d16af52f
DO
977 $ret[] = array ('tag' => '$cn_' . $cell['name']);
978 if (!strlen ($cell['rack_id']))
914b439b 979 $ret[] = array ('tag' => '$unmounted');
6d472f26
DO
980 if (!$cell['nports'])
981 $ret[] = array ('tag' => '$portless');
5d6de575
DO
982 if ($cell['asset_no'] == '')
983 $ret[] = array ('tag' => '$no_asset_tag');
2c21a10c 984 break;
4c9d35ec 985 case 'ipv4net':
d16af52f
DO
986 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
987 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
b9b915d5
DO
988 for ($i = 8; $i < 32; $i++)
989 {
990 // these conditions hit 1 to 3 times per each i
991 if ($cell['mask'] >= $i)
992 $ret[] = array ('tag' => '$masklen_ge_' . $i);
993 if ($cell['mask'] <= $i)
994 $ret[] = array ('tag' => '$masklen_le_' . $i);
995 if ($cell['mask'] == $i)
996 $ret[] = array ('tag' => '$masklen_eq_' . $i);
997 }
2c21a10c
DO
998 $ret[] = array ('tag' => '$any_ip4net');
999 $ret[] = array ('tag' => '$any_net');
1000 break;
1001 case 'ipv4vs':
d16af52f 1002 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
2c21a10c
DO
1003 $ret[] = array ('tag' => '$any_ipv4vs');
1004 $ret[] = array ('tag' => '$any_vs');
1005 break;
1006 case 'ipv4rspool':
d16af52f 1007 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
2c21a10c
DO
1008 $ret[] = array ('tag' => '$any_ipv4rsp');
1009 $ret[] = array ('tag' => '$any_rsp');
1010 break;
1011 case 'user':
b82cce3f
DO
1012 // {$username_XXX} autotag is generated always, but {$userid_XXX}
1013 // appears only for accounts, which exist in local database.
d16af52f
DO
1014 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
1015 if (isset ($cell['user_id']))
1016 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
2c21a10c
DO
1017 break;
1018 case 'file':
d16af52f 1019 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
2c21a10c
DO
1020 $ret[] = array ('tag' => '$any_file');
1021 break;
d16af52f 1022 default: // HCF!
2c21a10c
DO
1023 break;
1024 }
4c9d35ec
DO
1025 // {$tagless} doesn't apply to users
1026 switch ($cell['realm'])
1027 {
1028 case 'rack':
1029 case 'object':
1030 case 'ipv4net':
1031 case 'ipv4vs':
1032 case 'ipv4rspool':
1033 case 'file':
1034 if (!count ($cell['etags']))
1035 $ret[] = array ('tag' => '$untagged');
1036 break;
1037 default:
1038 break;
1039 }
f9bc186f
DO
1040 return $ret;
1041}
1042
abef7149
DO
1043// Check, if the given tag is present on the chain (will only work
1044// for regular tags with tag ID set.
1045function tagOnChain ($taginfo, $tagchain)
1046{
1047 if (!isset ($taginfo['id']))
1048 return FALSE;
1049 foreach ($tagchain as $test)
1050 if ($test['id'] == $taginfo['id'])
1051 return TRUE;
1052 return FALSE;
1053}
1054
f8821b96
DO
1055function tagNameOnChain ($tagname, $tagchain)
1056{
1057 foreach ($tagchain as $test)
1058 if ($test['tag'] == $tagname)
1059 return TRUE;
1060 return FALSE;
1061}
1062
abef7149
DO
1063// Return TRUE, if two tags chains differ (order of tags doesn't matter).
1064// Assume, that neither of the lists contains duplicates.
1065// FIXME: a faster, than O(x^2) method is possible for this calculation.
1066function tagChainCmp ($chain1, $chain2)
1067{
1068 if (count ($chain1) != count ($chain2))
1069 return TRUE;
1070 foreach ($chain1 as $taginfo1)
1071 if (!tagOnChain ($taginfo1, $chain2))
1072 return TRUE;
1073 return FALSE;
1074}
1075
0df8c52b 1076function redirectIfNecessary ()
da958e52 1077{
0df8c52b 1078 global $pageno, $tabno;
53bae67b
DO
1079 $pmap = array
1080 (
1081 'accounts' => 'userlist',
1082 'rspools' => 'ipv4rsplist',
1083 'rspool' => 'ipv4rsp',
1084 'vservices' => 'ipv4vslist',
1085 'vservice' => 'ipv4vs',
c78a40ec
DO
1086 'objects' => 'depot',
1087 'objgroup' => 'depot',
53bae67b
DO
1088 );
1089 $tmap = array();
1090 $tmap['objects']['newmulti'] = 'addmore';
1091 $tmap['objects']['newobj'] = 'addmore';
1092 $tmap['object']['switchvlans'] = 'livevlans';
1093 $tmap['object']['slb'] = 'editrspvs';
72d8ced3
DO
1094 $tmap['object']['portfwrd'] = 'nat4';
1095 $tmap['object']['network'] = 'ipv4';
53bae67b
DO
1096 if (isset ($pmap[$pageno]))
1097 redirectUser ($pmap[$pageno], $tabno);
1098 if (isset ($tmap[$pageno][$tabno]))
1099 redirectUser ($pageno, $tmap[$pageno][$tabno]);
0df8c52b
DO
1100}
1101
329ec966
DY
1102function prepareNavigation() {
1103 global
ac6b15d9 1104 $trigger,
329ec966
DY
1105 $pageno,
1106 $tabno;
1107
1108 $pageno = (isset ($_REQUEST['page'])) ? $_REQUEST['page'] : 'index';
1109
1110// Special handling of tab number to substitute the "last" index where applicable.
1111// Always show explicitly requested tab, substitute the last used name in case
1112// it is awailable, fall back to the default one.
1113
1114 if (isset ($_REQUEST['tab'])) {
1115 $tabno = $_REQUEST['tab'];
1116 // check if we accidentaly got on a dynamic tab that shouldn't be shown for this object
1117 if ( isset($trigger[$pageno][$tabno]) and !strlen($trigger[$pageno][$tabno] ()) ) {
1118 $tabno = 'default';
1119 $url = "index.php?page=$pageno&tab=$tabno&".urlizeGetParameters(array('page', 'tab'));
1120 header('Location: '.$url);
1121 exit();
1122 }
1123 } elseif (basename($_SERVER['PHP_SELF']) == 'index.php' and getConfigVar ('SHOW_LAST_TAB') == 'yes' and isset ($_SESSION['RTLT'][$pageno])) {
1124 $tabno = $_SESSION['RTLT'][$pageno];
1125 $url = "index.php?page=$pageno&tab=$tabno&".urlizeGetParameters(array('page', 'tab'));
1126 header('Location: '.$url);
1127 exit();
1128 } else {
1129 $tabno = 'default';
1130 }
1131}
1132
0df8c52b
DO
1133function fixContext ($target = NULL)
1134{
1135 global
1136 $pageno,
1137 $auto_tags,
1138 $expl_tags,
1139 $impl_tags,
1140 $target_given_tags,
1141 $user_given_tags,
1142 $etype_by_pageno,
1143 $page;
53bae67b 1144
0df8c52b
DO
1145 if ($target !== NULL)
1146 {
1147 $target_given_tags = $target['etags'];
1148 // Don't reset autochain, because auth procedures could push stuff there in.
1149 // Another important point is to ignore 'user' realm, so we don't infuse effective
1150 // context with autotags of the displayed account.
1151 if ($target['realm'] != 'user')
1152 $auto_tags = array_merge ($auto_tags, $target['atags']);
1153 }
1154 elseif (array_key_exists ($pageno, $etype_by_pageno))
53da7dca
DO
1155 {
1156 // Each page listed in the map above requires one uint argument.
0a50efb4 1157 $target_realm = $etype_by_pageno[$pageno];
0cc24e9a 1158 assertUIntArg ($page[$pageno]['bypass']);
0a50efb4 1159 $target_id = $_REQUEST[$page[$pageno]['bypass']];
b135a49d 1160 $target = spotEntity ($target_realm, $target_id);
53da7dca 1161 $target_given_tags = $target['etags'];
0df8c52b 1162 if ($target['realm'] != 'user')
53da7dca
DO
1163 $auto_tags = array_merge ($auto_tags, $target['atags']);
1164 }
4c9b513a
DO
1165 // Explicit and implicit chains should be normally empty at this point, so
1166 // overwrite the contents anyway.
1167 $expl_tags = mergeTagChains ($user_given_tags, $target_given_tags);
1168 $impl_tags = getImplicitTags ($expl_tags);
da958e52
DO
1169}
1170
abef7149
DO
1171// Take a list of user-supplied tag IDs to build a list of valid taginfo
1172// records indexed by tag IDs (tag chain).
6e49bd1f 1173function buildTagChainFromIds ($tagidlist)
ab379543 1174{
20c901a7 1175 global $taglist;
ab379543 1176 $ret = array();
abef7149 1177 foreach (array_unique ($tagidlist) as $tag_id)
ab379543
DO
1178 if (isset ($taglist[$tag_id]))
1179 $ret[] = $taglist[$tag_id];
1180 return $ret;
1181}
1182
7cc02fc1
DO
1183// Process a given tag tree and return only meaningful branches. The resulting
1184// (sub)tree will have refcnt leaves on every last branch.
a26a6ccc 1185function getObjectiveTagTree ($tree, $realm, $preselect)
7cc02fc1 1186{
51b6651a 1187 $self = __FUNCTION__;
7cc02fc1
DO
1188 $ret = array();
1189 foreach ($tree as $taginfo)
1190 {
a26a6ccc
DO
1191 $subsearch = $self ($taginfo['kids'], $realm, $preselect);
1192 // If the current node addresses something, add it to the result
1193 // regardless of how many sub-nodes it features.
1194 if
7cc02fc1 1195 (
a26a6ccc
DO
1196 isset ($taginfo['refcnt'][$realm]) or
1197 count ($subsearch) > 1 or
3fb336f6 1198 in_array ($taginfo['id'], $preselect)
a26a6ccc
DO
1199 )
1200 $ret[] = array
1201 (
1202 'id' => $taginfo['id'],
1203 'tag' => $taginfo['tag'],
1204 'parent_id' => $taginfo['parent_id'],
1205 'refcnt' => $taginfo['refcnt'],
1206 'kids' => $subsearch
1207 );
1208 else
1209 $ret = array_merge ($ret, $subsearch);
7cc02fc1
DO
1210 }
1211 return $ret;
1212}
1213
7ddb2c05
DO
1214// Get taginfo record by tag name, return NULL, if record doesn't exist.
1215function getTagByName ($target_name)
1216{
1217 global $taglist;
1218 foreach ($taglist as $taginfo)
1219 if ($taginfo['tag'] == $target_name)
1220 return $taginfo;
1221 return NULL;
1222}
1223
fc73c734
DO
1224// Merge two chains, filtering dupes out. Return the resulting superset.
1225function mergeTagChains ($chainA, $chainB)
1226{
1227 // $ret = $chainA;
1228 // Reindex by tag id in any case.
1229 $ret = array();
1230 foreach ($chainA as $tag)
1231 $ret[$tag['id']] = $tag;
1232 foreach ($chainB as $tag)
1233 if (!isset ($ret[$tag['id']]))
1234 $ret[$tag['id']] = $tag;
1235 return $ret;
1236}
1237
31c941ec
DO
1238function getCellFilter ()
1239{
7da7450c 1240 global $sic;
3d670bba 1241 if (isset ($_REQUEST['tagfilter']) and is_array ($_REQUEST['tagfilter']))
23cdc7e9
DO
1242 {
1243 $_REQUEST['cft'] = $_REQUEST['tagfilter'];
1244 unset ($_REQUEST['tagfilter']);
1245 }
3d670bba
DO
1246 $ret = array
1247 (
23cdc7e9
DO
1248 'tagidlist' => array(),
1249 'tnamelist' => array(),
1250 'pnamelist' => array(),
1251 'andor' => '',
3d670bba 1252 'text' => '',
23cdc7e9
DO
1253 'extratext' => '',
1254 'expression' => array(),
a8efc03e 1255 'urlextra' => '', // Just put text here and let makeHref call urlencode().
3d670bba 1256 );
23cdc7e9 1257 switch (TRUE)
31c941ec 1258 {
23cdc7e9
DO
1259 case (!isset ($_REQUEST['andor'])):
1260 $andor2 = getConfigVar ('FILTER_DEFAULT_ANDOR');
3d670bba 1261 break;
23cdc7e9
DO
1262 case ($_REQUEST['andor'] == 'and'):
1263 case ($_REQUEST['andor'] == 'or'):
1264 $ret['andor'] = $andor2 = $_REQUEST['andor'];
a8efc03e 1265 $ret['urlextra'] .= '&andor=' . $ret['andor'];
3d670bba
DO
1266 break;
1267 default:
0cc24e9a 1268 showWarning ('Invalid and/or switch value in submitted form', __FUNCTION__);
3d670bba 1269 return NULL;
31c941ec 1270 }
23cdc7e9
DO
1271 $andor1 = '';
1272 // Both tags and predicates, which don't exist, should be
1273 // handled somehow. Discard them silently for now.
1274 if (isset ($_REQUEST['cft']) and is_array ($_REQUEST['cft']))
31c941ec 1275 {
23cdc7e9
DO
1276 global $taglist;
1277 foreach ($_REQUEST['cft'] as $req_id)
1278 if (isset ($taglist[$req_id]))
1279 {
1280 $ret['tagidlist'][] = $req_id;
1281 $ret['tnamelist'][] = $taglist[$req_id]['tag'];
1282 $ret['text'] .= $andor1 . '{' . $taglist[$req_id]['tag'] . '}';
1283 $andor1 = ' ' . $andor2 . ' ';
a8efc03e 1284 $ret['urlextra'] .= '&cft[]=' . $req_id;
23cdc7e9
DO
1285 }
1286 }
1287 if (isset ($_REQUEST['cfp']) and is_array ($_REQUEST['cfp']))
1288 {
1289 global $pTable;
1290 foreach ($_REQUEST['cfp'] as $req_name)
1291 if (isset ($pTable[$req_name]))
1292 {
1293 $ret['pnamelist'][] = $req_name;
1294 $ret['text'] .= $andor1 . '[' . $req_name . ']';
1295 $andor1 = ' ' . $andor2 . ' ';
a8efc03e 1296 $ret['urlextra'] .= '&cfp[]=' . $req_name;
23cdc7e9
DO
1297 }
1298 }
7da7450c
DO
1299 // Extra text comes from TEXTAREA and is easily screwed by standard escaping function.
1300 if (isset ($sic['cfe']))
a8efc03e 1301 {
7da7450c
DO
1302 // Only consider extra text, when it is a correct RackCode expression.
1303 $parse = spotPayload ($sic['cfe'], 'SYNT_EXPR');
1304 if ($parse['result'] == 'ACK')
1305 {
1306 $ret['extratext'] = trim ($sic['cfe']);
1307 $ret['urlextra'] .= '&cfe=' . $ret['extratext'];
1308 }
a8efc03e 1309 }
23cdc7e9
DO
1310 $finaltext = array();
1311 if (strlen ($ret['text']))
1312 $finaltext[] = '(' . $ret['text'] . ')';
1313 if (strlen ($ret['extratext']))
1314 $finaltext[] = '(' . $ret['extratext'] . ')';
1315 $finaltext = implode (' ' . $andor2 . ' ', $finaltext);
1316 if (strlen ($finaltext))
1317 {
1318 $parse = spotPayload ($finaltext, 'SYNT_EXPR');
1319 $ret['expression'] = $parse['result'] == 'ACK' ? $parse['load'] : NULL;
8c699525
DO
1320 // It's not quite fair enough to put the blame of the whole text onto
1321 // non-empty "extra" portion of it, but it's the only user-generated portion
1322 // of it, thus the most probable cause of parse error.
1323 if (strlen ($ret['extratext']))
1324 $ret['extraclass'] = $parse['result'] == 'ACK' ? 'validation-success' : 'validation-error';
31c941ec 1325 }
3d670bba 1326 return $ret;
31c941ec
DO
1327}
1328
db55cf54
DO
1329// Return an empty message log.
1330function emptyLog ()
1331{
1332 return array
1333 (
1334 'v' => 2,
1335 'm' => array()
1336 );
1337}
1338
2987fc1f
DO
1339// Return a message log consisting of only one message.
1340function oneLiner ($code, $args = array())
1341{
db55cf54 1342 $ret = emptyLog();
2987fc1f
DO
1343 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1344 return $ret;
46f92ff7
DO
1345}
1346
e53b1246
DO
1347// Merge message payload from two message logs given and return the result.
1348function mergeLogs ($log1, $log2)
1349{
1350 $ret = emptyLog();
1351 $ret['m'] = array_merge ($log1['m'], $log2['m']);
1352 return $ret;
1353}
1354
9f54e6e9 1355function validTagName ($s, $allow_autotag = FALSE)
2eeeca80 1356{
9f54e6e9
DO
1357 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1358 return TRUE;
1359 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1360 return TRUE;
1361 return FALSE;
2eeeca80
DO
1362}
1363
53bae67b
DO
1364function redirectUser ($p, $t)
1365{
790a60e8
DO
1366 global $page;
1367 $l = "index.php?page=${p}&tab=${t}";
53bae67b
DO
1368 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1369 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1370 header ("Location: " . $l);
1371 die;
1372}
1373
9f3e5caa
DO
1374function getRackCodeStats ()
1375{
1376 global $rackCode;
914b439b 1377 $defc = $grantc = $modc = 0;
9f3e5caa
DO
1378 foreach ($rackCode as $s)
1379 switch ($s['type'])
1380 {
1381 case 'SYNT_DEFINITION':
1382 $defc++;
1383 break;
1384 case 'SYNT_GRANT':
1385 $grantc++;
1386 break;
914b439b
DO
1387 case 'SYNT_CTXMOD':
1388 $modc++;
1389 break;
9f3e5caa
DO
1390 default:
1391 break;
1392 }
914b439b
DO
1393 $ret = array
1394 (
1395 'Definition sentences' => $defc,
1396 'Grant sentences' => $grantc,
1397 'Context mod sentences' => $modc
1398 );
9f3e5caa
DO
1399 return $ret;
1400}
1401
d5157018
DO
1402function getRackImageWidth ()
1403{
529eac25
DO
1404 global $rtwidth;
1405 return 3 + $rtwidth[0] + $rtwidth[1] + $rtwidth[2] + 3;
d5157018
DO
1406}
1407
1408function getRackImageHeight ($units)
1409{
1410 return 3 + 3 + $units * 2;
1411}
1412
2987fc1f
DO
1413// Perform substitutions and return resulting string
1414// used solely by buildLVSConfig()
1415function apply_macros ($macros, $subject)
1416{
1417 $ret = $subject;
1418 foreach ($macros as $search => $replace)
1419 $ret = str_replace ($search, $replace, $ret);
1420 return $ret;
1421}
1422
1423function buildLVSConfig ($object_id = 0)
1424{
1425 if ($object_id <= 0)
1426 {
0cc24e9a 1427 showWarning ('Invalid argument', __FUNCTION__);
2987fc1f
DO
1428 return;
1429 }
6297d584 1430 $oInfo = spotEntity ('object', $object_id);
2987fc1f
DO
1431 $lbconfig = getSLBConfig ($object_id);
1432 if ($lbconfig === NULL)
1433 {
0cc24e9a 1434 showWarning ('getSLBConfig() failed', __FUNCTION__);
2987fc1f
DO
1435 return;
1436 }
1437 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1438 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1439 foreach ($lbconfig as $vs_id => $vsinfo)
1440 {
1441 $newconfig .= "########################################################\n" .
59a83bd8
DO
1442 "# VS (id == ${vs_id}): " . (!strlen ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1443 "# RS pool (id == ${vsinfo['pool_id']}): " . (!strlen ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
2987fc1f
DO
1444 "########################################################\n";
1445 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1446 $macros = array
1447 (
1448 '%VIP%' => $vsinfo['vip'],
1449 '%VPORT%' => $vsinfo['vport'],
1450 '%PROTO%' => $vsinfo['proto'],
1451 '%VNAME%' => $vsinfo['vs_name'],
1452 '%RSPOOLNAME%' => $vsinfo['pool_name']
1453 );
1454 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1455 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1456 $newconfig .= apply_macros
1457 (
1458 $macros,
1459 lf_wrap ($vsinfo['vs_vsconfig']) .
1460 lf_wrap ($vsinfo['lb_vsconfig']) .
1461 lf_wrap ($vsinfo['pool_vsconfig'])
1462 );
1463 foreach ($vsinfo['rslist'] as $rs)
1464 {
59a83bd8 1465 if (!strlen ($rs['rsport']))
79a9edb4 1466 $rs['rsport'] = $vsinfo['vport'];
2987fc1f
DO
1467 $macros['%RSIP%'] = $rs['rsip'];
1468 $macros['%RSPORT%'] = $rs['rsport'];
1469 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1470 $newconfig .= apply_macros
1471 (
1472 $macros,
1473 lf_wrap ($vsinfo['vs_rsconfig']) .
1474 lf_wrap ($vsinfo['lb_rsconfig']) .
1475 lf_wrap ($vsinfo['pool_rsconfig']) .
1476 lf_wrap ($rs['rs_rsconfig'])
1477 );
1478 $newconfig .= "\t}\n";
1479 }
1480 $newconfig .= "}\n\n\n";
1481 }
3dd72e34
DO
1482 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1483 return str_replace ("\r", '', $newconfig);
2987fc1f
DO
1484}
1485
2d318652
DO
1486// Indicate occupation state of each IP address: none, ordinary or problematic.
1487function markupIPv4AddrList (&$addrlist)
1488{
1489 foreach (array_keys ($addrlist) as $ip_bin)
1490 {
d983f70a
DO
1491 $refc = array
1492 (
00c5d8cb
DO
1493 'shared' => 0, // virtual
1494 'virtual' => 0, // loopback
1495 'regular' => 0, // connected host
1496 'router' => 0 // connected gateway
d983f70a
DO
1497 );
1498 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1499 $refc[$a['type']]++;
00c5d8cb 1500 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
d983f70a
DO
1501 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1502 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
2d318652
DO
1503
1504 if ($nrealms == 1)
1505 $addrlist[$ip_bin]['class'] = 'trbusy';
1506 elseif ($nrealms > 1)
1507 $addrlist[$ip_bin]['class'] = 'trerror';
1508 else
1509 $addrlist[$ip_bin]['class'] = '';
1510 }
1511}
1512
04d619d0
DO
1513// Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1514function findRouters ($addrlist)
1515{
1516 $ret = array();
1517 foreach ($addrlist as $addr)
1518 foreach ($addr['allocs'] as $alloc)
1519 if ($alloc['type'] == 'router')
1520 $ret[] = array
1521 (
1522 'id' => $alloc['object_id'],
1523 'iface' => $alloc['name'],
1524 'dname' => $alloc['object_name'],
1525 'addr' => $addr['ip']
1526 );
1527 return $ret;
1528}
1529
fb7a4967
DO
1530// Assist in tag chain sorting.
1531function taginfoCmp ($tagA, $tagB)
1532{
1533 return $tagA['ci'] - $tagB['ci'];
1534}
1535
1327d9dd
DO
1536// Compare networks. When sorting a tree, the records on the list will have
1537// distinct base IP addresses.
3444ecf2
DO
1538// "The comparison function must return an integer less than, equal to, or greater
1539// than zero if the first argument is considered to be respectively less than,
1540// equal to, or greater than the second." (c) PHP manual
1327d9dd
DO
1541function IPv4NetworkCmp ($netA, $netB)
1542{
2d75c30b
DO
1543 // There's a problem just substracting one u32 integer from another,
1544 // because the result may happen big enough to become a negative i32
1545 // integer itself (PHP tries to cast everything it sees to signed int)
3444ecf2
DO
1546 // The comparison below must treat positive and negative values of both
1547 // arguments.
1548 // Equal values give instant decision regardless of their [equal] sign.
1549 if ($netA['ip_bin'] == $netB['ip_bin'])
2d75c30b 1550 return 0;
3444ecf2
DO
1551 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1552 // 0x00000001~0x7fffffff 1~2147483647
1553 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1554 // 0x80000000~0xffffffff -2147483648~-1
1555 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1556 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1557 if ($signA == $signB)
1558 {
1559 if ($netA['ip_bin'] > $netB['ip_bin'])
1560 return 1;
1561 else
1562 return -1;
1563 }
1564 else // With only one of two values being negative, it... wins!
1565 {
1566 if ($netA['ip_bin'] < $netB['ip_bin'])
1567 return 1;
1568 else
1569 return -1;
1570 }
1327d9dd
DO
1571}
1572
fb7a4967 1573// Modify the given tag tree so, that each level's items are sorted alphabetically.
1327d9dd 1574function sortTree (&$tree, $sortfunc = '')
fb7a4967 1575{
59a83bd8 1576 if (!strlen ($sortfunc))
1327d9dd 1577 return;
51b6651a 1578 $self = __FUNCTION__;
1327d9dd 1579 usort ($tree, $sortfunc);
fb7a4967
DO
1580 // Don't make a mistake of directly iterating over the items of current level, because this way
1581 // the sorting will be performed on a _copy_ if each item, not the item itself.
1582 foreach (array_keys ($tree) as $tagid)
51b6651a 1583 $self ($tree[$tagid]['kids'], $sortfunc);
fb7a4967
DO
1584}
1585
0137d53c
DO
1586function iptree_fill (&$netdata)
1587{
59a83bd8 1588 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
0137d53c 1589 return;
a987ff52 1590 // If we really have nested prefixes, they must fit into the tree.
0137d53c
DO
1591 $worktree = array
1592 (
1593 'ip_bin' => $netdata['ip_bin'],
1594 'mask' => $netdata['mask']
1595 );
1596 foreach ($netdata['kids'] as $pfx)
1597 iptree_embed ($worktree, $pfx);
1598 $netdata['kids'] = iptree_construct ($worktree);
1599 $netdata['kidc'] = count ($netdata['kids']);
1600}
1601
1602function iptree_construct ($node)
1603{
1604 $self = __FUNCTION__;
1605
1606 if (!isset ($node['right']))
1607 {
1608 if (!isset ($node['ip']))
1609 {
1610 $node['ip'] = long2ip ($node['ip_bin']);
1611 $node['kids'] = array();
fec0c8da 1612 $node['kidc'] = 0;
0137d53c
DO
1613 $node['name'] = '';
1614 }
1615 return array ($node);
1616 }
1617 else
1618 return array_merge ($self ($node['left']), $self ($node['right']));
1619}
1620
1621function iptree_embed (&$node, $pfx)
1622{
1623 $self = __FUNCTION__;
1624
1625 // hit?
1626 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1627 {
1628 $node = $pfx;
1629 return;
1630 }
1631 if ($node['mask'] == $pfx['mask'])
1632 {
0cc24e9a 1633 throw new RuntimeException('Internal error, the recurring loop lost control');
0137d53c
DO
1634 }
1635
1636 // split?
1637 if (!isset ($node['right']))
1638 {
a987ff52
DO
1639 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
1640 $node['left']['mask'] = $node['mask'] + 1;
0137d53c 1641 $node['left']['ip_bin'] = $node['ip_bin'];
a987ff52
DO
1642 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
1643 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] | binInvMaskFromDec ($node['left']['mask']));
1644
1645 $node['right']['mask'] = $node['mask'] + 1;
0137d53c 1646 $node['right']['ip_bin'] = $node['ip_bin'] + binInvMaskFromDec ($node['mask'] + 1) + 1;
a987ff52
DO
1647 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
1648 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] | binInvMaskFromDec ($node['right']['mask']));
0137d53c
DO
1649 }
1650
1651 // repeat!
1652 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1653 $self ($node['left'], $pfx);
1654 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1655 $self ($node['right'], $pfx);
1656 else
1657 {
0cc24e9a 1658 throw new RuntimeException ('Internal error, cannot decide between left and right');
0137d53c
DO
1659 }
1660}
1661
3b81cb98 1662function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
0137d53c 1663{
59a83bd8 1664 if (!strlen ($func))
0137d53c
DO
1665 return;
1666 $self = __FUNCTION__;
1667 foreach (array_keys ($tree) as $key)
1668 {
1669 $func ($tree[$key]);
59a83bd8 1670 if (strlen ($stopfunc) and $stopfunc ($tree[$key]))
c3315231 1671 continue;
0137d53c
DO
1672 $self ($tree[$key]['kids'], $func);
1673 }
1674}
1675
a987ff52
DO
1676function loadIPv4AddrList (&$netinfo)
1677{
1678 loadOwnIPv4Addresses ($netinfo);
1679 markupIPv4AddrList ($netinfo['addrlist']);
1680}
b18d26dc 1681
b6b87070 1682function countOwnIPv4Addresses (&$node)
b18d26dc 1683{
b6b87070 1684 $toscan = array();
737a3f72 1685 $node['addrt'] = 0;
4d0dbd87
DO
1686 $node['mask_bin'] = binMaskFromDec ($node['mask']);
1687 $node['mask_bin_inv'] = binInvMaskFromDec ($node['mask']);
1688 $node['db_first'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] & $node['mask_bin']);
1689 $node['db_last'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] | ($node['mask_bin_inv']));
59a83bd8 1690 if (!count ($node['kids']))
737a3f72 1691 {
f7414fa5 1692 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
737a3f72
DO
1693 $node['addrt'] = binInvMaskFromDec ($node['mask']) + 1;
1694 }
b18d26dc 1695 else
b6b87070 1696 foreach ($node['kids'] as $nested)
b18d26dc 1697 if (!isset ($nested['id'])) // spare
737a3f72 1698 {
f7414fa5 1699 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
737a3f72
DO
1700 $node['addrt'] += binInvMaskFromDec ($nested['mask']) + 1;
1701 }
4d0dbd87
DO
1702 // Don't do anything more, because the displaying function will load the addresses anyway.
1703 return;
f7414fa5 1704 $node['addrc'] = count (scanIPv4Space ($toscan));
b6b87070
DO
1705}
1706
c3315231
DO
1707function nodeIsCollapsed ($node)
1708{
1709 return $node['symbol'] == 'node-collapsed';
1710}
1711
b6b87070
DO
1712function loadOwnIPv4Addresses (&$node)
1713{
1714 $toscan = array();
43eb71f1 1715 if (!isset ($node['kids']) or !count ($node['kids']))
f7414fa5 1716 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
b6b87070
DO
1717 else
1718 foreach ($node['kids'] as $nested)
1719 if (!isset ($nested['id'])) // spare
f7414fa5
DO
1720 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1721 $node['addrlist'] = scanIPv4Space ($toscan);
b6b87070 1722 $node['addrc'] = count ($node['addrlist']);
b18d26dc
DO
1723}
1724
fec0c8da
DO
1725function prepareIPv4Tree ($netlist, $expanded_id = 0)
1726{
573214e0
DO
1727 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
1728 // so perform necessary pre-processing to make orphans belong to root. This trick
1729 // was earlier performed by getIPv4NetworkList().
1730 $netids = array_keys ($netlist);
1731 foreach ($netids as $cid)
1732 if (!in_array ($netlist[$cid]['parent_id'], $netids))
1733 $netlist[$cid]['parent_id'] = NULL;
fec0c8da
DO
1734 $tree = treeFromList ($netlist); // medium call
1735 sortTree ($tree, 'IPv4NetworkCmp');
fec0c8da 1736 // complement the tree before markup to make the spare networks have "symbol" set
c3315231
DO
1737 treeApplyFunc ($tree, 'iptree_fill');
1738 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
1739 // count addresses after the markup to skip computation for hidden tree nodes
1740 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
fec0c8da
DO
1741 return $tree;
1742}
1743
1744// Check all items of the tree recursively, until the requested target id is
1745// found. Mark all items leading to this item as "expanded", collapsing all
1746// the rest, which exceed the given threshold (if the threshold is given).
1747function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
1748{
1749 $self = __FUNCTION__;
1750 $ret = FALSE;
1751 foreach (array_keys ($tree) as $key)
1752 {
5388794d 1753 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
fec0c8da
DO
1754 $below = $self ($tree[$key]['kids'], $threshold, $target);
1755 if (!$tree[$key]['kidc']) // terminal node
1756 $tree[$key]['symbol'] = 'spacer';
1757 elseif ($tree[$key]['kidc'] < $threshold)
1758 $tree[$key]['symbol'] = 'node-expanded-static';
1759 elseif ($here or $below)
1760 $tree[$key]['symbol'] = 'node-expanded';
1761 else
1762 $tree[$key]['symbol'] = 'node-collapsed';
1763 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
1764 }
1765 return $ret;
1766}
1767
e1ae3fb4
AD
1768// Convert entity name to human-readable value
1769function formatEntityName ($name) {
1770 switch ($name)
1771 {
1772 case 'ipv4net':
1773 return 'IPv4 Network';
1774 case 'ipv4rspool':
1775 return 'IPv4 RS Pool';
1776 case 'ipv4vs':
1777 return 'IPv4 Virtual Service';
1778 case 'object':
1779 return 'Object';
1780 case 'rack':
1781 return 'Rack';
1782 case 'user':
1783 return 'User';
1784 }
1785 return 'invalid';
1786}
1787
1788// Take a MySQL or other generic timestamp and make it prettier
1789function formatTimestamp ($timestamp) {
1790 return date('n/j/y g:iA', strtotime($timestamp));
1791}
1792
8bc5d1e4
DO
1793// Display hrefs for all of a file's parents. If scissors are requested,
1794// prepend cutting button to each of them.
1795function serializeFileLinks ($links, $scissors = FALSE)
e1ae3fb4 1796{
e1ae3fb4
AD
1797 $comma = '';
1798 $ret = '';
1799 foreach ($links as $link_id => $li)
1800 {
1801 switch ($li['entity_type'])
1802 {
1803 case 'ipv4net':
1804 $params = "page=ipv4net&id=";
1805 break;
1806 case 'ipv4rspool':
1807 $params = "page=ipv4rspool&pool_id=";
1808 break;
1809 case 'ipv4vs':
1810 $params = "page=ipv4vs&vs_id=";
1811 break;
1812 case 'object':
1813 $params = "page=object&object_id=";
1814 break;
1815 case 'rack':
1816 $params = "page=rack&rack_id=";
1817 break;
1818 case 'user':
1819 $params = "page=user&user_id=";
1820 break;
1821 }
8bc5d1e4
DO
1822 $ret .= $comma;
1823 if ($scissors)
1824 {
1825 $ret .= "<a href='" . makeHrefProcess(array('op'=>'unlinkFile', 'link_id'=>$link_id)) . "'";
1826 $ret .= getImageHREF ('cut') . '</a> ';
1827 }
790a60e8 1828 $ret .= sprintf("<a href='index.php?%s%s'>%s</a>", $params, $li['entity_id'], $li['name']);
8bc5d1e4 1829 $comma = '<br>';
e1ae3fb4 1830 }
e1ae3fb4
AD
1831 return $ret;
1832}
1833
1834// Convert filesize to appropriate unit and make it human-readable
1835function formatFileSize ($bytes) {
1836 // bytes
1837 if($bytes < 1024) // bytes
1838 return "${bytes} bytes";
1839
1840 // kilobytes
1841 if ($bytes < 1024000)
1842 return sprintf ("%.1fk", round (($bytes / 1024), 1));
1843
1844 // megabytes
1845 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
1846}
1847
1848// Reverse of formatFileSize, it converts human-readable value to bytes
1849function convertToBytes ($value) {
1850 $value = trim($value);
1851 $last = strtolower($value[strlen($value)-1]);
1852 switch ($last)
1853 {
1854 case 'g':
1855 $value *= 1024;
1856 case 'm':
1857 $value *= 1024;
1858 case 'k':
1859 $value *= 1024;
1860 }
1861
1862 return $value;
1863}
1864
4fbb5a00
DY
1865function ip_quad2long ($ip)
1866{
1867 return sprintf("%u", ip2long($ip));
1868}
1869
1870function ip_long2quad ($quad)
1871{
1872 return long2ip($quad);
1873}
1874
1875function makeHref($params = array())
1876{
790a60e8 1877 $ret = 'index.php?';
4fbb5a00 1878 $first = true;
4fbb5a00
DY
1879 foreach($params as $key=>$value)
1880 {
1881 if (!$first)
1882 $ret.='&';
1883 $ret .= urlencode($key).'='.urlencode($value);
1884 $first = false;
1885 }
1886 return $ret;
1887}
1888
1889function makeHrefProcess($params = array())
1890{
790a60e8
DO
1891 global $pageno, $tabno;
1892 $ret = 'process.php?';
4fbb5a00 1893 $first = true;
9f14a7ef
DY
1894 if (!isset($params['page']))
1895 $params['page'] = $pageno;
1896 if (!isset($params['tab']))
1897 $params['tab'] = $tabno;
4fbb5a00
DY
1898 foreach($params as $key=>$value)
1899 {
1900 if (!$first)
1901 $ret.='&';
1902 $ret .= urlencode($key).'='.urlencode($value);
1903 $first = false;
1904 }
1905 return $ret;
1906}
1907
39106006 1908function makeHrefForHelper ($helper_name, $params = array())
4fbb5a00 1909{
790a60e8 1910 $ret = 'popup.php?helper=' . $helper_name;
4fbb5a00 1911 foreach($params as $key=>$value)
39106006 1912 $ret .= '&'.urlencode($key).'='.urlencode($value);
4fbb5a00
DY
1913 return $ret;
1914}
1915
f3d274bf
DO
1916// Process the given list of records to build data suitable for printNiftySelect()
1917// (like it was formerly executed by printSelect()). Screen out vendors according
1918// to VENDOR_SIEVE, if object type ID is provided. However, the OPTGROUP with already
1919// selected OPTION is protected from being screened.
1920function cookOptgroups ($recordList, $object_type_id = 0, $existing_value = 0)
1921{
1922 $ret = array();
1923 // Always keep "other" OPTGROUP at the SELECT bottom.
1924 $therest = array();
1925 foreach ($recordList as $dict_key => $dict_value)
1926 if (strpos ($dict_value, '%GSKIP%') !== FALSE)
1927 {
1928 $tmp = explode ('%GSKIP%', $dict_value, 2);
1929 $ret[$tmp[0]][$dict_key] = $tmp[1];
1930 }
1931 elseif (strpos ($dict_value, '%GPASS%') !== FALSE)
1932 {
1933 $tmp = explode ('%GPASS%', $dict_value, 2);
1934 $ret[$tmp[0]][$dict_key] = $tmp[1];
1935 }
1936 else
1937 $therest[$dict_key] = $dict_value;
1938 if ($object_type_id != 0)
1939 {
1940 $screenlist = array();
1941 foreach (explode (';', getConfigVar ('VENDOR_SIEVE')) as $sieve)
1942 if (FALSE !== mb_ereg ("^([^@]+)(@${object_type_id})?\$", trim ($sieve), $regs))
1943 $screenlist[] = $regs[1];
1944 foreach (array_keys ($ret) as $vendor)
1945 if (in_array ($vendor, $screenlist))
1946 {
1947 $ok_to_screen = TRUE;
1948 if ($existing_value)
1949 foreach (array_keys ($ret[$vendor]) as $recordkey)
1950 if ($recordkey == $existing_value)
1951 {
1952 $ok_to_screen = FALSE;
1953 break;
1954 }
1955 if ($ok_to_screen)
1956 unset ($ret[$vendor]);
1957 }
1958 }
1959 $ret['other'] = $therest;
1960 return $ret;
1961}
1962
f8874cdb
DO
1963function dos2unix ($text)
1964{
1965 return str_replace ("\r\n", "\n", $text);
1966}
1967
a0527aef 1968function buildPredicateTable ($parsetree)
2c21a10c 1969{
a0527aef
DO
1970 $ret = array();
1971 foreach ($parsetree as $sentence)
72e8baf6 1972 if ($sentence['type'] == 'SYNT_DEFINITION')
a0527aef 1973 $ret[$sentence['term']] = $sentence['definition'];
72e8baf6
DO
1974 // Now we have predicate table filled in with the latest definitions of each
1975 // particular predicate met. This isn't as chik, as on-the-fly predicate
1976 // overloading during allow/deny scan, but quite sufficient for this task.
a0527aef
DO
1977 return $ret;
1978}
1979
1980// Take a list of records and filter against given RackCode expression. Return
1981// the original list intact, if there was no filter requested, but return an
1982// empty list, if there was an error.
573214e0 1983function filterCellList ($list_in, $expression = array())
d08d766d
DO
1984{
1985 if ($expression === NULL)
1986 return array();
1987 if (!count ($expression))
1988 return $list_in;
d08d766d
DO
1989 $list_out = array();
1990 foreach ($list_in as $item_key => $item_value)
573214e0 1991 if (TRUE === judgeCell ($item_value, $expression))
d08d766d
DO
1992 $list_out[$item_key] = $item_value;
1993 return $list_out;
1994}
1995
212c9d8a 1996// Tell, if the given expression is true for the given entity. Take complete record on input.
573214e0 1997function judgeCell ($cell, $expression)
d08d766d
DO
1998{
1999 global $pTable;
2000 return eval_expression
2001 (
2002 $expression,
2003 array_merge
2004 (
573214e0
DO
2005 $cell['etags'],
2006 $cell['itags'],
2007 $cell['atags']
d08d766d
DO
2008 ),
2009 $pTable,
2010 TRUE
2011 );
2012}
2013
7ddbcf59 2014// Tell, if a constraint from config option permits given record.
212c9d8a 2015function considerConfiguredConstraint ($cell, $varname)
c6bc0ac5 2016{
7ddbcf59 2017 if (!strlen (getConfigVar ($varname)))
c6bc0ac5 2018 return TRUE; // no restriction
7ddbcf59
DO
2019 global $parseCache;
2020 if (!isset ($parseCache[$varname]))
2021 // getConfigVar() doesn't re-read the value from DB because of its
2022 // own cache, so there is no race condition here between two calls.
2023 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
2024 if ($parseCache[$varname]['result'] != 'ACK')
2025 return FALSE; // constraint set, but cannot be used due to compilation error
212c9d8a 2026 return judgeCell ($cell, $parseCache[$varname]['load']);
c6bc0ac5
DO
2027}
2028
17112e81
DO
2029// Return list of records in the given realm, which conform to
2030// the given RackCode expression. If the realm is unknown or text
2031// doesn't validate as a RackCode expression, return NULL.
2032// Otherwise (successful scan) return a list of all matched
2033// records, even if the list is empty (array() !== NULL). If the
2034// text is an empty string, return all found records in the given
2035// realm.
2036function scanRealmByText ($realm = NULL, $ftext = '')
2037{
2038 switch ($realm)
2039 {
2040 case 'object':
2041 case 'user':
2042 case 'ipv4net':
2043 case 'file':
39776127 2044 case 'ipv4vs':
41780975 2045 case 'ipv4rspool':
17112e81
DO
2046 if (!strlen ($ftext = trim ($ftext)))
2047 $fexpr = array();
2048 else
2049 {
2050 $fparse = spotPayload ($ftext, 'SYNT_EXPR');
2051 if ($fparse['result'] != 'ACK')
2052 return NULL;
2053 $fexpr = $fparse['load'];
2054 }
2055 return filterCellList (listCells ($realm), $fexpr);
2056 default:
c5f84f48 2057 throw new InvalidArgException ('$realm', $realm);
17112e81
DO
2058 }
2059
2060}
39776127
DO
2061
2062function getIPv4VSOptions ()
2063{
2064 $ret = array();
2065 foreach (listCells ('ipv4vs') as $vsid => $vsinfo)
59a83bd8 2066 $ret[$vsid] = $vsinfo['dname'] . (!strlen ($vsinfo['name']) ? '' : " (${vsinfo['name']})");
39776127
DO
2067 return $ret;
2068}
2069
41780975
DO
2070function getIPv4RSPoolOptions ()
2071{
2072 $ret = array();
2073 foreach (listCells ('ipv4rspool') as $pool_id => $poolInfo)
2074 $ret[$pool_id] = $poolInfo['name'];
2075 return $ret;
2076}
2077
d16af52f
DO
2078// Derive a complete cell structure from the given username regardless
2079// if it is a local account or not.
2080function constructUserCell ($username)
2081{
2082 if (NULL !== ($userid = getUserIDByUsername ($username)))
2083 return spotEntity ('user', $userid);
2084 $ret = array
2085 (
2086 'realm' => 'user',
2087 'user_name' => $username,
2088 'user_realname' => '',
2089 'etags' => array(),
2090 'itags' => array(),
d16af52f 2091 );
5689cefd 2092 $ret['atags'] = generateEntityAutoTags ($ret);
d16af52f
DO
2093 return $ret;
2094}
2095
56a797ef
DO
2096// Let's have this debug helper here to enable debugging of process.php w/o interface.php.
2097function dump ($var)
2098{
2099 echo '<div align=left><pre>';
2100 print_r ($var);
2101 echo '</pre></div>';
2102}
2103
9e51318b
DO
2104function getTagChart ($limit = 0, $realm = 'total', $special_tags = array())
2105{
2106 global $taglist;
2107 // first build top-N chart...
2108 $toplist = array();
2109 foreach ($taglist as $taginfo)
2110 if (isset ($taginfo['refcnt'][$realm]))
2111 $toplist[$taginfo['id']] = $taginfo['refcnt'][$realm];
2112 arsort ($toplist, SORT_NUMERIC);
2113 $ret = array();
2114 $done = 0;
2115 foreach (array_keys ($toplist) as $tag_id)
2116 {
2117 $ret[$tag_id] = $taglist[$tag_id];
2118 if (++$done == $limit)
2119 break;
2120 }
2121 // ...then make sure, that every item of the special list is shown
2122 // (using the same sort order)
2123 $extra = array();
2124 foreach ($special_tags as $taginfo)
2125 if (!array_key_exists ($taginfo['id'], $ret))
2126 $extra[$taginfo['id']] = $taglist[$taginfo['id']]['refcnt'][$realm];
2127 arsort ($extra, SORT_NUMERIC);
2128 foreach (array_keys ($extra) as $tag_id)
2129 $ret[] = $taglist[$tag_id];
2130 return $ret;
2131}
2132
7fa7047a
DO
2133function decodeObjectType ($objtype_id, $style = 'r')
2134{
2135 static $types = array();
2136 if (!count ($types))
2137 $types = array
2138 (
2139 'r' => readChapter (CHAP_OBJTYPE),
2140 'a' => readChapter (CHAP_OBJTYPE, 'a'),
2141 'o' => readChapter (CHAP_OBJTYPE, 'o')
2142 );
2143 return $types[$style][$objtype_id];
2144}
2145
0df8c52b
DO
2146function isolatedPermission ($p, $t, $cell)
2147{
2148 // This function is called from both "file" page and a number of other pages,
2149 // which have already fixed security context and authorized the user for it.
2150 // OTOH, it is necessary here to authorize against the current file, which
2151 // means saving the current context and building a new one.
2152 global
2153 $expl_tags,
2154 $impl_tags,
2155 $target_given_tags,
2156 $auto_tags;
2157 // push current context
2158 $orig_expl_tags = $expl_tags;
2159 $orig_impl_tags = $impl_tags;
2160 $orig_target_given_tags = $target_given_tags;
2161 $orig_auto_tags = $auto_tags;
2162 // retarget
2163 fixContext ($cell);
2164 // remember decision
2165 $ret = permitted ($p, $t);
2166 // pop context
2167 $expl_tags = $orig_expl_tags;
2168 $impl_tags = $orig_impl_tags;
2169 $target_given_tags = $orig_target_given_tags;
2170 $auto_tags = $orig_auto_tags;
2171 return $ret;
2172}
2173
3153a326
DO
2174function getPortListPrefs()
2175{
2176 $ret = array();
2177 if (0 >= ($ret['iif_pick'] = getConfigVar ('DEFAULT_PORT_IIF_ID')))
2178 $ret['iif_pick'] = 1;
2179 $ret['oif_picks'] = array();
2180 foreach (explode (';', getConfigVar ('DEFAULT_PORT_OIF_IDS')) as $tmp)
2181 {
2182 $tmp = explode ('=', trim ($tmp));
2183 if (count ($tmp) == 2 and $tmp[0] > 0 and $tmp[1] > 0)
2184 $ret['oif_picks'][$tmp[0]] = $tmp[1];
2185 }
2186 // enforce default value
2187 if (!array_key_exists (1, $ret['oif_picks']))
2188 $ret['oif_picks'][1] = 24;
2189 $ret['selected'] = $ret['iif_pick'] . '-' . $ret['oif_picks'][$ret['iif_pick']];
2190 return $ret;
2191}
2192
2dfa1b73
DO
2193// Return data for printNiftySelect() with port type options. All OIF options
2194// for the default IIF will be shown, but only the default OIFs will be present
2195// for each other IIFs. IIFs, for which there is no default OIF, will not
2196// be listed.
2197// This SELECT will be used for the "add new port" form.
2198function getNewPortTypeOptions()
2199{
2200 $ret = array();
2201 $prefs = getPortListPrefs();
2202 foreach (getPortInterfaceCompat() as $row)
2203 {
2204 if ($row['iif_id'] == $prefs['iif_pick'])
2205 $optgroup = $row['iif_name'];
2206 elseif (array_key_exists ($row['iif_id'], $prefs['oif_picks']) and $prefs['oif_picks'][$row['iif_id']] == $row['oif_id'])
2207 $optgroup = 'other';
2208 else
2209 continue;
2210 if (!array_key_exists ($optgroup, $ret))
2211 $ret[$optgroup] = array();
2212 $ret[$optgroup][$row['iif_id'] . '-' . $row['oif_id']] = $row['oif_name'];
2213 }
2214 return $ret;
2215}
2216
69c6e510
DY
2217//Make URL from GET without parameters specified in $parameters
2218function urlizeGetParameters($parameters) {
2219 $url = '';
2220 foreach ($_GET as $name=>$value) {
2221 if (in_array($name, $parameters)) continue;
2222 if ($url != '') $url .= '&';
2223 if (gettype($value) == 'array')
2224 foreach($value as $v)
2225 $url .= urlencode($name.'[]').'='.urlencode($v);
2226 else
2227 $url .= urlencode($name).'='.urlencode($value);
2228 }
2229 return $url;
2230}
2231
8198f2c6
DO
2232function getVLANDomain ($vdid)
2233{
2234 $ret = getVLANDomainInfo ($vdid);
2235 $ret['vlanlist'] = array();
8198f2c6
DO
2236 foreach (getDomainVLANs ($vdid) as $vlan_id => $vlan_descr)
2237 $ret['vlanlist'][$vlan_id] = $vlan_descr;
2238 $ret['switchlist'] = getVLANDomainSwitches ($vdid);
2239 return $ret;
2240}
2241
2242// Return a serialized version of VLAN configuration for a port.
2243// If a native VLAN is defined, print it first. All other VLANs
d0dadd80
DO
2244// are tagged and are listed after a plus sign. When no configuration
2245// is set for a port, return "default" string.
2246function serializeVLANPack ($native_vid = 0, $allowed_vids = array())
8198f2c6
DO
2247{
2248 $tagged = array();
2249 foreach ($allowed_vids as $vlan_id)
2250 if ($vlan_id != $native_vid)
2251 $tagged[] = $vlan_id;
2252 sort ($tagged);
d0dadd80 2253 $ret = $native_vid ? $native_vid : '';
e9be55de
DO
2254 $tagged_bits = array();
2255 $id_from = $id_to = 0;
2256 foreach ($tagged as $next_id)
2257 {
2258 if ($id_to)
2259 {
2260 if ($next_id == $id_to + 1) // merge
2261 {
2262 $id_to = $next_id;
2263 continue;
2264 }
2265 // flush
2266 $tagged_bits[] = $id_from == $id_to ? $id_from : "${id_from}-${id_to}";
2267 }
2268 $id_from = $id_to = $next_id; // start next pair
2269 }
2270 // pull last pair
2271 if ($id_to)
2272 $tagged_bits[] = $id_from == $id_to ? $id_from : "${id_from}-${id_to}";
8198f2c6 2273 if (count ($tagged))
e9be55de 2274 $ret .= '+' . implode (',', $tagged_bits);
d0dadd80 2275 return strlen ($ret) ? $ret : 'default';
8198f2c6
DO
2276}
2277
8846b060
DO
2278// Decode VLAN compound key (which is a string formatted DOMAINID-VLANID) and
2279// return the numbers as an array of two.
2280function decodeVLANCK ($string)
2281{
2282 $matches = array();
2283 if (1 != preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $string, $matches))
2284 throw new InvalidArgException ('VLAN compound key', $string);
2285 return array ($matches[1], $matches[2]);
2286}
2287
ce85f5c8
DO
2288// Return VLAN name formatted for HTML output (note, that input
2289// argument comes from database unescaped).
2290function formatVLANName ($vlaninfo)
2291{
5847d944 2292 $ret = '<tt>VLAN' . $vlaninfo['vlan_id'] . '</tt>';
ce85f5c8 2293 if (strlen ($vlaninfo['vlan_descr']))
5847d944 2294 $ret .= ' <i>(' . niftyString ($vlaninfo['vlan_descr']) . ')</i>';
ce85f5c8
DO
2295 return $ret;
2296}
2297
f10dd5cc
DO
2298// Read given running-config and return a list of work items in a format
2299// similar to the one, which setSwitchVLANConfig() understands.
2300function iosReadVLANConfig ($input)
2301{
2302 $ret = array();
2303 $procfunc = 'iosPickInterfaceCommand';
2304 foreach (explode ("\n", $input) as $line)
2305 $procfunc = $procfunc ($ret, $line);
2306 return $ret;
2307}
2308
2309function iosPickInterfaceCommand (&$work, $line)
2310{
2311 $matches = array();
2312 if (!preg_match ('@^interface ((Ethernet|FastEthernet|GigabitEthernet|TenGigabitEthernet)[[:digit:]]+(/[[:digit:]]+)*)$@', $line, $matches))
2313 return __FUNCTION__; // continue scan
2314 $work['current'] = array ('port_name' => $matches[1]);
2315 return 'iosPickSwitchportCommand'; // switch to interface block reading
2316}
2317
2318function iosPickSwitchportCommand (&$work, $line)
2319{
2320 if ($line[0] != ' ') // end of interface section
2321 {
2322 $boiled = array ('port_name' => $work['current']['port_name']);
2323 // fill in defaults
2324 if (!array_key_exists ('mode', $work['current']))
2325 $work['current']['mode'] = 'access';
2326 if (!array_key_exists ('access vlan', $work['current']))
2327 $work['current']['access vlan'] = 1;
2328 if (!array_key_exists ('trunk native vlan', $work['current']))
2329 $work['current']['trunk native vlan'] = 1;
2330 if (!array_key_exists ('trunk allowed vlan', $work['current']))
2331 $work['current']['trunk allowed vlan'] = range (VLAN_MIN_ID, VLAN_MAX_ID);
2332 // save work, if it makes sense
2333 switch ($work['current']['mode'])
2334 {
2335 case 'access':
2336 $work[] = array
2337 (
2338 'port_name' => $work['current']['port_name'],
2339 'allowed' => array ($work['current']['access vlan']),
2340 'native' => $work['current']['access vlan'],
2341 );
2342 break;
2343 case 'trunk':
2344 $work[] = array
2345 (
2346 'port_name' => $work['current']['port_name'],
e9be55de 2347 'allowed' => $work['current']['trunk allowed vlan'],
f10dd5cc
DO
2348 'native' => $work['current']['trunk native vlan'],
2349 );
2350 break;
2351 default:
2352 // dot1q-tunnel, dynamic, private-vlan --- skip these
2353 }
2354 unset ($work['current']);
2355 return 'iosPickInterfaceCommand';
2356 }
2357 // not yet
2358 $matches = array();
2359 switch (TRUE)
2360 {
2361 case (preg_match ('@^ switchport mode (.+)$@', $line, $matches)):
2362 $work['current']['mode'] = $matches[1];
2363 break;
2364 case (preg_match ('@^ switchport access vlan (.+)$@', $line, $matches)):
2365 $work['current']['access vlan'] = $matches[1];
2366 break;
2367 case (preg_match ('@^ switchport trunk native vlan (.+)$@', $line, $matches)):
2368 $work['current']['trunk native vlan'] = $matches[1];
2369 break;
2370 case (preg_match ('@^ switchport trunk allowed vlan add (.+)$@', $line, $matches)):
2371 $work['current']['trunk allowed vlan'] = array_merge
2372 (
2373 $work['current']['trunk allowed vlan'],
2374 iosParseVLANString ($matches[1])
2375 );
2376 break;
2377 case (preg_match ('@^ switchport trunk allowed vlan (.+)$@', $line, $matches)):
2378 $work['current']['trunk allowed vlan'] = iosParseVLANString ($matches[1]);
2379 break;
2380 default: // suppress warning on irrelevant config clause
2381 }
2382 return __FUNCTION__;
2383}
2384
2385function iosParseVLANString ($string)
2386{
2387 $ret = array();
2388 foreach (explode (',', $string) as $item)
2389 {
2390 $matches = array();
2391 if (preg_match ('/^([[:digit:]]+)$/', $item, $matches))
2392 $ret[] = $matches[1];
2393 elseif (preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $item, $matches))
2394 $ret = array_merge ($ret, range ($matches[1], $matches[2]));
2395 }
2396 return $ret;
2397}
2398
e673ee24 2399?>