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