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