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