r3017 - force "op" coordinate to be empty for all entry points except process.php
[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
e673ee24
DO
689// This function expands port compat list into a matrix.
690function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
691{
692 $matrix = array();
693 // Create type matrix and markup compatible types.
694 foreach (array_keys ($portTypeList) as $type1)
695 foreach (array_keys ($portTypeList) as $type2)
696 $matrix[$type1][$type2] = FALSE;
697 foreach ($portCompatList as $pair)
698 $matrix[$pair['type1']][$pair['type2']] = TRUE;
699 return $matrix;
700}
701
c31cd72c 702// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
703// if FQDN is set. The next choice is object's common name, if it looks like a
704// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 705// object is returned (which may appear 0 and more elements long).
f321b50a 706function findAllEndpoints ($object_id, $fallback = '')
c31cd72c 707{
7fa7047a
DO
708 foreach (getAttrValues ($object_id) as $record)
709 if ($record['id'] == 3 && strlen ($record['value'])) // FQDN
c31cd72c 710 return array ($record['value']);
c31cd72c 711 $regular = array();
85970da2
DO
712 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
713 if ($alloc['type'] == 'regular')
714 $regular[] = $dottedquad;
59a83bd8 715 if (!count ($regular) && strlen ($fallback))
f321b50a 716 return array ($fallback);
c31cd72c
DO
717 return $regular;
718}
719
83ba6670
DO
720// Some records in the dictionary may be written as plain text or as Wiki
721// link in the following syntax:
722// 1. word
723// 2. [[word URL]] // FIXME: this isn't working
724// 3. [[word word word | URL]]
725// This function parses the line and returns text suitable for either A
726// (rendering <A HREF>) or O (for <OPTION>).
7fa7047a 727function parseWikiLink ($line, $which)
83ba6670 728{
010231c2 729 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af 730 {
7fa7047a
DO
731 // always strip the marker for A-data, but let cookOptgroup()
732 // do this later (otherwise it can't sort groups out)
733 if ($which == 'a')
f0b540a3 734 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
24cbe8af
DO
735 else
736 return $line;
737 }
010231c2
DO
738 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
739 $s = explode ('|', $line);
83ba6670 740 $o_value = trim ($s[0]);
83ba6670
DO
741 if ($which == 'o')
742 return $o_value;
7fa7047a
DO
743 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
744 $a_value = trim ($s[1]);
745 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
746}
747
177b1e9b
DO
748// rackspace usage for a single rack
749// (T + W + U) / (height * 3 - A)
11df133a 750function getRSUforRack ($data = NULL)
177b1e9b 751{
11df133a 752 if ($data == NULL)
177b1e9b
DO
753 {
754 showError ('Invalid argument', __FUNCTION__);
755 return NULL;
756 }
6ffba290 757 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
758 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
759 for ($locidx = 0; $locidx < 3; $locidx++)
760 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 761 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
762}
763
11df133a
DO
764// Same for row.
765function getRSUforRackRow ($rowData = NULL)
766{
bb26a59e 767 if ($rowData === NULL)
11df133a
DO
768 {
769 showError ('Invalid argument', __FUNCTION__);
770 return NULL;
771 }
bb26a59e
DO
772 if (!count ($rowData))
773 return 0;
11df133a 774 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 775 $total_height = 0;
dfa3c075
DO
776 foreach (array_keys ($rowData) as $rack_id)
777 {
61a1d996
DO
778 $data = spotEntity ('rack', $rack_id);
779 amplifyCell ($data);
dfa3c075 780 $total_height += $data['height'];
11df133a
DO
781 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
782 for ($locidx = 0; $locidx < 3; $locidx++)
783 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
784 }
785 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
786}
787
9af110b4
DO
788// Make sure the string is always wrapped with LF characters
789function lf_wrap ($str)
790{
791 $ret = trim ($str, "\r\n");
59a83bd8 792 if (strlen ($ret))
9af110b4
DO
793 $ret .= "\n";
794 return $ret;
795}
796
e6e7d8b3
DO
797// Adopted from Mantis BTS code.
798function string_insert_hrefs ($s)
799{
800 if (getConfigVar ('DETECT_URLS') != 'yes')
801 return $s;
802 # Find any URL in a string and replace it by a clickable link
803 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
804 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
805 $s);
806 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
807 '<a href="mailto:\0">\0</a>',
808 $s);
809 return $s;
810}
811
812// Idem.
813function email_regex_simple ()
814{
815 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
816 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
817}
818
118e4c38
DO
819// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
820// for the requested object_type_id.
821function getAutoPorts ($type_id)
822{
823 $ret = array();
824 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
825 foreach ($typemap as $equation)
826 {
827 $tmp = explode ('=', $equation);
828 if (count ($tmp) != 2)
829 continue;
830 $objtype_id = $tmp[0];
831 if ($objtype_id != $type_id)
832 continue;
833 $portlist = $tmp[1];
834 foreach (explode ('+', $portlist) as $product)
835 {
836 $tmp = explode ('*', $product);
837 if (count ($tmp) != 3)
838 continue;
839 $nports = $tmp[0];
840 $port_type = $tmp[1];
841 $format = $tmp[2];
842 for ($i = 0; $i < $nports; $i++)
843 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
844 }
845 }
846 return $ret;
847}
848
86256b96
DO
849// Use pre-served trace to traverse the tree, then place given node where it belongs.
850function pokeNode (&$tree, $trace, $key, $value, $threshold = 0)
851{
852 // This function needs the trace to be followed FIFO-way. The fastest
853 // way to do so is to use array_push() for putting values into the
854 // list and array_shift() for getting them out. This exposed up to 11%
855 // performance gain compared to other patterns of array_push/array_unshift/
856 // array_reverse/array_pop/array_shift conjunction.
857 $myid = array_shift ($trace);
858 if (!count ($trace)) // reached the target
9dfd4cc9 859 {
86256b96
DO
860 if (!$threshold or ($threshold and $tree[$myid]['kidc'] + 1 < $threshold))
861 $tree[$myid]['kids'][$key] = $value;
862 // Reset accumulated records once, when the limit is reached, not each time
863 // after that.
864 if (++$tree[$myid]['kidc'] == $threshold)
865 $tree[$myid]['kids'] = array();
866 }
867 else // not yet
868 {
869 $self = __FUNCTION__;
870 $self ($tree[$myid]['kids'], $trace, $key, $value, $threshold);
9dfd4cc9 871 }
9dfd4cc9
DO
872}
873
d65353ad
DO
874// Build a tree from the item list and return it. Input and output data is
875// indexed by item id (nested items in output are recursively stored in 'kids'
51b6651a
DO
876// key, which is in turn indexed by id. Functions, which are ready to handle
877// tree collapsion/expansion themselves, may request non-zero threshold value
878// for smaller resulting tree.
3fb336f6 879function treeFromList (&$orig_nodelist, $threshold = 0, $return_main_payload = TRUE)
d65353ad 880{
86256b96 881 $tree = array();
3fb336f6 882 $nodelist = $orig_nodelist;
86256b96
DO
883 // Array equivalent of traceEntity() function.
884 $trace = array();
885 // set kidc and kids only once
886 foreach (array_keys ($nodelist) as $nodeid)
887 {
888 $nodelist[$nodeid]['kidc'] = 0;
889 $nodelist[$nodeid]['kids'] = array();
890 }
891 do
9dfd4cc9 892 {
86256b96
DO
893 $nextpass = FALSE;
894 foreach (array_keys ($nodelist) as $nodeid)
9dfd4cc9 895 {
86256b96
DO
896 // When adding a node to the working tree, book another
897 // iteration, because the new item could make a way for
898 // others onto the tree. Also remove any item added from
899 // the input list, so iteration base shrinks.
900 // First check if we can assign directly.
901 if ($nodelist[$nodeid]['parent_id'] == NULL)
9dfd4cc9 902 {
86256b96
DO
903 $tree[$nodeid] = $nodelist[$nodeid];
904 $trace[$nodeid] = array(); // Trace to root node is empty
905 unset ($nodelist[$nodeid]);
906 $nextpass = TRUE;
9dfd4cc9 907 }
86256b96
DO
908 // Now look if it fits somewhere on already built tree.
909 elseif (isset ($trace[$nodelist[$nodeid]['parent_id']]))
9dfd4cc9 910 {
86256b96
DO
911 // Trace to a node is a trace to its parent plus parent id.
912 $trace[$nodeid] = $trace[$nodelist[$nodeid]['parent_id']];
913 $trace[$nodeid][] = $nodelist[$nodeid]['parent_id'];
914 pokeNode ($tree, $trace[$nodeid], $nodeid, $nodelist[$nodeid], $threshold);
915 // path to any other node is made of all parent nodes plus the added node itself
916 unset ($nodelist[$nodeid]);
917 $nextpass = TRUE;
9dfd4cc9
DO
918 }
919 }
9dfd4cc9 920 }
86256b96 921 while ($nextpass);
3fb336f6 922 if (!$return_main_payload)
86256b96 923 return $nodelist;
3fb336f6
DO
924 // update each input node with its backtrace route
925 foreach ($trace as $nodeid => $route)
926 $orig_nodelist[$nodeid]['trace'] = $route;
927 return $tree;
9dfd4cc9
DO
928}
929
49fb1027 930// Build a tree from the tag list and return everything _except_ the tree.
573214e0
DO
931// IOW, return taginfo items, which have parent_id set and pointing outside
932// of the "normal" tree, which originates from the root.
49fb1027
DO
933function getOrphanedTags ()
934{
935 global $taglist;
86256b96 936 return treeFromList ($taglist, 0, FALSE);
49fb1027
DO
937}
938
6e49bd1f 939function serializeTags ($chain, $baseurl = '')
ba93bd98
DO
940{
941 $comma = '';
942 $ret = '';
6e49bd1f 943 foreach ($chain as $taginfo)
ba93bd98 944 {
e2ac59cf 945 $ret .= $comma .
a8efc03e 946 ($baseurl == '' ? '' : "<a href='${baseurl}cft[]=${taginfo['id']}'>") .
e2ac59cf
DO
947 $taginfo['tag'] .
948 ($baseurl == '' ? '' : '</a>');
ba93bd98
DO
949 $comma = ', ';
950 }
951 return $ret;
952}
953
ba93bd98
DO
954// Return the list of missing implicit tags.
955function getImplicitTags ($oldtags)
956{
3fb336f6
DO
957 global $taglist;
958 $tmp = array();
959 foreach ($oldtags as $taginfo)
960 $tmp = array_merge ($tmp, $taglist[$taginfo['id']]['trace']);
961 // don't call array_unique here, it is in the function we will call now
962 return buildTagChainFromIds ($tmp);
ba93bd98
DO
963}
964
6e49bd1f 965// Minimize the chain: exclude all implicit tags and return the result.
5fd2a004
DO
966// This function makes use of an external cache with a miss/hit ratio
967// about 3/7 (ticket:255).
3fb336f6 968function getExplicitTagsOnly ($chain)
ab379543 969{
5fd2a004 970 global $taglist, $tagRelCache;
ab379543 971 $ret = array();
5fd2a004
DO
972 foreach (array_keys ($chain) as $keyA) // check each A
973 {
974 $tagidA = $chain[$keyA]['id'];
975 // do not include A in result, if A is seen on the trace of any B!=A
976 foreach (array_keys ($chain) as $keyB)
977 {
978 $tagidB = $chain[$keyB]['id'];
979 if ($tagidA == $tagidB)
980 continue;
981 if (!isset ($tagRelCache[$tagidA][$tagidB]))
0745db4d 982 $tagRelCache[$tagidA][$tagidB] = in_array ($tagidA, $taglist[$tagidB]['trace']);
5fd2a004
DO
983 if ($tagRelCache[$tagidA][$tagidB] === TRUE) // A is ancestor of B
984 continue 2; // skip this A
985 }
986 $ret[] = $chain[$keyA];
987 }
74ccacff
DO
988 return $ret;
989}
990
2c21a10c 991// Universal autotags generator, a complementing function for loadEntityTags().
2c21a10c 992// Bypass key isn't strictly typed, but interpreted depending on the realm.
d16af52f 993function generateEntityAutoTags ($cell)
cce6b057 994{
cce6b057 995 $ret = array();
d16af52f 996 switch ($cell['realm'])
2c21a10c
DO
997 {
998 case 'rack':
d16af52f 999 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
2c21a10c
DO
1000 $ret[] = array ('tag' => '$any_rack');
1001 break;
4c9d35ec 1002 case 'object':
d16af52f
DO
1003 $ret[] = array ('tag' => '$id_' . $cell['id']);
1004 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
2c21a10c 1005 $ret[] = array ('tag' => '$any_object');
d16af52f
DO
1006 if (validTagName ('$cn_' . $cell['name']))
1007 $ret[] = array ('tag' => '$cn_' . $cell['name']);
1008 if (!strlen ($cell['rack_id']))
914b439b 1009 $ret[] = array ('tag' => '$unmounted');
6d472f26
DO
1010 if (!$cell['nports'])
1011 $ret[] = array ('tag' => '$portless');
2c21a10c 1012 break;
4c9d35ec 1013 case 'ipv4net':
d16af52f
DO
1014 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
1015 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
b9b915d5
DO
1016 for ($i = 8; $i < 32; $i++)
1017 {
1018 // these conditions hit 1 to 3 times per each i
1019 if ($cell['mask'] >= $i)
1020 $ret[] = array ('tag' => '$masklen_ge_' . $i);
1021 if ($cell['mask'] <= $i)
1022 $ret[] = array ('tag' => '$masklen_le_' . $i);
1023 if ($cell['mask'] == $i)
1024 $ret[] = array ('tag' => '$masklen_eq_' . $i);
1025 }
2c21a10c
DO
1026 $ret[] = array ('tag' => '$any_ip4net');
1027 $ret[] = array ('tag' => '$any_net');
1028 break;
1029 case 'ipv4vs':
d16af52f 1030 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
2c21a10c
DO
1031 $ret[] = array ('tag' => '$any_ipv4vs');
1032 $ret[] = array ('tag' => '$any_vs');
1033 break;
1034 case 'ipv4rspool':
d16af52f 1035 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
2c21a10c
DO
1036 $ret[] = array ('tag' => '$any_ipv4rsp');
1037 $ret[] = array ('tag' => '$any_rsp');
1038 break;
1039 case 'user':
b82cce3f
DO
1040 // {$username_XXX} autotag is generated always, but {$userid_XXX}
1041 // appears only for accounts, which exist in local database.
d16af52f
DO
1042 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
1043 if (isset ($cell['user_id']))
1044 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
2c21a10c
DO
1045 break;
1046 case 'file':
d16af52f 1047 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
2c21a10c
DO
1048 $ret[] = array ('tag' => '$any_file');
1049 break;
d16af52f 1050 default: // HCF!
2c21a10c
DO
1051 break;
1052 }
4c9d35ec
DO
1053 // {$tagless} doesn't apply to users
1054 switch ($cell['realm'])
1055 {
1056 case 'rack':
1057 case 'object':
1058 case 'ipv4net':
1059 case 'ipv4vs':
1060 case 'ipv4rspool':
1061 case 'file':
1062 if (!count ($cell['etags']))
1063 $ret[] = array ('tag' => '$untagged');
1064 break;
1065 default:
1066 break;
1067 }
f9bc186f
DO
1068 return $ret;
1069}
1070
abef7149
DO
1071// Check, if the given tag is present on the chain (will only work
1072// for regular tags with tag ID set.
1073function tagOnChain ($taginfo, $tagchain)
1074{
1075 if (!isset ($taginfo['id']))
1076 return FALSE;
1077 foreach ($tagchain as $test)
1078 if ($test['id'] == $taginfo['id'])
1079 return TRUE;
1080 return FALSE;
1081}
1082
f8821b96
DO
1083function tagNameOnChain ($tagname, $tagchain)
1084{
1085 foreach ($tagchain as $test)
1086 if ($test['tag'] == $tagname)
1087 return TRUE;
1088 return FALSE;
1089}
1090
abef7149
DO
1091// Return TRUE, if two tags chains differ (order of tags doesn't matter).
1092// Assume, that neither of the lists contains duplicates.
1093// FIXME: a faster, than O(x^2) method is possible for this calculation.
1094function tagChainCmp ($chain1, $chain2)
1095{
1096 if (count ($chain1) != count ($chain2))
1097 return TRUE;
1098 foreach ($chain1 as $taginfo1)
1099 if (!tagOnChain ($taginfo1, $chain2))
1100 return TRUE;
1101 return FALSE;
1102}
1103
53bae67b
DO
1104// If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1105// hold all appropriate (explicit and implicit) tags respectively.
1106// Otherwise some limited redirection is necessary (only page and tab
1107// names are preserved, ophandler name change isn't handled).
da958e52
DO
1108function fixContext ()
1109{
4c9b513a
DO
1110 global
1111 $pageno,
1112 $tabno,
1113 $auto_tags,
1114 $expl_tags,
1115 $impl_tags,
1116 $target_given_tags,
1117 $user_given_tags,
25186565 1118 $etype_by_pageno,
4c9b513a 1119 $page;
53bae67b
DO
1120
1121 $pmap = array
1122 (
1123 'accounts' => 'userlist',
1124 'rspools' => 'ipv4rsplist',
1125 'rspool' => 'ipv4rsp',
1126 'vservices' => 'ipv4vslist',
1127 'vservice' => 'ipv4vs',
c78a40ec
DO
1128 'objects' => 'depot',
1129 'objgroup' => 'depot',
53bae67b
DO
1130 );
1131 $tmap = array();
1132 $tmap['objects']['newmulti'] = 'addmore';
1133 $tmap['objects']['newobj'] = 'addmore';
1134 $tmap['object']['switchvlans'] = 'livevlans';
1135 $tmap['object']['slb'] = 'editrspvs';
72d8ced3
DO
1136 $tmap['object']['portfwrd'] = 'nat4';
1137 $tmap['object']['network'] = 'ipv4';
53bae67b
DO
1138 if (isset ($pmap[$pageno]))
1139 redirectUser ($pmap[$pageno], $tabno);
1140 if (isset ($tmap[$pageno][$tabno]))
1141 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1142
53da7dca
DO
1143 if (isset ($etype_by_pageno[$pageno]))
1144 {
1145 // Each page listed in the map above requires one uint argument.
1146 assertUIntArg ($page[$pageno]['bypass'], __FUNCTION__);
0a50efb4
DO
1147 $target_realm = $etype_by_pageno[$pageno];
1148 $target_id = $_REQUEST[$page[$pageno]['bypass']];
b135a49d 1149 $target = spotEntity ($target_realm, $target_id);
53da7dca
DO
1150 $target_given_tags = $target['etags'];
1151 // Don't reset autochain, because auth procedures could push stuff there in.
1152 // Another important point is to ignore 'user' realm, so we don't infuse effective
1153 // context with autotags of the displayed account.
1154 if ($pageno != 'user')
1155 $auto_tags = array_merge ($auto_tags, $target['atags']);
1156 }
4c9b513a
DO
1157 // Explicit and implicit chains should be normally empty at this point, so
1158 // overwrite the contents anyway.
1159 $expl_tags = mergeTagChains ($user_given_tags, $target_given_tags);
1160 $impl_tags = getImplicitTags ($expl_tags);
da958e52
DO
1161}
1162
abef7149
DO
1163// Take a list of user-supplied tag IDs to build a list of valid taginfo
1164// records indexed by tag IDs (tag chain).
6e49bd1f 1165function buildTagChainFromIds ($tagidlist)
ab379543 1166{
20c901a7 1167 global $taglist;
ab379543 1168 $ret = array();
abef7149 1169 foreach (array_unique ($tagidlist) as $tag_id)
ab379543
DO
1170 if (isset ($taglist[$tag_id]))
1171 $ret[] = $taglist[$tag_id];
1172 return $ret;
1173}
1174
7cc02fc1
DO
1175// Process a given tag tree and return only meaningful branches. The resulting
1176// (sub)tree will have refcnt leaves on every last branch.
a26a6ccc 1177function getObjectiveTagTree ($tree, $realm, $preselect)
7cc02fc1 1178{
51b6651a 1179 $self = __FUNCTION__;
7cc02fc1
DO
1180 $ret = array();
1181 foreach ($tree as $taginfo)
1182 {
a26a6ccc
DO
1183 $subsearch = $self ($taginfo['kids'], $realm, $preselect);
1184 // If the current node addresses something, add it to the result
1185 // regardless of how many sub-nodes it features.
1186 if
7cc02fc1 1187 (
a26a6ccc
DO
1188 isset ($taginfo['refcnt'][$realm]) or
1189 count ($subsearch) > 1 or
3fb336f6 1190 in_array ($taginfo['id'], $preselect)
a26a6ccc
DO
1191 )
1192 $ret[] = array
1193 (
1194 'id' => $taginfo['id'],
1195 'tag' => $taginfo['tag'],
1196 'parent_id' => $taginfo['parent_id'],
1197 'refcnt' => $taginfo['refcnt'],
1198 'kids' => $subsearch
1199 );
1200 else
1201 $ret = array_merge ($ret, $subsearch);
7cc02fc1
DO
1202 }
1203 return $ret;
1204}
1205
7ddb2c05
DO
1206// Get taginfo record by tag name, return NULL, if record doesn't exist.
1207function getTagByName ($target_name)
1208{
1209 global $taglist;
1210 foreach ($taglist as $taginfo)
1211 if ($taginfo['tag'] == $target_name)
1212 return $taginfo;
1213 return NULL;
1214}
1215
fc73c734
DO
1216// Merge two chains, filtering dupes out. Return the resulting superset.
1217function mergeTagChains ($chainA, $chainB)
1218{
1219 // $ret = $chainA;
1220 // Reindex by tag id in any case.
1221 $ret = array();
1222 foreach ($chainA as $tag)
1223 $ret[$tag['id']] = $tag;
1224 foreach ($chainB as $tag)
1225 if (!isset ($ret[$tag['id']]))
1226 $ret[$tag['id']] = $tag;
1227 return $ret;
1228}
1229
31c941ec
DO
1230function getCellFilter ()
1231{
7da7450c 1232 global $sic;
3d670bba 1233 if (isset ($_REQUEST['tagfilter']) and is_array ($_REQUEST['tagfilter']))
23cdc7e9
DO
1234 {
1235 $_REQUEST['cft'] = $_REQUEST['tagfilter'];
1236 unset ($_REQUEST['tagfilter']);
1237 }
3d670bba
DO
1238 $ret = array
1239 (
23cdc7e9
DO
1240 'tagidlist' => array(),
1241 'tnamelist' => array(),
1242 'pnamelist' => array(),
1243 'andor' => '',
3d670bba 1244 'text' => '',
23cdc7e9
DO
1245 'extratext' => '',
1246 'expression' => array(),
a8efc03e 1247 'urlextra' => '', // Just put text here and let makeHref call urlencode().
3d670bba 1248 );
23cdc7e9 1249 switch (TRUE)
31c941ec 1250 {
23cdc7e9
DO
1251 case (!isset ($_REQUEST['andor'])):
1252 $andor2 = getConfigVar ('FILTER_DEFAULT_ANDOR');
3d670bba 1253 break;
23cdc7e9
DO
1254 case ($_REQUEST['andor'] == 'and'):
1255 case ($_REQUEST['andor'] == 'or'):
1256 $ret['andor'] = $andor2 = $_REQUEST['andor'];
a8efc03e 1257 $ret['urlextra'] .= '&andor=' . $ret['andor'];
3d670bba
DO
1258 break;
1259 default:
23cdc7e9 1260 showError ('Invalid and/or switch value in submitted form', __FUNCTION__);
3d670bba 1261 return NULL;
31c941ec 1262 }
23cdc7e9
DO
1263 $andor1 = '';
1264 // Both tags and predicates, which don't exist, should be
1265 // handled somehow. Discard them silently for now.
1266 if (isset ($_REQUEST['cft']) and is_array ($_REQUEST['cft']))
31c941ec 1267 {
23cdc7e9
DO
1268 global $taglist;
1269 foreach ($_REQUEST['cft'] as $req_id)
1270 if (isset ($taglist[$req_id]))
1271 {
1272 $ret['tagidlist'][] = $req_id;
1273 $ret['tnamelist'][] = $taglist[$req_id]['tag'];
1274 $ret['text'] .= $andor1 . '{' . $taglist[$req_id]['tag'] . '}';
1275 $andor1 = ' ' . $andor2 . ' ';
a8efc03e 1276 $ret['urlextra'] .= '&cft[]=' . $req_id;
23cdc7e9
DO
1277 }
1278 }
1279 if (isset ($_REQUEST['cfp']) and is_array ($_REQUEST['cfp']))
1280 {
1281 global $pTable;
1282 foreach ($_REQUEST['cfp'] as $req_name)
1283 if (isset ($pTable[$req_name]))
1284 {
1285 $ret['pnamelist'][] = $req_name;
1286 $ret['text'] .= $andor1 . '[' . $req_name . ']';
1287 $andor1 = ' ' . $andor2 . ' ';
a8efc03e 1288 $ret['urlextra'] .= '&cfp[]=' . $req_name;
23cdc7e9
DO
1289 }
1290 }
7da7450c
DO
1291 // Extra text comes from TEXTAREA and is easily screwed by standard escaping function.
1292 if (isset ($sic['cfe']))
a8efc03e 1293 {
7da7450c
DO
1294 // Only consider extra text, when it is a correct RackCode expression.
1295 $parse = spotPayload ($sic['cfe'], 'SYNT_EXPR');
1296 if ($parse['result'] == 'ACK')
1297 {
1298 $ret['extratext'] = trim ($sic['cfe']);
1299 $ret['urlextra'] .= '&cfe=' . $ret['extratext'];
1300 }
a8efc03e 1301 }
23cdc7e9
DO
1302 $finaltext = array();
1303 if (strlen ($ret['text']))
1304 $finaltext[] = '(' . $ret['text'] . ')';
1305 if (strlen ($ret['extratext']))
1306 $finaltext[] = '(' . $ret['extratext'] . ')';
1307 $finaltext = implode (' ' . $andor2 . ' ', $finaltext);
1308 if (strlen ($finaltext))
1309 {
1310 $parse = spotPayload ($finaltext, 'SYNT_EXPR');
1311 $ret['expression'] = $parse['result'] == 'ACK' ? $parse['load'] : NULL;
8c699525
DO
1312 // It's not quite fair enough to put the blame of the whole text onto
1313 // non-empty "extra" portion of it, but it's the only user-generated portion
1314 // of it, thus the most probable cause of parse error.
1315 if (strlen ($ret['extratext']))
1316 $ret['extraclass'] = $parse['result'] == 'ACK' ? 'validation-success' : 'validation-error';
31c941ec 1317 }
3d670bba 1318 return $ret;
31c941ec
DO
1319}
1320
db55cf54
DO
1321// Return an empty message log.
1322function emptyLog ()
1323{
1324 return array
1325 (
1326 'v' => 2,
1327 'm' => array()
1328 );
1329}
1330
2987fc1f
DO
1331// Return a message log consisting of only one message.
1332function oneLiner ($code, $args = array())
1333{
db55cf54 1334 $ret = emptyLog();
2987fc1f
DO
1335 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1336 return $ret;
46f92ff7
DO
1337}
1338
e53b1246
DO
1339// Merge message payload from two message logs given and return the result.
1340function mergeLogs ($log1, $log2)
1341{
1342 $ret = emptyLog();
1343 $ret['m'] = array_merge ($log1['m'], $log2['m']);
1344 return $ret;
1345}
1346
9f54e6e9 1347function validTagName ($s, $allow_autotag = FALSE)
2eeeca80 1348{
9f54e6e9
DO
1349 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1350 return TRUE;
1351 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1352 return TRUE;
1353 return FALSE;
2eeeca80
DO
1354}
1355
53bae67b
DO
1356function redirectUser ($p, $t)
1357{
1358 global $page, $root;
1359 $l = "{$root}?page=${p}&tab=${t}";
1360 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1361 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1362 header ("Location: " . $l);
1363 die;
1364}
1365
9f3e5caa
DO
1366function getRackCodeStats ()
1367{
1368 global $rackCode;
914b439b 1369 $defc = $grantc = $modc = 0;
9f3e5caa
DO
1370 foreach ($rackCode as $s)
1371 switch ($s['type'])
1372 {
1373 case 'SYNT_DEFINITION':
1374 $defc++;
1375 break;
1376 case 'SYNT_GRANT':
1377 $grantc++;
1378 break;
914b439b
DO
1379 case 'SYNT_CTXMOD':
1380 $modc++;
1381 break;
9f3e5caa
DO
1382 default:
1383 break;
1384 }
914b439b
DO
1385 $ret = array
1386 (
1387 'Definition sentences' => $defc,
1388 'Grant sentences' => $grantc,
1389 'Context mod sentences' => $modc
1390 );
9f3e5caa
DO
1391 return $ret;
1392}
1393
d5157018
DO
1394function getRackImageWidth ()
1395{
529eac25
DO
1396 global $rtwidth;
1397 return 3 + $rtwidth[0] + $rtwidth[1] + $rtwidth[2] + 3;
d5157018
DO
1398}
1399
1400function getRackImageHeight ($units)
1401{
1402 return 3 + 3 + $units * 2;
1403}
1404
2987fc1f
DO
1405// Perform substitutions and return resulting string
1406// used solely by buildLVSConfig()
1407function apply_macros ($macros, $subject)
1408{
1409 $ret = $subject;
1410 foreach ($macros as $search => $replace)
1411 $ret = str_replace ($search, $replace, $ret);
1412 return $ret;
1413}
1414
1415function buildLVSConfig ($object_id = 0)
1416{
1417 if ($object_id <= 0)
1418 {
1419 showError ('Invalid argument', __FUNCTION__);
1420 return;
1421 }
6297d584 1422 $oInfo = spotEntity ('object', $object_id);
2987fc1f
DO
1423 $lbconfig = getSLBConfig ($object_id);
1424 if ($lbconfig === NULL)
1425 {
1426 showError ('getSLBConfig() failed', __FUNCTION__);
1427 return;
1428 }
1429 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1430 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1431 foreach ($lbconfig as $vs_id => $vsinfo)
1432 {
1433 $newconfig .= "########################################################\n" .
59a83bd8
DO
1434 "# VS (id == ${vs_id}): " . (!strlen ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1435 "# RS pool (id == ${vsinfo['pool_id']}): " . (!strlen ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
2987fc1f
DO
1436 "########################################################\n";
1437 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1438 $macros = array
1439 (
1440 '%VIP%' => $vsinfo['vip'],
1441 '%VPORT%' => $vsinfo['vport'],
1442 '%PROTO%' => $vsinfo['proto'],
1443 '%VNAME%' => $vsinfo['vs_name'],
1444 '%RSPOOLNAME%' => $vsinfo['pool_name']
1445 );
1446 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1447 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1448 $newconfig .= apply_macros
1449 (
1450 $macros,
1451 lf_wrap ($vsinfo['vs_vsconfig']) .
1452 lf_wrap ($vsinfo['lb_vsconfig']) .
1453 lf_wrap ($vsinfo['pool_vsconfig'])
1454 );
1455 foreach ($vsinfo['rslist'] as $rs)
1456 {
59a83bd8 1457 if (!strlen ($rs['rsport']))
79a9edb4 1458 $rs['rsport'] = $vsinfo['vport'];
2987fc1f
DO
1459 $macros['%RSIP%'] = $rs['rsip'];
1460 $macros['%RSPORT%'] = $rs['rsport'];
1461 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1462 $newconfig .= apply_macros
1463 (
1464 $macros,
1465 lf_wrap ($vsinfo['vs_rsconfig']) .
1466 lf_wrap ($vsinfo['lb_rsconfig']) .
1467 lf_wrap ($vsinfo['pool_rsconfig']) .
1468 lf_wrap ($rs['rs_rsconfig'])
1469 );
1470 $newconfig .= "\t}\n";
1471 }
1472 $newconfig .= "}\n\n\n";
1473 }
3dd72e34
DO
1474 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1475 return str_replace ("\r", '', $newconfig);
2987fc1f
DO
1476}
1477
2d318652
DO
1478// Indicate occupation state of each IP address: none, ordinary or problematic.
1479function markupIPv4AddrList (&$addrlist)
1480{
1481 foreach (array_keys ($addrlist) as $ip_bin)
1482 {
d983f70a
DO
1483 $refc = array
1484 (
00c5d8cb
DO
1485 'shared' => 0, // virtual
1486 'virtual' => 0, // loopback
1487 'regular' => 0, // connected host
1488 'router' => 0 // connected gateway
d983f70a
DO
1489 );
1490 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1491 $refc[$a['type']]++;
00c5d8cb 1492 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
d983f70a
DO
1493 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1494 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
2d318652
DO
1495
1496 if ($nrealms == 1)
1497 $addrlist[$ip_bin]['class'] = 'trbusy';
1498 elseif ($nrealms > 1)
1499 $addrlist[$ip_bin]['class'] = 'trerror';
1500 else
1501 $addrlist[$ip_bin]['class'] = '';
1502 }
1503}
1504
04d619d0
DO
1505// Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1506function findRouters ($addrlist)
1507{
1508 $ret = array();
1509 foreach ($addrlist as $addr)
1510 foreach ($addr['allocs'] as $alloc)
1511 if ($alloc['type'] == 'router')
1512 $ret[] = array
1513 (
1514 'id' => $alloc['object_id'],
1515 'iface' => $alloc['name'],
1516 'dname' => $alloc['object_name'],
1517 'addr' => $addr['ip']
1518 );
1519 return $ret;
1520}
1521
fb7a4967
DO
1522// Assist in tag chain sorting.
1523function taginfoCmp ($tagA, $tagB)
1524{
1525 return $tagA['ci'] - $tagB['ci'];
1526}
1527
1327d9dd
DO
1528// Compare networks. When sorting a tree, the records on the list will have
1529// distinct base IP addresses.
3444ecf2
DO
1530// "The comparison function must return an integer less than, equal to, or greater
1531// than zero if the first argument is considered to be respectively less than,
1532// equal to, or greater than the second." (c) PHP manual
1327d9dd
DO
1533function IPv4NetworkCmp ($netA, $netB)
1534{
2d75c30b
DO
1535 // There's a problem just substracting one u32 integer from another,
1536 // because the result may happen big enough to become a negative i32
1537 // integer itself (PHP tries to cast everything it sees to signed int)
3444ecf2
DO
1538 // The comparison below must treat positive and negative values of both
1539 // arguments.
1540 // Equal values give instant decision regardless of their [equal] sign.
1541 if ($netA['ip_bin'] == $netB['ip_bin'])
2d75c30b 1542 return 0;
3444ecf2
DO
1543 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1544 // 0x00000001~0x7fffffff 1~2147483647
1545 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1546 // 0x80000000~0xffffffff -2147483648~-1
1547 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1548 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1549 if ($signA == $signB)
1550 {
1551 if ($netA['ip_bin'] > $netB['ip_bin'])
1552 return 1;
1553 else
1554 return -1;
1555 }
1556 else // With only one of two values being negative, it... wins!
1557 {
1558 if ($netA['ip_bin'] < $netB['ip_bin'])
1559 return 1;
1560 else
1561 return -1;
1562 }
1327d9dd
DO
1563}
1564
fb7a4967 1565// Modify the given tag tree so, that each level's items are sorted alphabetically.
1327d9dd 1566function sortTree (&$tree, $sortfunc = '')
fb7a4967 1567{
59a83bd8 1568 if (!strlen ($sortfunc))
1327d9dd 1569 return;
51b6651a 1570 $self = __FUNCTION__;
1327d9dd 1571 usort ($tree, $sortfunc);
fb7a4967
DO
1572 // Don't make a mistake of directly iterating over the items of current level, because this way
1573 // the sorting will be performed on a _copy_ if each item, not the item itself.
1574 foreach (array_keys ($tree) as $tagid)
51b6651a 1575 $self ($tree[$tagid]['kids'], $sortfunc);
fb7a4967
DO
1576}
1577
0137d53c
DO
1578function iptree_fill (&$netdata)
1579{
59a83bd8 1580 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
0137d53c 1581 return;
a987ff52 1582 // If we really have nested prefixes, they must fit into the tree.
0137d53c
DO
1583 $worktree = array
1584 (
1585 'ip_bin' => $netdata['ip_bin'],
1586 'mask' => $netdata['mask']
1587 );
1588 foreach ($netdata['kids'] as $pfx)
1589 iptree_embed ($worktree, $pfx);
1590 $netdata['kids'] = iptree_construct ($worktree);
1591 $netdata['kidc'] = count ($netdata['kids']);
1592}
1593
1594function iptree_construct ($node)
1595{
1596 $self = __FUNCTION__;
1597
1598 if (!isset ($node['right']))
1599 {
1600 if (!isset ($node['ip']))
1601 {
1602 $node['ip'] = long2ip ($node['ip_bin']);
1603 $node['kids'] = array();
fec0c8da 1604 $node['kidc'] = 0;
0137d53c
DO
1605 $node['name'] = '';
1606 }
1607 return array ($node);
1608 }
1609 else
1610 return array_merge ($self ($node['left']), $self ($node['right']));
1611}
1612
1613function iptree_embed (&$node, $pfx)
1614{
1615 $self = __FUNCTION__;
1616
1617 // hit?
1618 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1619 {
1620 $node = $pfx;
1621 return;
1622 }
1623 if ($node['mask'] == $pfx['mask'])
1624 {
1625 showError ('Internal error, the recurring loop lost control', __FUNCTION__);
1626 die;
1627 }
1628
1629 // split?
1630 if (!isset ($node['right']))
1631 {
a987ff52
DO
1632 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
1633 $node['left']['mask'] = $node['mask'] + 1;
0137d53c 1634 $node['left']['ip_bin'] = $node['ip_bin'];
a987ff52
DO
1635 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
1636 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] | binInvMaskFromDec ($node['left']['mask']));
1637
1638 $node['right']['mask'] = $node['mask'] + 1;
0137d53c 1639 $node['right']['ip_bin'] = $node['ip_bin'] + binInvMaskFromDec ($node['mask'] + 1) + 1;
a987ff52
DO
1640 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
1641 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] | binInvMaskFromDec ($node['right']['mask']));
0137d53c
DO
1642 }
1643
1644 // repeat!
1645 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1646 $self ($node['left'], $pfx);
1647 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1648 $self ($node['right'], $pfx);
1649 else
1650 {
1651 showError ('Internal error, cannot decide between left and right', __FUNCTION__);
1652 die;
1653 }
1654}
1655
3b81cb98 1656function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
0137d53c 1657{
59a83bd8 1658 if (!strlen ($func))
0137d53c
DO
1659 return;
1660 $self = __FUNCTION__;
1661 foreach (array_keys ($tree) as $key)
1662 {
1663 $func ($tree[$key]);
59a83bd8 1664 if (strlen ($stopfunc) and $stopfunc ($tree[$key]))
c3315231 1665 continue;
0137d53c
DO
1666 $self ($tree[$key]['kids'], $func);
1667 }
1668}
1669
a987ff52
DO
1670function loadIPv4AddrList (&$netinfo)
1671{
1672 loadOwnIPv4Addresses ($netinfo);
1673 markupIPv4AddrList ($netinfo['addrlist']);
1674}
b18d26dc 1675
b6b87070 1676function countOwnIPv4Addresses (&$node)
b18d26dc 1677{
b6b87070 1678 $toscan = array();
737a3f72 1679 $node['addrt'] = 0;
4d0dbd87
DO
1680 $node['mask_bin'] = binMaskFromDec ($node['mask']);
1681 $node['mask_bin_inv'] = binInvMaskFromDec ($node['mask']);
1682 $node['db_first'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] & $node['mask_bin']);
1683 $node['db_last'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] | ($node['mask_bin_inv']));
59a83bd8 1684 if (!count ($node['kids']))
737a3f72 1685 {
f7414fa5 1686 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
737a3f72
DO
1687 $node['addrt'] = binInvMaskFromDec ($node['mask']) + 1;
1688 }
b18d26dc 1689 else
b6b87070 1690 foreach ($node['kids'] as $nested)
b18d26dc 1691 if (!isset ($nested['id'])) // spare
737a3f72 1692 {
f7414fa5 1693 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
737a3f72
DO
1694 $node['addrt'] += binInvMaskFromDec ($nested['mask']) + 1;
1695 }
4d0dbd87
DO
1696 // Don't do anything more, because the displaying function will load the addresses anyway.
1697 return;
f7414fa5 1698 $node['addrc'] = count (scanIPv4Space ($toscan));
b6b87070
DO
1699}
1700
c3315231
DO
1701function nodeIsCollapsed ($node)
1702{
1703 return $node['symbol'] == 'node-collapsed';
1704}
1705
b6b87070
DO
1706function loadOwnIPv4Addresses (&$node)
1707{
1708 $toscan = array();
43eb71f1 1709 if (!isset ($node['kids']) or !count ($node['kids']))
f7414fa5 1710 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
b6b87070
DO
1711 else
1712 foreach ($node['kids'] as $nested)
1713 if (!isset ($nested['id'])) // spare
f7414fa5
DO
1714 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1715 $node['addrlist'] = scanIPv4Space ($toscan);
b6b87070 1716 $node['addrc'] = count ($node['addrlist']);
b18d26dc
DO
1717}
1718
fec0c8da
DO
1719function prepareIPv4Tree ($netlist, $expanded_id = 0)
1720{
573214e0
DO
1721 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
1722 // so perform necessary pre-processing to make orphans belong to root. This trick
1723 // was earlier performed by getIPv4NetworkList().
1724 $netids = array_keys ($netlist);
1725 foreach ($netids as $cid)
1726 if (!in_array ($netlist[$cid]['parent_id'], $netids))
1727 $netlist[$cid]['parent_id'] = NULL;
fec0c8da
DO
1728 $tree = treeFromList ($netlist); // medium call
1729 sortTree ($tree, 'IPv4NetworkCmp');
fec0c8da 1730 // complement the tree before markup to make the spare networks have "symbol" set
c3315231
DO
1731 treeApplyFunc ($tree, 'iptree_fill');
1732 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
1733 // count addresses after the markup to skip computation for hidden tree nodes
1734 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
fec0c8da
DO
1735 return $tree;
1736}
1737
1738// Check all items of the tree recursively, until the requested target id is
1739// found. Mark all items leading to this item as "expanded", collapsing all
1740// the rest, which exceed the given threshold (if the threshold is given).
1741function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
1742{
1743 $self = __FUNCTION__;
1744 $ret = FALSE;
1745 foreach (array_keys ($tree) as $key)
1746 {
5388794d 1747 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
fec0c8da
DO
1748 $below = $self ($tree[$key]['kids'], $threshold, $target);
1749 if (!$tree[$key]['kidc']) // terminal node
1750 $tree[$key]['symbol'] = 'spacer';
1751 elseif ($tree[$key]['kidc'] < $threshold)
1752 $tree[$key]['symbol'] = 'node-expanded-static';
1753 elseif ($here or $below)
1754 $tree[$key]['symbol'] = 'node-expanded';
1755 else
1756 $tree[$key]['symbol'] = 'node-collapsed';
1757 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
1758 }
1759 return $ret;
1760}
1761
e1ae3fb4
AD
1762// Convert entity name to human-readable value
1763function formatEntityName ($name) {
1764 switch ($name)
1765 {
1766 case 'ipv4net':
1767 return 'IPv4 Network';
1768 case 'ipv4rspool':
1769 return 'IPv4 RS Pool';
1770 case 'ipv4vs':
1771 return 'IPv4 Virtual Service';
1772 case 'object':
1773 return 'Object';
1774 case 'rack':
1775 return 'Rack';
1776 case 'user':
1777 return 'User';
1778 }
1779 return 'invalid';
1780}
1781
1782// Take a MySQL or other generic timestamp and make it prettier
1783function formatTimestamp ($timestamp) {
1784 return date('n/j/y g:iA', strtotime($timestamp));
1785}
1786
8bc5d1e4
DO
1787// Display hrefs for all of a file's parents. If scissors are requested,
1788// prepend cutting button to each of them.
1789function serializeFileLinks ($links, $scissors = FALSE)
e1ae3fb4
AD
1790{
1791 global $root;
1792
1793 $comma = '';
1794 $ret = '';
1795 foreach ($links as $link_id => $li)
1796 {
1797 switch ($li['entity_type'])
1798 {
1799 case 'ipv4net':
1800 $params = "page=ipv4net&id=";
1801 break;
1802 case 'ipv4rspool':
1803 $params = "page=ipv4rspool&pool_id=";
1804 break;
1805 case 'ipv4vs':
1806 $params = "page=ipv4vs&vs_id=";
1807 break;
1808 case 'object':
1809 $params = "page=object&object_id=";
1810 break;
1811 case 'rack':
1812 $params = "page=rack&rack_id=";
1813 break;
1814 case 'user':
1815 $params = "page=user&user_id=";
1816 break;
1817 }
8bc5d1e4
DO
1818 $ret .= $comma;
1819 if ($scissors)
1820 {
1821 $ret .= "<a href='" . makeHrefProcess(array('op'=>'unlinkFile', 'link_id'=>$link_id)) . "'";
1822 $ret .= getImageHREF ('cut') . '</a> ';
1823 }
1824 $ret .= sprintf("<a href='%s?%s%s'>%s</a>", $root, $params, $li['entity_id'], $li['name']);
1825 $comma = '<br>';
e1ae3fb4 1826 }
e1ae3fb4
AD
1827 return $ret;
1828}
1829
1830// Convert filesize to appropriate unit and make it human-readable
1831function formatFileSize ($bytes) {
1832 // bytes
1833 if($bytes < 1024) // bytes
1834 return "${bytes} bytes";
1835
1836 // kilobytes
1837 if ($bytes < 1024000)
1838 return sprintf ("%.1fk", round (($bytes / 1024), 1));
1839
1840 // megabytes
1841 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
1842}
1843
1844// Reverse of formatFileSize, it converts human-readable value to bytes
1845function convertToBytes ($value) {
1846 $value = trim($value);
1847 $last = strtolower($value[strlen($value)-1]);
1848 switch ($last)
1849 {
1850 case 'g':
1851 $value *= 1024;
1852 case 'm':
1853 $value *= 1024;
1854 case 'k':
1855 $value *= 1024;
1856 }
1857
1858 return $value;
1859}
1860
4fbb5a00
DY
1861function ip_quad2long ($ip)
1862{
1863 return sprintf("%u", ip2long($ip));
1864}
1865
1866function ip_long2quad ($quad)
1867{
1868 return long2ip($quad);
1869}
1870
1871function makeHref($params = array())
1872{
1873 global $head_revision, $numeric_revision, $root;
1874 $ret = $root.'?';
1875 $first = true;
1876 if (!isset($params['r']) and ($numeric_revision != $head_revision))
1877 {
1878 $params['r'] = $numeric_revision;
1879 }
1880 foreach($params as $key=>$value)
1881 {
1882 if (!$first)
1883 $ret.='&';
1884 $ret .= urlencode($key).'='.urlencode($value);
1885 $first = false;
1886 }
1887 return $ret;
1888}
1889
1890function makeHrefProcess($params = array())
1891{
1892 global $head_revision, $numeric_revision, $root, $pageno, $tabno;
1893 $ret = $root.'process.php'.'?';
1894 $first = true;
1895 if ($numeric_revision != $head_revision)
1896 {
1897 error_log("Can't make a process link when not in head revision");
1898 die();
1899 }
9f14a7ef
DY
1900 if (!isset($params['page']))
1901 $params['page'] = $pageno;
1902 if (!isset($params['tab']))
1903 $params['tab'] = $tabno;
4fbb5a00
DY
1904 foreach($params as $key=>$value)
1905 {
1906 if (!$first)
1907 $ret.='&';
1908 $ret .= urlencode($key).'='.urlencode($value);
1909 $first = false;
1910 }
1911 return $ret;
1912}
1913
39106006 1914function makeHrefForHelper ($helper_name, $params = array())
4fbb5a00
DY
1915{
1916 global $head_revision, $numeric_revision, $root;
e8dd0422 1917 $ret = $root.'popup.php'.'?helper='.$helper_name;
4fbb5a00
DY
1918 if ($numeric_revision != $head_revision)
1919 {
1920 error_log("Can't make a process link when not in head revision");
1921 die();
1922 }
1923 foreach($params as $key=>$value)
39106006 1924 $ret .= '&'.urlencode($key).'='.urlencode($value);
4fbb5a00
DY
1925 return $ret;
1926}
1927
f3d274bf
DO
1928// Process the given list of records to build data suitable for printNiftySelect()
1929// (like it was formerly executed by printSelect()). Screen out vendors according
1930// to VENDOR_SIEVE, if object type ID is provided. However, the OPTGROUP with already
1931// selected OPTION is protected from being screened.
1932function cookOptgroups ($recordList, $object_type_id = 0, $existing_value = 0)
1933{
1934 $ret = array();
1935 // Always keep "other" OPTGROUP at the SELECT bottom.
1936 $therest = array();
1937 foreach ($recordList as $dict_key => $dict_value)
1938 if (strpos ($dict_value, '%GSKIP%') !== FALSE)
1939 {
1940 $tmp = explode ('%GSKIP%', $dict_value, 2);
1941 $ret[$tmp[0]][$dict_key] = $tmp[1];
1942 }
1943 elseif (strpos ($dict_value, '%GPASS%') !== FALSE)
1944 {
1945 $tmp = explode ('%GPASS%', $dict_value, 2);
1946 $ret[$tmp[0]][$dict_key] = $tmp[1];
1947 }
1948 else
1949 $therest[$dict_key] = $dict_value;
1950 if ($object_type_id != 0)
1951 {
1952 $screenlist = array();
1953 foreach (explode (';', getConfigVar ('VENDOR_SIEVE')) as $sieve)
1954 if (FALSE !== mb_ereg ("^([^@]+)(@${object_type_id})?\$", trim ($sieve), $regs))
1955 $screenlist[] = $regs[1];
1956 foreach (array_keys ($ret) as $vendor)
1957 if (in_array ($vendor, $screenlist))
1958 {
1959 $ok_to_screen = TRUE;
1960 if ($existing_value)
1961 foreach (array_keys ($ret[$vendor]) as $recordkey)
1962 if ($recordkey == $existing_value)
1963 {
1964 $ok_to_screen = FALSE;
1965 break;
1966 }
1967 if ($ok_to_screen)
1968 unset ($ret[$vendor]);
1969 }
1970 }
1971 $ret['other'] = $therest;
1972 return $ret;
1973}
1974
f8874cdb
DO
1975function dos2unix ($text)
1976{
1977 return str_replace ("\r\n", "\n", $text);
1978}
1979
a0527aef 1980function buildPredicateTable ($parsetree)
2c21a10c 1981{
a0527aef
DO
1982 $ret = array();
1983 foreach ($parsetree as $sentence)
72e8baf6 1984 if ($sentence['type'] == 'SYNT_DEFINITION')
a0527aef 1985 $ret[$sentence['term']] = $sentence['definition'];
72e8baf6
DO
1986 // Now we have predicate table filled in with the latest definitions of each
1987 // particular predicate met. This isn't as chik, as on-the-fly predicate
1988 // overloading during allow/deny scan, but quite sufficient for this task.
a0527aef
DO
1989 return $ret;
1990}
1991
1992// Take a list of records and filter against given RackCode expression. Return
1993// the original list intact, if there was no filter requested, but return an
1994// empty list, if there was an error.
573214e0 1995function filterCellList ($list_in, $expression = array())
d08d766d
DO
1996{
1997 if ($expression === NULL)
1998 return array();
1999 if (!count ($expression))
2000 return $list_in;
d08d766d
DO
2001 $list_out = array();
2002 foreach ($list_in as $item_key => $item_value)
573214e0 2003 if (TRUE === judgeCell ($item_value, $expression))
d08d766d
DO
2004 $list_out[$item_key] = $item_value;
2005 return $list_out;
2006}
2007
212c9d8a 2008// Tell, if the given expression is true for the given entity. Take complete record on input.
573214e0 2009function judgeCell ($cell, $expression)
d08d766d
DO
2010{
2011 global $pTable;
2012 return eval_expression
2013 (
2014 $expression,
2015 array_merge
2016 (
573214e0
DO
2017 $cell['etags'],
2018 $cell['itags'],
2019 $cell['atags']
d08d766d
DO
2020 ),
2021 $pTable,
2022 TRUE
2023 );
2024}
2025
7ddbcf59 2026// Tell, if a constraint from config option permits given record.
212c9d8a 2027function considerConfiguredConstraint ($cell, $varname)
c6bc0ac5 2028{
7ddbcf59 2029 if (!strlen (getConfigVar ($varname)))
c6bc0ac5 2030 return TRUE; // no restriction
7ddbcf59
DO
2031 global $parseCache;
2032 if (!isset ($parseCache[$varname]))
2033 // getConfigVar() doesn't re-read the value from DB because of its
2034 // own cache, so there is no race condition here between two calls.
2035 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
2036 if ($parseCache[$varname]['result'] != 'ACK')
2037 return FALSE; // constraint set, but cannot be used due to compilation error
212c9d8a 2038 return judgeCell ($cell, $parseCache[$varname]['load']);
c6bc0ac5
DO
2039}
2040
17112e81
DO
2041// Return list of records in the given realm, which conform to
2042// the given RackCode expression. If the realm is unknown or text
2043// doesn't validate as a RackCode expression, return NULL.
2044// Otherwise (successful scan) return a list of all matched
2045// records, even if the list is empty (array() !== NULL). If the
2046// text is an empty string, return all found records in the given
2047// realm.
2048function scanRealmByText ($realm = NULL, $ftext = '')
2049{
2050 switch ($realm)
2051 {
2052 case 'object':
2053 case 'user':
2054 case 'ipv4net':
2055 case 'file':
39776127 2056 case 'ipv4vs':
41780975 2057 case 'ipv4rspool':
17112e81
DO
2058 if (!strlen ($ftext = trim ($ftext)))
2059 $fexpr = array();
2060 else
2061 {
2062 $fparse = spotPayload ($ftext, 'SYNT_EXPR');
2063 if ($fparse['result'] != 'ACK')
2064 return NULL;
2065 $fexpr = $fparse['load'];
2066 }
2067 return filterCellList (listCells ($realm), $fexpr);
2068 default:
c5f84f48 2069 throw new InvalidArgException ('$realm', $realm);
17112e81
DO
2070 }
2071
2072}
39776127
DO
2073
2074function getIPv4VSOptions ()
2075{
2076 $ret = array();
2077 foreach (listCells ('ipv4vs') as $vsid => $vsinfo)
59a83bd8 2078 $ret[$vsid] = $vsinfo['dname'] . (!strlen ($vsinfo['name']) ? '' : " (${vsinfo['name']})");
39776127
DO
2079 return $ret;
2080}
2081
41780975
DO
2082function getIPv4RSPoolOptions ()
2083{
2084 $ret = array();
2085 foreach (listCells ('ipv4rspool') as $pool_id => $poolInfo)
2086 $ret[$pool_id] = $poolInfo['name'];
2087 return $ret;
2088}
2089
d16af52f
DO
2090// Derive a complete cell structure from the given username regardless
2091// if it is a local account or not.
2092function constructUserCell ($username)
2093{
2094 if (NULL !== ($userid = getUserIDByUsername ($username)))
2095 return spotEntity ('user', $userid);
2096 $ret = array
2097 (
2098 'realm' => 'user',
2099 'user_name' => $username,
2100 'user_realname' => '',
2101 'etags' => array(),
2102 'itags' => array(),
d16af52f 2103 );
5689cefd 2104 $ret['atags'] = generateEntityAutoTags ($ret);
d16af52f
DO
2105 return $ret;
2106}
2107
56a797ef
DO
2108// Let's have this debug helper here to enable debugging of process.php w/o interface.php.
2109function dump ($var)
2110{
2111 echo '<div align=left><pre>';
2112 print_r ($var);
2113 echo '</pre></div>';
2114}
2115
9e51318b
DO
2116function getTagChart ($limit = 0, $realm = 'total', $special_tags = array())
2117{
2118 global $taglist;
2119 // first build top-N chart...
2120 $toplist = array();
2121 foreach ($taglist as $taginfo)
2122 if (isset ($taginfo['refcnt'][$realm]))
2123 $toplist[$taginfo['id']] = $taginfo['refcnt'][$realm];
2124 arsort ($toplist, SORT_NUMERIC);
2125 $ret = array();
2126 $done = 0;
2127 foreach (array_keys ($toplist) as $tag_id)
2128 {
2129 $ret[$tag_id] = $taglist[$tag_id];
2130 if (++$done == $limit)
2131 break;
2132 }
2133 // ...then make sure, that every item of the special list is shown
2134 // (using the same sort order)
2135 $extra = array();
2136 foreach ($special_tags as $taginfo)
2137 if (!array_key_exists ($taginfo['id'], $ret))
2138 $extra[$taginfo['id']] = $taglist[$taginfo['id']]['refcnt'][$realm];
2139 arsort ($extra, SORT_NUMERIC);
2140 foreach (array_keys ($extra) as $tag_id)
2141 $ret[] = $taglist[$tag_id];
2142 return $ret;
2143}
2144
7fa7047a
DO
2145function decodeObjectType ($objtype_id, $style = 'r')
2146{
2147 static $types = array();
2148 if (!count ($types))
2149 $types = array
2150 (
2151 'r' => readChapter (CHAP_OBJTYPE),
2152 'a' => readChapter (CHAP_OBJTYPE, 'a'),
2153 'o' => readChapter (CHAP_OBJTYPE, 'o')
2154 );
2155 return $types[$style][$objtype_id];
2156}
2157
e673ee24 2158?>