r2879 - pull {$untagged} into trunk
[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 );
38
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.
42 function displayedName ($objectData)
43 {
44 if ($objectData['name'] != '')
45 return $objectData['name'];
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 }
54 else
55 {
56 if (considerConfiguredConstraint (spotEntity ('object', $objectData['id']), 'NAMEWARN_LISTSRC'))
57 return "ANONYMOUS " . $objectData['objtype_name'];
58 else
59 return "[${objectData['objtype_name']}]";
60 }
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.
66 function 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;
83 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
84 break 2;
85 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
86 break 2;
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);
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";
104 return $height;
105 }
106
107 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
108 // attributes.
109 function 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.
120 // Explicitly show even single-cell spanned atoms, because rectHeight()
121 // is expeciting this data for correct calculation.
122 if ($colspan != 0)
123 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
124 else
125 {
126 $colspan = $templateWidth[$template_idx];
127 if ($colspan >= 1)
128 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
129 if ($maxheight >= 1)
130 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
131 }
132 }
133 }
134 }
135 return;
136 }
137
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.
141 function markAllSpans (&$rackData = NULL)
142 {
143 if ($rackData == NULL)
144 {
145 showError ('Invalid rackData', __FUNCTION__);
146 return;
147 }
148 for ($i = $rackData['height']; $i > 0; $i--)
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).
154 function markBestSpan (&$rackData, $i)
155 {
156 global $template, $templateWidth;
157 for ($j = 0; $j < 6; $j++)
158 {
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)
169 {
170 $best_template_index = $j;
171 $bestheight = $height[$j];
172 break;
173 }
174 // distribute span marks
175 markSpan ($rackData, $i, $bestheight, $best_template_index);
176 return TRUE;
177 }
178
179 // We can mount 'F' atoms and unmount our own 'T' atoms.
180 function 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.
198 function 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'.
214 function 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
229 // This function highlights specified object (and removes previous highlight).
230 function 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.
245 function 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.
263 function 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
279 // netmask conversion from length to number
280 function binMaskFromDec ($maskL)
281 {
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];
318 }
319
320 // complementary value
321 function binInvMaskFromDec ($maskL)
322 {
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];
359 }
360
361 // This function looks up 'has_problems' flag for 'T' atoms
362 // and modifies 'hl' key. May be, this should be better done
363 // in amplifyCell(). We don't honour 'skipped' key, because
364 // the function is also used for thumb creation.
365 function 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 {
371 $object = spotEntity ('object', $rackData[$i][$locidx]['object_id']);
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
383 function search_cmpObj ($a, $b)
384 {
385 return ($a['score'] > $b['score'] ? -1 : 1);
386 }
387
388 function getObjectSearchResults ($terms)
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.
401 function l2addressForDatabase ($string)
402 {
403 $string = strtoupper ($string);
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));
419 case (preg_match (RE_L2_IPCFG, $string)):
420 return implode ('', explode ('-', $string));
421 default:
422 return NULL;
423 }
424 }
425
426 function 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().
444 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
445 {
446 if ($row_id <= 0 or $rack_id <= 0)
447 {
448 showError ('Invalid arguments passed', __FUNCTION__);
449 return NULL;
450 }
451 $rackList = listCells ('rack', $row_id);
452 doubleLink ($rackList);
453 if (isset ($rackList[$rack_id]['prev_key']))
454 return $rackList[$rack_id]['prev_key'];
455 return NULL;
456 }
457
458 function getNextIDforRack ($row_id = 0, $rack_id = 0)
459 {
460 if ($row_id <= 0 or $rack_id <= 0)
461 {
462 showError ('Invalid arguments passed', __FUNCTION__);
463 return NULL;
464 }
465 $rackList = listCells ('rack', $row_id);
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.
474 function 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
488 function 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
529 function sortByName ($a, $b)
530 {
531 return sortTokenize($a['name'], $b['name']);
532 }
533
534 function 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
544 function sortObjectAddressesAndNames ($a, $b)
545 {
546 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
547 if ($objname_cmp == 0)
548 {
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);
552 if ($objname_cmp == 0)
553 sortTokenize($a['ip'], $b['ip']);
554 return $objname_cmp;
555 }
556 return $objname_cmp;
557 }
558
559 function sortAddresses ($a, $b)
560 {
561 $name_cmp = sortTokenize($a['name'], $b['name']);
562 if ($name_cmp == 0)
563 {
564 return sortTokenize($a['ip'], $b['ip']);
565 }
566 return $name_cmp;
567 }
568
569 // This function expands port compat list into a matrix.
570 function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
571 {
572 $matrix = array();
573 // Create type matrix and markup compatible types.
574 foreach (array_keys ($portTypeList) as $type1)
575 foreach (array_keys ($portTypeList) as $type2)
576 $matrix[$type1][$type2] = FALSE;
577 foreach ($portCompatList as $pair)
578 $matrix[$pair['type1']][$pair['type2']] = TRUE;
579 return $matrix;
580 }
581
582 // This function returns an array of single element of object's FQDN attribute,
583 // if FQDN is set. The next choice is object's common name, if it looks like a
584 // hostname. Otherwise an array of all 'regular' IP addresses of the
585 // object is returned (which may appear 0 and more elements long).
586 function findAllEndpoints ($object_id, $fallback = '')
587 {
588 $values = getAttrValues ($object_id);
589 foreach ($values as $record)
590 if ($record['name'] == 'FQDN' && strlen ($record['value']))
591 return array ($record['value']);
592 $regular = array();
593 foreach (getObjectIPv4Allocations ($object_id) as $dottedquad => $alloc)
594 if ($alloc['type'] == 'regular')
595 $regular[] = $dottedquad;
596 if (!count ($regular) && strlen ($fallback))
597 return array ($fallback);
598 return $regular;
599 }
600
601 // Some records in the dictionary may be written as plain text or as Wiki
602 // link in the following syntax:
603 // 1. word
604 // 2. [[word URL]] // FIXME: this isn't working
605 // 3. [[word word word | URL]]
606 // This function parses the line and returns text suitable for either A
607 // (rendering <A HREF>) or O (for <OPTION>).
608 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
609 {
610 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
611 {
612 if ($strip_optgroup)
613 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
614 else
615 return $line;
616 }
617 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
618 $s = explode ('|', $line);
619 $o_value = trim ($s[0]);
620 if ($strip_optgroup)
621 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
622 $a_value = trim ($s[1]);
623 if ($which == 'a')
624 return "<a href='${a_value}'>${o_value}</a>";
625 if ($which == 'o')
626 return $o_value;
627 }
628
629 // rackspace usage for a single rack
630 // (T + W + U) / (height * 3 - A)
631 function getRSUforRack ($data = NULL)
632 {
633 if ($data == NULL)
634 {
635 showError ('Invalid argument', __FUNCTION__);
636 return NULL;
637 }
638 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
639 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
640 for ($locidx = 0; $locidx < 3; $locidx++)
641 $counter[$data[$unit_no][$locidx]['state']]++;
642 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
643 }
644
645 // Same for row.
646 function getRSUforRackRow ($rowData = NULL)
647 {
648 if ($rowData === NULL)
649 {
650 showError ('Invalid argument', __FUNCTION__);
651 return NULL;
652 }
653 if (!count ($rowData))
654 return 0;
655 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
656 $total_height = 0;
657 foreach (array_keys ($rowData) as $rack_id)
658 {
659 $data = spotEntity ('rack', $rack_id);
660 amplifyCell ($data);
661 $total_height += $data['height'];
662 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
663 for ($locidx = 0; $locidx < 3; $locidx++)
664 $counter[$data[$unit_no][$locidx]['state']]++;
665 }
666 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
667 }
668
669 // Make sure the string is always wrapped with LF characters
670 function lf_wrap ($str)
671 {
672 $ret = trim ($str, "\r\n");
673 if (strlen ($ret))
674 $ret .= "\n";
675 return $ret;
676 }
677
678 // Adopted from Mantis BTS code.
679 function string_insert_hrefs ($s)
680 {
681 if (getConfigVar ('DETECT_URLS') != 'yes')
682 return $s;
683 # Find any URL in a string and replace it by a clickable link
684 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
685 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
686 $s);
687 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
688 '<a href="mailto:\0">\0</a>',
689 $s);
690 return $s;
691 }
692
693 // Idem.
694 function email_regex_simple ()
695 {
696 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
697 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
698 }
699
700 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
701 // for the requested object_type_id.
702 function getAutoPorts ($type_id)
703 {
704 $ret = array();
705 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
706 foreach ($typemap as $equation)
707 {
708 $tmp = explode ('=', $equation);
709 if (count ($tmp) != 2)
710 continue;
711 $objtype_id = $tmp[0];
712 if ($objtype_id != $type_id)
713 continue;
714 $portlist = $tmp[1];
715 foreach (explode ('+', $portlist) as $product)
716 {
717 $tmp = explode ('*', $product);
718 if (count ($tmp) != 3)
719 continue;
720 $nports = $tmp[0];
721 $port_type = $tmp[1];
722 $format = $tmp[2];
723 for ($i = 0; $i < $nports; $i++)
724 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
725 }
726 }
727 return $ret;
728 }
729
730 // Use pre-served trace to traverse the tree, then place given node where it belongs.
731 function pokeNode (&$tree, $trace, $key, $value, $threshold = 0)
732 {
733 // This function needs the trace to be followed FIFO-way. The fastest
734 // way to do so is to use array_push() for putting values into the
735 // list and array_shift() for getting them out. This exposed up to 11%
736 // performance gain compared to other patterns of array_push/array_unshift/
737 // array_reverse/array_pop/array_shift conjunction.
738 $myid = array_shift ($trace);
739 if (!count ($trace)) // reached the target
740 {
741 if (!$threshold or ($threshold and $tree[$myid]['kidc'] + 1 < $threshold))
742 $tree[$myid]['kids'][$key] = $value;
743 // Reset accumulated records once, when the limit is reached, not each time
744 // after that.
745 if (++$tree[$myid]['kidc'] == $threshold)
746 $tree[$myid]['kids'] = array();
747 }
748 else // not yet
749 {
750 $self = __FUNCTION__;
751 $self ($tree[$myid]['kids'], $trace, $key, $value, $threshold);
752 }
753 }
754
755 // Build a tree from the item list and return it. Input and output data is
756 // indexed by item id (nested items in output are recursively stored in 'kids'
757 // key, which is in turn indexed by id. Functions, which are ready to handle
758 // tree collapsion/expansion themselves, may request non-zero threshold value
759 // for smaller resulting tree.
760 function treeFromList ($nodelist, $threshold = 0, $return_main_payload = TRUE)
761 {
762 $tree = array();
763 // Array equivalent of traceEntity() function.
764 $trace = array();
765 // set kidc and kids only once
766 foreach (array_keys ($nodelist) as $nodeid)
767 {
768 $nodelist[$nodeid]['kidc'] = 0;
769 $nodelist[$nodeid]['kids'] = array();
770 }
771 do
772 {
773 $nextpass = FALSE;
774 foreach (array_keys ($nodelist) as $nodeid)
775 {
776 // When adding a node to the working tree, book another
777 // iteration, because the new item could make a way for
778 // others onto the tree. Also remove any item added from
779 // the input list, so iteration base shrinks.
780 // First check if we can assign directly.
781 if ($nodelist[$nodeid]['parent_id'] == NULL)
782 {
783 $tree[$nodeid] = $nodelist[$nodeid];
784 $trace[$nodeid] = array(); // Trace to root node is empty
785 unset ($nodelist[$nodeid]);
786 $nextpass = TRUE;
787 }
788 // Now look if it fits somewhere on already built tree.
789 elseif (isset ($trace[$nodelist[$nodeid]['parent_id']]))
790 {
791 // Trace to a node is a trace to its parent plus parent id.
792 $trace[$nodeid] = $trace[$nodelist[$nodeid]['parent_id']];
793 $trace[$nodeid][] = $nodelist[$nodeid]['parent_id'];
794 pokeNode ($tree, $trace[$nodeid], $nodeid, $nodelist[$nodeid], $threshold);
795 // path to any other node is made of all parent nodes plus the added node itself
796 unset ($nodelist[$nodeid]);
797 $nextpass = TRUE;
798 }
799 }
800 }
801 while ($nextpass);
802 if ($return_main_payload)
803 return $tree;
804 else
805 return $nodelist;
806 }
807
808 // Build a tree from the tag list and return everything _except_ the tree.
809 // IOW, return taginfo items, which have parent_id set and pointing outside
810 // of the "normal" tree, which originates from the root.
811 function getOrphanedTags ()
812 {
813 global $taglist;
814 return treeFromList ($taglist, 0, FALSE);
815 }
816
817 function serializeTags ($chain, $baseurl = '')
818 {
819 $comma = '';
820 $ret = '';
821 foreach ($chain as $taginfo)
822 {
823 $ret .= $comma .
824 ($baseurl == '' ? '' : "<a href='${baseurl}cft[]=${taginfo['id']}'>") .
825 $taginfo['tag'] .
826 ($baseurl == '' ? '' : '</a>');
827 $comma = ', ';
828 }
829 return $ret;
830 }
831
832 // For each tag add all its parent tags onto the list. Don't expect anything
833 // except user's tags on the chain.
834 function getTagChainExpansion ($chain, $tree = NULL)
835 {
836 $self = __FUNCTION__;
837 if ($tree === NULL)
838 {
839 global $tagtree;
840 $tree = $tagtree;
841 }
842 // For each tag find its path from the root, then combine items
843 // of all paths and add them to the chain, if they aren't there yet.
844 $ret = array();
845 foreach ($tree as $taginfo1)
846 {
847 $hit = FALSE;
848 foreach ($chain as $taginfo2)
849 if ($taginfo1['id'] == $taginfo2['id'])
850 {
851 $hit = TRUE;
852 break;
853 }
854 if (count ($taginfo1['kids']) > 0)
855 {
856 $subsearch = $self ($chain, $taginfo1['kids']);
857 if (count ($subsearch))
858 {
859 $hit = TRUE;
860 $ret = array_merge ($ret, $subsearch);
861 }
862 }
863 if ($hit)
864 $ret[] = $taginfo1;
865 }
866 return $ret;
867 }
868
869 // Return the list of missing implicit tags.
870 function getImplicitTags ($oldtags)
871 {
872 $ret = array();
873 $newtags = getTagChainExpansion ($oldtags);
874 foreach ($newtags as $newtag)
875 {
876 $already_exists = FALSE;
877 foreach ($oldtags as $oldtag)
878 if ($newtag['id'] == $oldtag['id'])
879 {
880 $already_exists = TRUE;
881 break;
882 }
883 if ($already_exists)
884 continue;
885 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
886 }
887 return $ret;
888 }
889
890 // Minimize the chain: exclude all implicit tags and return the result.
891 function getExplicitTagsOnly ($chain, $tree = NULL)
892 {
893 $self = __FUNCTION__;
894 global $tagtree;
895 if ($tree === NULL)
896 $tree = $tagtree;
897 $ret = array();
898 foreach ($tree as $taginfo)
899 {
900 if (isset ($taginfo['kids']))
901 {
902 $harvest = $self ($chain, $taginfo['kids']);
903 if (count ($harvest) > 0)
904 {
905 $ret = array_merge ($ret, $harvest);
906 continue;
907 }
908 }
909 // This tag isn't implicit, test is for being explicit.
910 foreach ($chain as $testtag)
911 if ($taginfo['id'] == $testtag['id'])
912 {
913 $ret[] = $testtag;
914 break;
915 }
916 }
917 return $ret;
918 }
919
920 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
921 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
922 // a list of tag structures. Same structure (tag ID list) is returned after processing.
923 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
924 {
925 $self = __FUNCTION__;
926 global $tagtree;
927 if ($tree === NULL)
928 $tree = $tagtree;
929 $getallkids = $getall;
930 $ret = array();
931 foreach ($tree as $taginfo)
932 {
933 foreach ($idlist as $test_id)
934 if ($getall or $taginfo['id'] == $test_id)
935 {
936 $ret[] = $taginfo['id'];
937 // Once matched node makes all sub-nodes match, but don't make
938 // a mistake of matching every other node at the current level.
939 $getallkids = TRUE;
940 break;
941 }
942 if (isset ($taginfo['kids']))
943 $ret = array_merge ($ret, $self ($idlist, $taginfo['kids'], $getallkids));
944 $getallkids = FALSE;
945 }
946 return $ret;
947 }
948
949 // Universal autotags generator, a complementing function for loadEntityTags().
950 // Bypass key isn't strictly typed, but interpreted depending on the realm.
951 function generateEntityAutoTags ($cell)
952 {
953 $ret = array();
954 switch ($cell['realm'])
955 {
956 case 'rack':
957 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
958 $ret[] = array ('tag' => '$any_rack');
959 break;
960 case 'object': // during transition bypass is already the whole structure
961 $ret[] = array ('tag' => '$id_' . $cell['id']);
962 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
963 $ret[] = array ('tag' => '$any_object');
964 if (validTagName ('$cn_' . $cell['name']))
965 $ret[] = array ('tag' => '$cn_' . $cell['name']);
966 if (!strlen ($cell['rack_id']))
967 $ret[] = array ('tag' => '$unmounted');
968 break;
969 case 'ipv4net': // during transition bypass is already the whole structure
970 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
971 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
972 $ret[] = array ('tag' => '$any_ip4net');
973 $ret[] = array ('tag' => '$any_net');
974 break;
975 case 'ipv4vs':
976 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
977 $ret[] = array ('tag' => '$any_ipv4vs');
978 $ret[] = array ('tag' => '$any_vs');
979 break;
980 case 'ipv4rspool':
981 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
982 $ret[] = array ('tag' => '$any_ipv4rsp');
983 $ret[] = array ('tag' => '$any_rsp');
984 break;
985 case 'user':
986 // {$username_XXX} autotag is generated always, but {$userid_XXX}
987 // appears only for accounts, which exist in local database.
988 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
989 if (isset ($cell['user_id']))
990 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
991 break;
992 case 'file':
993 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
994 $ret[] = array ('tag' => '$any_file');
995 break;
996 default: // HCF!
997 break;
998 }
999 if (!count ($cell['etags']))
1000 $ret[] = array ('tag' => '$untagged');
1001 return $ret;
1002 }
1003
1004 // Check, if the given tag is present on the chain (will only work
1005 // for regular tags with tag ID set.
1006 function tagOnChain ($taginfo, $tagchain)
1007 {
1008 if (!isset ($taginfo['id']))
1009 return FALSE;
1010 foreach ($tagchain as $test)
1011 if ($test['id'] == $taginfo['id'])
1012 return TRUE;
1013 return FALSE;
1014 }
1015
1016 function tagNameOnChain ($tagname, $tagchain)
1017 {
1018 foreach ($tagchain as $test)
1019 if ($test['tag'] == $tagname)
1020 return TRUE;
1021 return FALSE;
1022 }
1023
1024 // Idem, but use ID list instead of chain.
1025 function tagOnIdList ($taginfo, $tagidlist)
1026 {
1027 if (!isset ($taginfo['id']))
1028 return FALSE;
1029 foreach ($tagidlist as $tagid)
1030 if ($taginfo['id'] == $tagid)
1031 return TRUE;
1032 return FALSE;
1033 }
1034
1035 // Return TRUE, if two tags chains differ (order of tags doesn't matter).
1036 // Assume, that neither of the lists contains duplicates.
1037 // FIXME: a faster, than O(x^2) method is possible for this calculation.
1038 function tagChainCmp ($chain1, $chain2)
1039 {
1040 if (count ($chain1) != count ($chain2))
1041 return TRUE;
1042 foreach ($chain1 as $taginfo1)
1043 if (!tagOnChain ($taginfo1, $chain2))
1044 return TRUE;
1045 return FALSE;
1046 }
1047
1048 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1049 // hold all appropriate (explicit and implicit) tags respectively.
1050 // Otherwise some limited redirection is necessary (only page and tab
1051 // names are preserved, ophandler name change isn't handled).
1052 function fixContext ()
1053 {
1054 global
1055 $pageno,
1056 $tabno,
1057 $auto_tags,
1058 $expl_tags,
1059 $impl_tags,
1060 $target_given_tags,
1061 $user_given_tags,
1062 $etype_by_pageno,
1063 $page;
1064
1065 $pmap = array
1066 (
1067 'accounts' => 'userlist',
1068 'rspools' => 'ipv4rsplist',
1069 'rspool' => 'ipv4rsp',
1070 'vservices' => 'ipv4vslist',
1071 'vservice' => 'ipv4vs',
1072 'objects' => 'depot',
1073 'objgroup' => 'depot',
1074 );
1075 $tmap = array();
1076 $tmap['objects']['newmulti'] = 'addmore';
1077 $tmap['objects']['newobj'] = 'addmore';
1078 $tmap['object']['switchvlans'] = 'livevlans';
1079 $tmap['object']['slb'] = 'editrspvs';
1080 $tmap['object']['portfwrd'] = 'nat4';
1081 $tmap['object']['network'] = 'ipv4';
1082 if (isset ($pmap[$pageno]))
1083 redirectUser ($pmap[$pageno], $tabno);
1084 if (isset ($tmap[$pageno][$tabno]))
1085 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1086
1087 if (isset ($etype_by_pageno[$pageno]))
1088 {
1089 // Each page listed in the map above requires one uint argument.
1090 assertUIntArg ($page[$pageno]['bypass'], __FUNCTION__);
1091 $target_realm = $etype_by_pageno[$pageno];
1092 $target_id = $_REQUEST[$page[$pageno]['bypass']];
1093 $target = spotEntity ($target_realm, $target_id);
1094 $target_given_tags = $target['etags'];
1095 // Don't reset autochain, because auth procedures could push stuff there in.
1096 // Another important point is to ignore 'user' realm, so we don't infuse effective
1097 // context with autotags of the displayed account.
1098 if ($pageno != 'user')
1099 $auto_tags = array_merge ($auto_tags, $target['atags']);
1100 }
1101 // Explicit and implicit chains should be normally empty at this point, so
1102 // overwrite the contents anyway.
1103 $expl_tags = mergeTagChains ($user_given_tags, $target_given_tags);
1104 $impl_tags = getImplicitTags ($expl_tags);
1105 }
1106
1107 // Take a list of user-supplied tag IDs to build a list of valid taginfo
1108 // records indexed by tag IDs (tag chain).
1109 function buildTagChainFromIds ($tagidlist)
1110 {
1111 global $taglist;
1112 $ret = array();
1113 foreach (array_unique ($tagidlist) as $tag_id)
1114 if (isset ($taglist[$tag_id]))
1115 $ret[] = $taglist[$tag_id];
1116 return $ret;
1117 }
1118
1119 // Process a given tag tree and return only meaningful branches. The resulting
1120 // (sub)tree will have refcnt leaves on every last branch.
1121 function getObjectiveTagTree ($tree, $realm, $preselect)
1122 {
1123 $self = __FUNCTION__;
1124 $ret = array();
1125 foreach ($tree as $taginfo)
1126 {
1127 $subsearch = $self ($taginfo['kids'], $realm, $preselect);
1128 // If the current node addresses something, add it to the result
1129 // regardless of how many sub-nodes it features.
1130 if
1131 (
1132 isset ($taginfo['refcnt'][$realm]) or
1133 count ($subsearch) > 1 or
1134 tagOnIdList ($taginfo, $preselect)
1135 )
1136 $ret[] = array
1137 (
1138 'id' => $taginfo['id'],
1139 'tag' => $taginfo['tag'],
1140 'parent_id' => $taginfo['parent_id'],
1141 'refcnt' => $taginfo['refcnt'],
1142 'kids' => $subsearch
1143 );
1144 else
1145 $ret = array_merge ($ret, $subsearch);
1146 }
1147 return $ret;
1148 }
1149
1150 // Get taginfo record by tag name, return NULL, if record doesn't exist.
1151 function getTagByName ($target_name)
1152 {
1153 global $taglist;
1154 foreach ($taglist as $taginfo)
1155 if ($taginfo['tag'] == $target_name)
1156 return $taginfo;
1157 return NULL;
1158 }
1159
1160 // Merge two chains, filtering dupes out. Return the resulting superset.
1161 function mergeTagChains ($chainA, $chainB)
1162 {
1163 // $ret = $chainA;
1164 // Reindex by tag id in any case.
1165 $ret = array();
1166 foreach ($chainA as $tag)
1167 $ret[$tag['id']] = $tag;
1168 foreach ($chainB as $tag)
1169 if (!isset ($ret[$tag['id']]))
1170 $ret[$tag['id']] = $tag;
1171 return $ret;
1172 }
1173
1174 function getCellFilter ()
1175 {
1176 global $sic;
1177 if (isset ($_REQUEST['tagfilter']) and is_array ($_REQUEST['tagfilter']))
1178 {
1179 $_REQUEST['cft'] = $_REQUEST['tagfilter'];
1180 unset ($_REQUEST['tagfilter']);
1181 }
1182 $ret = array
1183 (
1184 'tagidlist' => array(),
1185 'tnamelist' => array(),
1186 'pnamelist' => array(),
1187 'andor' => '',
1188 'text' => '',
1189 'extratext' => '',
1190 'expression' => array(),
1191 'urlextra' => '', // Just put text here and let makeHref call urlencode().
1192 );
1193 switch (TRUE)
1194 {
1195 case (!isset ($_REQUEST['andor'])):
1196 $andor2 = getConfigVar ('FILTER_DEFAULT_ANDOR');
1197 break;
1198 case ($_REQUEST['andor'] == 'and'):
1199 case ($_REQUEST['andor'] == 'or'):
1200 $ret['andor'] = $andor2 = $_REQUEST['andor'];
1201 $ret['urlextra'] .= '&andor=' . $ret['andor'];
1202 break;
1203 default:
1204 showError ('Invalid and/or switch value in submitted form', __FUNCTION__);
1205 return NULL;
1206 }
1207 $andor1 = '';
1208 // Both tags and predicates, which don't exist, should be
1209 // handled somehow. Discard them silently for now.
1210 if (isset ($_REQUEST['cft']) and is_array ($_REQUEST['cft']))
1211 {
1212 global $taglist;
1213 foreach ($_REQUEST['cft'] as $req_id)
1214 if (isset ($taglist[$req_id]))
1215 {
1216 $ret['tagidlist'][] = $req_id;
1217 $ret['tnamelist'][] = $taglist[$req_id]['tag'];
1218 $ret['text'] .= $andor1 . '{' . $taglist[$req_id]['tag'] . '}';
1219 $andor1 = ' ' . $andor2 . ' ';
1220 $ret['urlextra'] .= '&cft[]=' . $req_id;
1221 }
1222 }
1223 if (isset ($_REQUEST['cfp']) and is_array ($_REQUEST['cfp']))
1224 {
1225 global $pTable;
1226 foreach ($_REQUEST['cfp'] as $req_name)
1227 if (isset ($pTable[$req_name]))
1228 {
1229 $ret['pnamelist'][] = $req_name;
1230 $ret['text'] .= $andor1 . '[' . $req_name . ']';
1231 $andor1 = ' ' . $andor2 . ' ';
1232 $ret['urlextra'] .= '&cfp[]=' . $req_name;
1233 }
1234 }
1235 // Extra text comes from TEXTAREA and is easily screwed by standard escaping function.
1236 if (isset ($sic['cfe']))
1237 {
1238 // Only consider extra text, when it is a correct RackCode expression.
1239 $parse = spotPayload ($sic['cfe'], 'SYNT_EXPR');
1240 if ($parse['result'] == 'ACK')
1241 {
1242 $ret['extratext'] = trim ($sic['cfe']);
1243 $ret['urlextra'] .= '&cfe=' . $ret['extratext'];
1244 }
1245 }
1246 $finaltext = array();
1247 if (strlen ($ret['text']))
1248 $finaltext[] = '(' . $ret['text'] . ')';
1249 if (strlen ($ret['extratext']))
1250 $finaltext[] = '(' . $ret['extratext'] . ')';
1251 $finaltext = implode (' ' . $andor2 . ' ', $finaltext);
1252 if (strlen ($finaltext))
1253 {
1254 $parse = spotPayload ($finaltext, 'SYNT_EXPR');
1255 $ret['expression'] = $parse['result'] == 'ACK' ? $parse['load'] : NULL;
1256 // It's not quite fair enough to put the blame of the whole text onto
1257 // non-empty "extra" portion of it, but it's the only user-generated portion
1258 // of it, thus the most probable cause of parse error.
1259 if (strlen ($ret['extratext']))
1260 $ret['extraclass'] = $parse['result'] == 'ACK' ? 'validation-success' : 'validation-error';
1261 }
1262 return $ret;
1263 }
1264
1265 // Return an empty message log.
1266 function emptyLog ()
1267 {
1268 return array
1269 (
1270 'v' => 2,
1271 'm' => array()
1272 );
1273 }
1274
1275 // Return a message log consisting of only one message.
1276 function oneLiner ($code, $args = array())
1277 {
1278 $ret = emptyLog();
1279 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1280 return $ret;
1281 }
1282
1283 // Merge message payload from two message logs given and return the result.
1284 function mergeLogs ($log1, $log2)
1285 {
1286 $ret = emptyLog();
1287 $ret['m'] = array_merge ($log1['m'], $log2['m']);
1288 return $ret;
1289 }
1290
1291 function validTagName ($s, $allow_autotag = FALSE)
1292 {
1293 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1294 return TRUE;
1295 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1296 return TRUE;
1297 return FALSE;
1298 }
1299
1300 function redirectUser ($p, $t)
1301 {
1302 global $page, $root;
1303 $l = "{$root}?page=${p}&tab=${t}";
1304 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1305 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1306 header ("Location: " . $l);
1307 die;
1308 }
1309
1310 function getRackCodeStats ()
1311 {
1312 global $rackCode;
1313 $defc = $grantc = $modc = 0;
1314 foreach ($rackCode as $s)
1315 switch ($s['type'])
1316 {
1317 case 'SYNT_DEFINITION':
1318 $defc++;
1319 break;
1320 case 'SYNT_GRANT':
1321 $grantc++;
1322 break;
1323 case 'SYNT_CTXMOD':
1324 $modc++;
1325 break;
1326 default:
1327 break;
1328 }
1329 $ret = array
1330 (
1331 'Definition sentences' => $defc,
1332 'Grant sentences' => $grantc,
1333 'Context mod sentences' => $modc
1334 );
1335 return $ret;
1336 }
1337
1338 function getRackImageWidth ()
1339 {
1340 global $rtwidth;
1341 return 3 + $rtwidth[0] + $rtwidth[1] + $rtwidth[2] + 3;
1342 }
1343
1344 function getRackImageHeight ($units)
1345 {
1346 return 3 + 3 + $units * 2;
1347 }
1348
1349 // Perform substitutions and return resulting string
1350 // used solely by buildLVSConfig()
1351 function apply_macros ($macros, $subject)
1352 {
1353 $ret = $subject;
1354 foreach ($macros as $search => $replace)
1355 $ret = str_replace ($search, $replace, $ret);
1356 return $ret;
1357 }
1358
1359 function buildLVSConfig ($object_id = 0)
1360 {
1361 if ($object_id <= 0)
1362 {
1363 showError ('Invalid argument', __FUNCTION__);
1364 return;
1365 }
1366 $oInfo = spotEntity ('object', $object_id);
1367 $lbconfig = getSLBConfig ($object_id);
1368 if ($lbconfig === NULL)
1369 {
1370 showError ('getSLBConfig() failed', __FUNCTION__);
1371 return;
1372 }
1373 $newconfig = "#\n#\n# This configuration has been generated automatically by RackTables\n";
1374 $newconfig .= "# for object_id == ${object_id}\n# object name: ${oInfo['name']}\n#\n#\n\n\n";
1375 foreach ($lbconfig as $vs_id => $vsinfo)
1376 {
1377 $newconfig .= "########################################################\n" .
1378 "# VS (id == ${vs_id}): " . (!strlen ($vsinfo['vs_name']) ? 'NO NAME' : $vsinfo['vs_name']) . "\n" .
1379 "# RS pool (id == ${vsinfo['pool_id']}): " . (!strlen ($vsinfo['pool_name']) ? 'ANONYMOUS' : $vsinfo['pool_name']) . "\n" .
1380 "########################################################\n";
1381 # The order of inheritance is: VS -> LB -> pool [ -> RS ]
1382 $macros = array
1383 (
1384 '%VIP%' => $vsinfo['vip'],
1385 '%VPORT%' => $vsinfo['vport'],
1386 '%PROTO%' => $vsinfo['proto'],
1387 '%VNAME%' => $vsinfo['vs_name'],
1388 '%RSPOOLNAME%' => $vsinfo['pool_name']
1389 );
1390 $newconfig .= "virtual_server ${vsinfo['vip']} ${vsinfo['vport']} {\n";
1391 $newconfig .= "\tprotocol ${vsinfo['proto']}\n";
1392 $newconfig .= apply_macros
1393 (
1394 $macros,
1395 lf_wrap ($vsinfo['vs_vsconfig']) .
1396 lf_wrap ($vsinfo['lb_vsconfig']) .
1397 lf_wrap ($vsinfo['pool_vsconfig'])
1398 );
1399 foreach ($vsinfo['rslist'] as $rs)
1400 {
1401 if (!strlen ($rs['rsport']))
1402 $rs['rsport'] = $vsinfo['vport'];
1403 $macros['%RSIP%'] = $rs['rsip'];
1404 $macros['%RSPORT%'] = $rs['rsport'];
1405 $newconfig .= "\treal_server ${rs['rsip']} ${rs['rsport']} {\n";
1406 $newconfig .= apply_macros
1407 (
1408 $macros,
1409 lf_wrap ($vsinfo['vs_rsconfig']) .
1410 lf_wrap ($vsinfo['lb_rsconfig']) .
1411 lf_wrap ($vsinfo['pool_rsconfig']) .
1412 lf_wrap ($rs['rs_rsconfig'])
1413 );
1414 $newconfig .= "\t}\n";
1415 }
1416 $newconfig .= "}\n\n\n";
1417 }
1418 // FIXME: deal somehow with Mac-styled text, the below replacement will screw it up
1419 return str_replace ("\r", '', $newconfig);
1420 }
1421
1422 // Indicate occupation state of each IP address: none, ordinary or problematic.
1423 function markupIPv4AddrList (&$addrlist)
1424 {
1425 foreach (array_keys ($addrlist) as $ip_bin)
1426 {
1427 $refc = array
1428 (
1429 'shared' => 0, // virtual
1430 'virtual' => 0, // loopback
1431 'regular' => 0, // connected host
1432 'router' => 0 // connected gateway
1433 );
1434 foreach ($addrlist[$ip_bin]['allocs'] as $a)
1435 $refc[$a['type']]++;
1436 $nvirtloopback = ($refc['shared'] + $refc['virtual'] > 0) ? 1 : 0; // modulus of virtual + shared
1437 $nreserved = ($addrlist[$ip_bin]['reserved'] == 'yes') ? 1 : 0; // only one reservation is possible ever
1438 $nrealms = $nreserved + $nvirtloopback + $refc['regular'] + $refc['router']; // latter two are connected and router allocations
1439
1440 if ($nrealms == 1)
1441 $addrlist[$ip_bin]['class'] = 'trbusy';
1442 elseif ($nrealms > 1)
1443 $addrlist[$ip_bin]['class'] = 'trerror';
1444 else
1445 $addrlist[$ip_bin]['class'] = '';
1446 }
1447 }
1448
1449 // Scan the given address list (returned by scanIPv4Space) and return a list of all routers found.
1450 function findRouters ($addrlist)
1451 {
1452 $ret = array();
1453 foreach ($addrlist as $addr)
1454 foreach ($addr['allocs'] as $alloc)
1455 if ($alloc['type'] == 'router')
1456 $ret[] = array
1457 (
1458 'id' => $alloc['object_id'],
1459 'iface' => $alloc['name'],
1460 'dname' => $alloc['object_name'],
1461 'addr' => $addr['ip']
1462 );
1463 return $ret;
1464 }
1465
1466 // Assist in tag chain sorting.
1467 function taginfoCmp ($tagA, $tagB)
1468 {
1469 return $tagA['ci'] - $tagB['ci'];
1470 }
1471
1472 // Compare networks. When sorting a tree, the records on the list will have
1473 // distinct base IP addresses.
1474 // "The comparison function must return an integer less than, equal to, or greater
1475 // than zero if the first argument is considered to be respectively less than,
1476 // equal to, or greater than the second." (c) PHP manual
1477 function IPv4NetworkCmp ($netA, $netB)
1478 {
1479 // There's a problem just substracting one u32 integer from another,
1480 // because the result may happen big enough to become a negative i32
1481 // integer itself (PHP tries to cast everything it sees to signed int)
1482 // The comparison below must treat positive and negative values of both
1483 // arguments.
1484 // Equal values give instant decision regardless of their [equal] sign.
1485 if ($netA['ip_bin'] == $netB['ip_bin'])
1486 return 0;
1487 // Same-signed values compete arithmetically within one of i32 contiguous ranges:
1488 // 0x00000001~0x7fffffff 1~2147483647
1489 // 0 doesn't have any sign, and network 0.0.0.0 isn't allowed
1490 // 0x80000000~0xffffffff -2147483648~-1
1491 $signA = $netA['ip_bin'] / abs ($netA['ip_bin']);
1492 $signB = $netB['ip_bin'] / abs ($netB['ip_bin']);
1493 if ($signA == $signB)
1494 {
1495 if ($netA['ip_bin'] > $netB['ip_bin'])
1496 return 1;
1497 else
1498 return -1;
1499 }
1500 else // With only one of two values being negative, it... wins!
1501 {
1502 if ($netA['ip_bin'] < $netB['ip_bin'])
1503 return 1;
1504 else
1505 return -1;
1506 }
1507 }
1508
1509 // Modify the given tag tree so, that each level's items are sorted alphabetically.
1510 function sortTree (&$tree, $sortfunc = '')
1511 {
1512 if (!strlen ($sortfunc))
1513 return;
1514 $self = __FUNCTION__;
1515 usort ($tree, $sortfunc);
1516 // Don't make a mistake of directly iterating over the items of current level, because this way
1517 // the sorting will be performed on a _copy_ if each item, not the item itself.
1518 foreach (array_keys ($tree) as $tagid)
1519 $self ($tree[$tagid]['kids'], $sortfunc);
1520 }
1521
1522 function iptree_fill (&$netdata)
1523 {
1524 if (!isset ($netdata['kids']) or !count ($netdata['kids']))
1525 return;
1526 // If we really have nested prefixes, they must fit into the tree.
1527 $worktree = array
1528 (
1529 'ip_bin' => $netdata['ip_bin'],
1530 'mask' => $netdata['mask']
1531 );
1532 foreach ($netdata['kids'] as $pfx)
1533 iptree_embed ($worktree, $pfx);
1534 $netdata['kids'] = iptree_construct ($worktree);
1535 $netdata['kidc'] = count ($netdata['kids']);
1536 }
1537
1538 function iptree_construct ($node)
1539 {
1540 $self = __FUNCTION__;
1541
1542 if (!isset ($node['right']))
1543 {
1544 if (!isset ($node['ip']))
1545 {
1546 $node['ip'] = long2ip ($node['ip_bin']);
1547 $node['kids'] = array();
1548 $node['kidc'] = 0;
1549 $node['name'] = '';
1550 }
1551 return array ($node);
1552 }
1553 else
1554 return array_merge ($self ($node['left']), $self ($node['right']));
1555 }
1556
1557 function iptree_embed (&$node, $pfx)
1558 {
1559 $self = __FUNCTION__;
1560
1561 // hit?
1562 if ($node['ip_bin'] == $pfx['ip_bin'] and $node['mask'] == $pfx['mask'])
1563 {
1564 $node = $pfx;
1565 return;
1566 }
1567 if ($node['mask'] == $pfx['mask'])
1568 {
1569 showError ('Internal error, the recurring loop lost control', __FUNCTION__);
1570 die;
1571 }
1572
1573 // split?
1574 if (!isset ($node['right']))
1575 {
1576 // Fill in db_first/db_last to make it possible to run scanIPv4Space() on the node.
1577 $node['left']['mask'] = $node['mask'] + 1;
1578 $node['left']['ip_bin'] = $node['ip_bin'];
1579 $node['left']['db_first'] = sprintf ('%u', $node['left']['ip_bin']);
1580 $node['left']['db_last'] = sprintf ('%u', $node['left']['ip_bin'] | binInvMaskFromDec ($node['left']['mask']));
1581
1582 $node['right']['mask'] = $node['mask'] + 1;
1583 $node['right']['ip_bin'] = $node['ip_bin'] + binInvMaskFromDec ($node['mask'] + 1) + 1;
1584 $node['right']['db_first'] = sprintf ('%u', $node['right']['ip_bin']);
1585 $node['right']['db_last'] = sprintf ('%u', $node['right']['ip_bin'] | binInvMaskFromDec ($node['right']['mask']));
1586 }
1587
1588 // repeat!
1589 if (($node['left']['ip_bin'] & binMaskFromDec ($node['left']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1590 $self ($node['left'], $pfx);
1591 elseif (($node['right']['ip_bin'] & binMaskFromDec ($node['right']['mask'])) == ($pfx['ip_bin'] & binMaskFromDec ($node['left']['mask'])))
1592 $self ($node['right'], $pfx);
1593 else
1594 {
1595 showError ('Internal error, cannot decide between left and right', __FUNCTION__);
1596 die;
1597 }
1598 }
1599
1600 function treeApplyFunc (&$tree, $func = '', $stopfunc = '')
1601 {
1602 if (!strlen ($func))
1603 return;
1604 $self = __FUNCTION__;
1605 foreach (array_keys ($tree) as $key)
1606 {
1607 $func ($tree[$key]);
1608 if (strlen ($stopfunc) and $stopfunc ($tree[$key]))
1609 continue;
1610 $self ($tree[$key]['kids'], $func);
1611 }
1612 }
1613
1614 function loadIPv4AddrList (&$netinfo)
1615 {
1616 loadOwnIPv4Addresses ($netinfo);
1617 markupIPv4AddrList ($netinfo['addrlist']);
1618 }
1619
1620 function countOwnIPv4Addresses (&$node)
1621 {
1622 $toscan = array();
1623 $node['addrt'] = 0;
1624 $node['mask_bin'] = binMaskFromDec ($node['mask']);
1625 $node['mask_bin_inv'] = binInvMaskFromDec ($node['mask']);
1626 $node['db_first'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] & $node['mask_bin']);
1627 $node['db_last'] = sprintf ('%u', 0x00000000 + $node['ip_bin'] | ($node['mask_bin_inv']));
1628 if (!count ($node['kids']))
1629 {
1630 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1631 $node['addrt'] = binInvMaskFromDec ($node['mask']) + 1;
1632 }
1633 else
1634 foreach ($node['kids'] as $nested)
1635 if (!isset ($nested['id'])) // spare
1636 {
1637 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1638 $node['addrt'] += binInvMaskFromDec ($nested['mask']) + 1;
1639 }
1640 // Don't do anything more, because the displaying function will load the addresses anyway.
1641 return;
1642 $node['addrc'] = count (scanIPv4Space ($toscan));
1643 }
1644
1645 function nodeIsCollapsed ($node)
1646 {
1647 return $node['symbol'] == 'node-collapsed';
1648 }
1649
1650 function loadOwnIPv4Addresses (&$node)
1651 {
1652 $toscan = array();
1653 if (!isset ($node['kids']) or !count ($node['kids']))
1654 $toscan[] = array ('i32_first' => $node['db_first'], 'i32_last' => $node['db_last']);
1655 else
1656 foreach ($node['kids'] as $nested)
1657 if (!isset ($nested['id'])) // spare
1658 $toscan[] = array ('i32_first' => $nested['db_first'], 'i32_last' => $nested['db_last']);
1659 $node['addrlist'] = scanIPv4Space ($toscan);
1660 $node['addrc'] = count ($node['addrlist']);
1661 }
1662
1663 function prepareIPv4Tree ($netlist, $expanded_id = 0)
1664 {
1665 // treeFromList() requires parent_id to be correct for an item to get onto the tree,
1666 // so perform necessary pre-processing to make orphans belong to root. This trick
1667 // was earlier performed by getIPv4NetworkList().
1668 $netids = array_keys ($netlist);
1669 foreach ($netids as $cid)
1670 if (!in_array ($netlist[$cid]['parent_id'], $netids))
1671 $netlist[$cid]['parent_id'] = NULL;
1672 $tree = treeFromList ($netlist); // medium call
1673 sortTree ($tree, 'IPv4NetworkCmp');
1674 // complement the tree before markup to make the spare networks have "symbol" set
1675 treeApplyFunc ($tree, 'iptree_fill');
1676 iptree_markup_collapsion ($tree, getConfigVar ('TREE_THRESHOLD'), $expanded_id);
1677 // count addresses after the markup to skip computation for hidden tree nodes
1678 treeApplyFunc ($tree, 'countOwnIPv4Addresses', 'nodeIsCollapsed');
1679 return $tree;
1680 }
1681
1682 // Check all items of the tree recursively, until the requested target id is
1683 // found. Mark all items leading to this item as "expanded", collapsing all
1684 // the rest, which exceed the given threshold (if the threshold is given).
1685 function iptree_markup_collapsion (&$tree, $threshold = 1024, $target = 0)
1686 {
1687 $self = __FUNCTION__;
1688 $ret = FALSE;
1689 foreach (array_keys ($tree) as $key)
1690 {
1691 $here = ($target === 'ALL' or ($target > 0 and isset ($tree[$key]['id']) and $tree[$key]['id'] == $target));
1692 $below = $self ($tree[$key]['kids'], $threshold, $target);
1693 if (!$tree[$key]['kidc']) // terminal node
1694 $tree[$key]['symbol'] = 'spacer';
1695 elseif ($tree[$key]['kidc'] < $threshold)
1696 $tree[$key]['symbol'] = 'node-expanded-static';
1697 elseif ($here or $below)
1698 $tree[$key]['symbol'] = 'node-expanded';
1699 else
1700 $tree[$key]['symbol'] = 'node-collapsed';
1701 $ret = ($ret or $here or $below); // parentheses are necessary for this to be computed correctly
1702 }
1703 return $ret;
1704 }
1705
1706 // Convert entity name to human-readable value
1707 function formatEntityName ($name) {
1708 switch ($name)
1709 {
1710 case 'ipv4net':
1711 return 'IPv4 Network';
1712 case 'ipv4rspool':
1713 return 'IPv4 RS Pool';
1714 case 'ipv4vs':
1715 return 'IPv4 Virtual Service';
1716 case 'object':
1717 return 'Object';
1718 case 'rack':
1719 return 'Rack';
1720 case 'user':
1721 return 'User';
1722 }
1723 return 'invalid';
1724 }
1725
1726 // Take a MySQL or other generic timestamp and make it prettier
1727 function formatTimestamp ($timestamp) {
1728 return date('n/j/y g:iA', strtotime($timestamp));
1729 }
1730
1731 // Display hrefs for all of a file's parents. If scissors are requested,
1732 // prepend cutting button to each of them.
1733 function serializeFileLinks ($links, $scissors = FALSE)
1734 {
1735 global $root;
1736
1737 $comma = '';
1738 $ret = '';
1739 foreach ($links as $link_id => $li)
1740 {
1741 switch ($li['entity_type'])
1742 {
1743 case 'ipv4net':
1744 $params = "page=ipv4net&id=";
1745 break;
1746 case 'ipv4rspool':
1747 $params = "page=ipv4rspool&pool_id=";
1748 break;
1749 case 'ipv4vs':
1750 $params = "page=ipv4vs&vs_id=";
1751 break;
1752 case 'object':
1753 $params = "page=object&object_id=";
1754 break;
1755 case 'rack':
1756 $params = "page=rack&rack_id=";
1757 break;
1758 case 'user':
1759 $params = "page=user&user_id=";
1760 break;
1761 }
1762 $ret .= $comma;
1763 if ($scissors)
1764 {
1765 $ret .= "<a href='" . makeHrefProcess(array('op'=>'unlinkFile', 'link_id'=>$link_id)) . "'";
1766 $ret .= getImageHREF ('cut') . '</a> ';
1767 }
1768 $ret .= sprintf("<a href='%s?%s%s'>%s</a>", $root, $params, $li['entity_id'], $li['name']);
1769 $comma = '<br>';
1770 }
1771 return $ret;
1772 }
1773
1774 // Convert filesize to appropriate unit and make it human-readable
1775 function formatFileSize ($bytes) {
1776 // bytes
1777 if($bytes < 1024) // bytes
1778 return "${bytes} bytes";
1779
1780 // kilobytes
1781 if ($bytes < 1024000)
1782 return sprintf ("%.1fk", round (($bytes / 1024), 1));
1783
1784 // megabytes
1785 return sprintf ("%.1f MB", round (($bytes / 1024000), 1));
1786 }
1787
1788 // Reverse of formatFileSize, it converts human-readable value to bytes
1789 function convertToBytes ($value) {
1790 $value = trim($value);
1791 $last = strtolower($value[strlen($value)-1]);
1792 switch ($last)
1793 {
1794 case 'g':
1795 $value *= 1024;
1796 case 'm':
1797 $value *= 1024;
1798 case 'k':
1799 $value *= 1024;
1800 }
1801
1802 return $value;
1803 }
1804
1805 function ip_quad2long ($ip)
1806 {
1807 return sprintf("%u", ip2long($ip));
1808 }
1809
1810 function ip_long2quad ($quad)
1811 {
1812 return long2ip($quad);
1813 }
1814
1815 function makeHref($params = array())
1816 {
1817 global $head_revision, $numeric_revision, $root;
1818 $ret = $root.'?';
1819 $first = true;
1820 if (!isset($params['r']) and ($numeric_revision != $head_revision))
1821 {
1822 $params['r'] = $numeric_revision;
1823 }
1824 foreach($params as $key=>$value)
1825 {
1826 if (!$first)
1827 $ret.='&';
1828 $ret .= urlencode($key).'='.urlencode($value);
1829 $first = false;
1830 }
1831 return $ret;
1832 }
1833
1834 function makeHrefProcess($params = array())
1835 {
1836 global $head_revision, $numeric_revision, $root, $pageno, $tabno;
1837 $ret = $root.'process.php'.'?';
1838 $first = true;
1839 if ($numeric_revision != $head_revision)
1840 {
1841 error_log("Can't make a process link when not in head revision");
1842 die();
1843 }
1844 if (!isset($params['page']))
1845 $params['page'] = $pageno;
1846 if (!isset($params['tab']))
1847 $params['tab'] = $tabno;
1848 foreach($params as $key=>$value)
1849 {
1850 if (!$first)
1851 $ret.='&';
1852 $ret .= urlencode($key).'='.urlencode($value);
1853 $first = false;
1854 }
1855 return $ret;
1856 }
1857
1858 function makeHrefForHelper ($helper_name, $params = array())
1859 {
1860 global $head_revision, $numeric_revision, $root;
1861 $ret = $root.'popup.php'.'?helper='.$helper_name;
1862 if ($numeric_revision != $head_revision)
1863 {
1864 error_log("Can't make a process link when not in head revision");
1865 die();
1866 }
1867 foreach($params as $key=>$value)
1868 $ret .= '&'.urlencode($key).'='.urlencode($value);
1869 return $ret;
1870 }
1871
1872 // Process the given list of records to build data suitable for printNiftySelect()
1873 // (like it was formerly executed by printSelect()). Screen out vendors according
1874 // to VENDOR_SIEVE, if object type ID is provided. However, the OPTGROUP with already
1875 // selected OPTION is protected from being screened.
1876 function cookOptgroups ($recordList, $object_type_id = 0, $existing_value = 0)
1877 {
1878 $ret = array();
1879 // Always keep "other" OPTGROUP at the SELECT bottom.
1880 $therest = array();
1881 foreach ($recordList as $dict_key => $dict_value)
1882 if (strpos ($dict_value, '%GSKIP%') !== FALSE)
1883 {
1884 $tmp = explode ('%GSKIP%', $dict_value, 2);
1885 $ret[$tmp[0]][$dict_key] = $tmp[1];
1886 }
1887 elseif (strpos ($dict_value, '%GPASS%') !== FALSE)
1888 {
1889 $tmp = explode ('%GPASS%', $dict_value, 2);
1890 $ret[$tmp[0]][$dict_key] = $tmp[1];
1891 }
1892 else
1893 $therest[$dict_key] = $dict_value;
1894 if ($object_type_id != 0)
1895 {
1896 $screenlist = array();
1897 foreach (explode (';', getConfigVar ('VENDOR_SIEVE')) as $sieve)
1898 if (FALSE !== mb_ereg ("^([^@]+)(@${object_type_id})?\$", trim ($sieve), $regs))
1899 $screenlist[] = $regs[1];
1900 foreach (array_keys ($ret) as $vendor)
1901 if (in_array ($vendor, $screenlist))
1902 {
1903 $ok_to_screen = TRUE;
1904 if ($existing_value)
1905 foreach (array_keys ($ret[$vendor]) as $recordkey)
1906 if ($recordkey == $existing_value)
1907 {
1908 $ok_to_screen = FALSE;
1909 break;
1910 }
1911 if ($ok_to_screen)
1912 unset ($ret[$vendor]);
1913 }
1914 }
1915 $ret['other'] = $therest;
1916 return $ret;
1917 }
1918
1919 function dos2unix ($text)
1920 {
1921 return str_replace ("\r\n", "\n", $text);
1922 }
1923
1924 function buildPredicateTable ($parsetree)
1925 {
1926 $ret = array();
1927 foreach ($parsetree as $sentence)
1928 if ($sentence['type'] == 'SYNT_DEFINITION')
1929 $ret[$sentence['term']] = $sentence['definition'];
1930 // Now we have predicate table filled in with the latest definitions of each
1931 // particular predicate met. This isn't as chik, as on-the-fly predicate
1932 // overloading during allow/deny scan, but quite sufficient for this task.
1933 return $ret;
1934 }
1935
1936 // Take a list of records and filter against given RackCode expression. Return
1937 // the original list intact, if there was no filter requested, but return an
1938 // empty list, if there was an error.
1939 function filterCellList ($list_in, $expression = array())
1940 {
1941 if ($expression === NULL)
1942 return array();
1943 if (!count ($expression))
1944 return $list_in;
1945 $list_out = array();
1946 foreach ($list_in as $item_key => $item_value)
1947 if (TRUE === judgeCell ($item_value, $expression))
1948 $list_out[$item_key] = $item_value;
1949 return $list_out;
1950 }
1951
1952 // Tell, if the given expression is true for the given entity. Take complete record on input.
1953 function judgeCell ($cell, $expression)
1954 {
1955 global $pTable;
1956 return eval_expression
1957 (
1958 $expression,
1959 array_merge
1960 (
1961 $cell['etags'],
1962 $cell['itags'],
1963 $cell['atags']
1964 ),
1965 $pTable,
1966 TRUE
1967 );
1968 }
1969
1970 // Tell, if a constraint from config option permits given record.
1971 function considerConfiguredConstraint ($cell, $varname)
1972 {
1973 if (!strlen (getConfigVar ($varname)))
1974 return TRUE; // no restriction
1975 global $parseCache;
1976 if (!isset ($parseCache[$varname]))
1977 // getConfigVar() doesn't re-read the value from DB because of its
1978 // own cache, so there is no race condition here between two calls.
1979 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
1980 if ($parseCache[$varname]['result'] != 'ACK')
1981 return FALSE; // constraint set, but cannot be used due to compilation error
1982 return judgeCell ($cell, $parseCache[$varname]['load']);
1983 }
1984
1985 // Return list of records in the given realm, which conform to
1986 // the given RackCode expression. If the realm is unknown or text
1987 // doesn't validate as a RackCode expression, return NULL.
1988 // Otherwise (successful scan) return a list of all matched
1989 // records, even if the list is empty (array() !== NULL). If the
1990 // text is an empty string, return all found records in the given
1991 // realm.
1992 function scanRealmByText ($realm = NULL, $ftext = '')
1993 {
1994 switch ($realm)
1995 {
1996 case 'object':
1997 case 'user':
1998 case 'ipv4net':
1999 case 'file':
2000 case 'ipv4vs':
2001 case 'ipv4rspool':
2002 if (!strlen ($ftext = trim ($ftext)))
2003 $fexpr = array();
2004 else
2005 {
2006 $fparse = spotPayload ($ftext, 'SYNT_EXPR');
2007 if ($fparse['result'] != 'ACK')
2008 return NULL;
2009 $fexpr = $fparse['load'];
2010 }
2011 return filterCellList (listCells ($realm), $fexpr);
2012 default:
2013 throw new InvalidArgException (__FUNCTION__);
2014 }
2015
2016 }
2017
2018 function getIPv4VSOptions ()
2019 {
2020 $ret = array();
2021 foreach (listCells ('ipv4vs') as $vsid => $vsinfo)
2022 $ret[$vsid] = $vsinfo['dname'] . (!strlen ($vsinfo['name']) ? '' : " (${vsinfo['name']})");
2023 return $ret;
2024 }
2025
2026 function getIPv4RSPoolOptions ()
2027 {
2028 $ret = array();
2029 foreach (listCells ('ipv4rspool') as $pool_id => $poolInfo)
2030 $ret[$pool_id] = $poolInfo['name'];
2031 return $ret;
2032 }
2033
2034 // Derive a complete cell structure from the given username regardless
2035 // if it is a local account or not.
2036 function constructUserCell ($username)
2037 {
2038 if (NULL !== ($userid = getUserIDByUsername ($username)))
2039 return spotEntity ('user', $userid);
2040 $ret = array
2041 (
2042 'realm' => 'user',
2043 'user_name' => $username,
2044 'user_realname' => '',
2045 'etags' => array(),
2046 'itags' => array(),
2047 );
2048 $ret['atags'] = generateEntityAutoTags ($ret);
2049 return $ret;
2050 }
2051
2052 ?>