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