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