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