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