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