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