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