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