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