r1941 + highlight the IP address on the object, which we have navigated from
[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
27// Objects of some types should be explicitly shown as
28// anonymous (labelless). This function is a single place where the
29// decision about displayed name is made.
30function displayedName ($objectData)
31{
32 if ($objectData['name'] != '')
33 return $objectData['name'];
9c0b0016 34 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
a0ec6295 35 return "ANONYMOUS " . $objectData['objtype_name'];
e673ee24 36 else
a0ec6295 37 return "[${objectData['objtype_name']}]";
e673ee24
DO
38}
39
40// This function finds height of solid rectangle of atoms, which are all
41// assigned to the same object. Rectangle base is defined by specified
42// template.
43function rectHeight ($rackData, $startRow, $template_idx)
44{
45 $height = 0;
46 // The first met object_id is used to match all the folowing IDs.
47 $object_id = 0;
48 global $template;
49 do
50 {
51 for ($locidx = 0; $locidx < 3; $locidx++)
52 {
53 // At least one value in template is TRUE, but the following block
54 // can meet 'skipped' atoms. Let's ensure we have something after processing
55 // the first row.
56 if ($template[$template_idx][$locidx])
57 {
58 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
59 break 2;
93e02204
DO
60 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
61 break 2;
62 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
63 break 2;
e673ee24
DO
64 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
65 break 2;
66 if ($object_id == 0)
67 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
68 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
69 break 2;
70 }
71 }
72 // If the first row can't offer anything, bail out.
73 if ($height == 0 and $object_id == 0)
74 break;
75 $height++;
76 }
77 while ($startRow - $height > 0);
93e02204
DO
78# echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
79# echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
80# echo ") height==${height}<br>\n";
e673ee24
DO
81 return $height;
82}
83
84// This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
85// attributes.
86function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
87{
88 global $template, $templateWidth;
89 $colspan = 0;
90 for ($height = 0; $height < $maxheight; $height++)
91 {
92 for ($locidx = 0; $locidx < 3; $locidx++)
93 {
94 if ($template[$template_idx][$locidx])
95 {
96 // Add colspan/rowspan to the first row met and mark the following ones to skip.
93e02204
DO
97 // Explicitly show even single-cell spanned atoms, because rectHeight()
98 // is expeciting this data for correct calculation.
e673ee24
DO
99 if ($colspan != 0)
100 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
101 else
102 {
103 $colspan = $templateWidth[$template_idx];
93e02204 104 if ($colspan >= 1)
e673ee24 105 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
93e02204 106 if ($maxheight >= 1)
e673ee24
DO
107 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
108 }
109 }
110 }
111 }
112 return;
113}
114
93e02204
DO
115// This function sets rowspan/solspan/skipped atom attributes for renderRack()
116// What we actually have to do is to find _all_ possible rectangles for each unit
117// and then select the widest of those with the maximal square.
e673ee24
DO
118function markAllSpans (&$rackData = NULL)
119{
120 if ($rackData == NULL)
121 {
61e269b5 122 showError ('Invalid rackData', __FUNCTION__);
e673ee24
DO
123 return;
124 }
125 for ($i = $rackData['height']; $i > 0; $i--)
93e02204
DO
126 while (markBestSpan ($rackData, $i));
127}
128
129// Calculate height of 6 possible span templates (array is presorted by width
130// descending) and mark the best (if any).
131function markBestSpan (&$rackData, $i)
132{
133 global $template, $templateWidth;
134 for ($j = 0; $j < 6; $j++)
e673ee24 135 {
93e02204
DO
136 $height[$j] = rectHeight ($rackData, $i, $j);
137 $square[$j] = $height[$j] * $templateWidth[$j];
138 }
139 // find the widest rectangle of those with maximal height
140 $maxsquare = max ($square);
141 if (!$maxsquare)
142 return FALSE;
143 $best_template_index = 0;
144 for ($j = 0; $j < 6; $j++)
145 if ($square[$j] == $maxsquare)
e673ee24 146 {
93e02204
DO
147 $best_template_index = $j;
148 $bestheight = $height[$j];
149 break;
e673ee24 150 }
93e02204
DO
151 // distribute span marks
152 markSpan ($rackData, $i, $bestheight, $best_template_index);
153 return TRUE;
e673ee24
DO
154}
155
156function delRow ($row_id = 0)
157{
158 if ($row_id == 0)
159 {
61e269b5 160 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
161 return;
162 }
163 if (!isset ($_REQUEST['confirmed']) || $_REQUEST['confirmed'] != 'true')
164 {
165 echo "Press <a href='?op=del_row&row_id=${row_id}&confirmed=true'>here</a> to confirm rack row deletion.";
166 return;
167 }
168 global $dbxlink;
169 echo 'Deleting rack row information: ';
170 $result = $dbxlink->query ("update RackRow set deleted = 'yes' where id=${row_id} limit 1");
171 if ($result->rowCount() != 1)
172 {
61e269b5 173 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1', __FUNCTION__);
e673ee24
DO
174 return;
175 }
176 echo 'OK<br>';
177 recordHistory ('RackRow', "id = ${row_id}");
178 echo "Information was deleted. You may return to <a href='?op=list_rows&editmode=on'>rack row list</a>.";
179}
180
181function delRack ($rack_id = 0)
182{
183 if ($rack_id == 0)
184 {
61e269b5 185 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
186 return;
187 }
188 if (!isset ($_REQUEST['confirmed']) || $_REQUEST['confirmed'] != 'true')
189 {
190 echo "Press <a href='?op=del_rack&rack_id=${rack_id}&confirmed=true'>here</a> to confirm rack deletion.";
191 return;
192 }
193 global $dbxlink;
194 echo 'Deleting rack information: ';
195 $result = $dbxlink->query ("update Rack set deleted = 'yes' where id=${rack_id} limit 1");
196 if ($result->rowCount() != 1)
197 {
61e269b5 198 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1', __FUNCTION__);
e673ee24
DO
199 return;
200 }
201 echo 'OK<br>';
202 recordHistory ('Rack', "id = ${rack_id}");
203 echo "Information was deleted. You may return to <a href='?op=list_racks&editmode=on'>rack list</a>.";
204}
205
206function delObject ($object_id = 0)
207{
208 if ($object_id == 0)
209 {
61e269b5 210 showError ('Not all required args are present.', __FUNCTION__);
e673ee24
DO
211 return;
212 }
213 if (!isset ($_REQUEST['confirmed']) || $_REQUEST['confirmed'] != 'true')
214 {
215 echo "Press <a href='?op=del_object&object_id=${object_id}&confirmed=true'>here</a> to confirm object deletion.";
216 return;
217 }
218 global $dbxlink;
219 echo 'Deleting object information: ';
220 $result = $dbxlink->query ("update RackObject set deleted = 'yes' where id=${object_id} limit 1");
221 if ($result->rowCount() != 1)
222 {
61e269b5 223 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1', __FUNCTION__);
e673ee24
DO
224 return;
225 }
226 echo 'OK<br>';
227 recordHistory ('RackObject', "id = ${object_id}");
228 echo "Information was deleted. You may return to <a href='?op=list_objects&editmode=on'>object list</a>.";
229}
230
231// We can mount 'F' atoms and unmount our own 'T' atoms.
232function applyObjectMountMask (&$rackData, $object_id)
233{
234 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
235 for ($locidx = 0; $locidx < 3; $locidx++)
236 switch ($rackData[$unit_no][$locidx]['state'])
237 {
238 case 'F':
239 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
240 break;
241 case 'T':
242 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
243 break;
244 default:
245 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
246 }
247}
248
249// Design change means transition between 'F' and 'A' and back.
250function applyRackDesignMask (&$rackData)
251{
252 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
253 for ($locidx = 0; $locidx < 3; $locidx++)
254 switch ($rackData[$unit_no][$locidx]['state'])
255 {
256 case 'F':
257 case 'A':
258 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
259 break;
260 default:
261 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
262 }
263}
264
265// The same for 'F' and 'U'.
266function applyRackProblemMask (&$rackData)
267{
268 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
269 for ($locidx = 0; $locidx < 3; $locidx++)
270 switch ($rackData[$unit_no][$locidx]['state'])
271 {
272 case 'F':
273 case 'U':
274 $rackData[$unit_no][$locidx]['enabled'] = TRUE;
275 break;
276 default:
277 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
278 }
279}
280
281// This mask should allow toggling 'T' and 'W' on object's rackspace.
282function applyObjectProblemMask (&$rackData)
283{
284 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
285 for ($locidx = 0; $locidx < 3; $locidx++)
286 switch ($rackData[$unit_no][$locidx]['state'])
287 {
288 case 'T':
289 case 'W':
290 $rackData[$unit_no][$locidx]['enabled'] = ($rackData[$unit_no][$locidx]['object_id'] == $object_id);
291 break;
292 default:
293 $rackData[$unit_no][$locidx]['enabled'] = FALSE;
294 }
295}
296
297// This function highlights specified object (and removes previous highlight).
298function highlightObject (&$rackData, $object_id)
299{
300 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
301 for ($locidx = 0; $locidx < 3; $locidx++)
302 if
303 (
304 $rackData[$unit_no][$locidx]['state'] == 'T' and
305 $rackData[$unit_no][$locidx]['object_id'] == $object_id
306 )
307 $rackData[$unit_no][$locidx]['hl'] = 'h';
308 else
309 unset ($rackData[$unit_no][$locidx]['hl']);
310}
311
312// This function marks atoms to selected or not depending on their current state.
313function markupAtomGrid (&$data, $checked_state)
314{
315 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
316 for ($locidx = 0; $locidx < 3; $locidx++)
317 {
318 if (!($data[$unit_no][$locidx]['enabled'] === TRUE))
319 continue;
320 if ($data[$unit_no][$locidx]['state'] == $checked_state)
321 $data[$unit_no][$locidx]['checked'] = ' checked';
322 else
323 $data[$unit_no][$locidx]['checked'] = '';
324 }
325}
326
327// This function is almost a clone of processGridForm(), but doesn't save anything to database
328// Return value is the changed rack data.
329// Here we assume that correct filter has already been applied, so we just
330// set or unset checkbox inputs w/o changing atom state.
331function mergeGridFormToRack (&$rackData)
332{
333 $rack_id = $rackData['id'];
334 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
335 for ($locidx = 0; $locidx < 3; $locidx++)
336 {
337 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
338 continue;
339 $inputname = "atom_${rack_id}_${unit_no}_${locidx}";
340 if (isset ($_REQUEST[$inputname]) and $_REQUEST[$inputname] == 'on')
341 $rackData[$unit_no][$locidx]['checked'] = ' checked';
342 else
343 $rackData[$unit_no][$locidx]['checked'] = '';
344 }
345}
346
347function binMaskFromDec ($maskL)
348{
349 $binmask=0;
350 for ($i=0; $i<$maskL; $i++)
351 {
352 $binmask*=2;
353 $binmask+=1;
354 }
355 for ($i=$maskL; $i<32; $i++)
356 {
357 $binmask*=2;
358 }
359 return $binmask;
360}
361
362function binInvMaskFromDec ($maskL)
363{
364 $binmask=0;
365 for ($i=0; $i<$maskL; $i++)
366 {
367 $binmask*=2;
368 }
369 for ($i=$maskL; $i<32; $i++)
370 {
371 $binmask*=2;
372 $binmask+=1;
373 }
374 return $binmask;
375}
376
fa05e3de 377function addRange ($range='', $name='', $is_bcast = FALSE, $taglist = array())
e673ee24 378{
2a201216
DY
379 // $range is in x.x.x.x/x format, split into ip/mask vars
380 $rangeArray = explode('/', $range);
6e8868cc
DO
381 if (count ($rangeArray) != 2)
382 return "Invalid IP subnet '${range}'";
2a201216
DY
383 $ip = $rangeArray[0];
384 $mask = $rangeArray[1];
385
c87fd3fe
DO
386 if (empty ($ip) or empty ($mask))
387 return "Invalid IP subnet '${range}'";
e673ee24
DO
388 $ipL = ip2long($ip);
389 $maskL = ip2long($mask);
390 if ($ipL == -1 || $ipL === FALSE)
391 return 'Bad ip address';
392 if ($mask < 32 && $mask > 0)
393 $maskL = $mask;
394 else
395 {
396 $maskB = decbin($maskL);
397 if (strlen($maskB)!=32)
398 return 'Bad mask';
399 $ones=0;
400 $zeroes=FALSE;
401 foreach( str_split ($maskB) as $digit)
402 {
403 if ($digit == '0')
404 $zeroes = TRUE;
405 if ($digit == '1')
406 {
407 $ones++;
408 if ($zeroes == TRUE)
409 return 'Bad mask';
410 }
411 }
412 $maskL = $ones;
413 }
414 $binmask = binMaskFromDec($maskL);
415 $ipL = $ipL & $binmask;
416
417 $query =
418 "select ".
419 "id, ip, mask, name ".
420 "from IPRanges ";
421
422
fa05e3de 423 $result = useSelectBlade ($query);
e673ee24
DO
424
425 while ($row = $result->fetch (PDO::FETCH_ASSOC))
426 {
427 $otherip = $row['ip'];
428 $othermask = binMaskFromDec($row['mask']);
429// echo "checking $otherip & $othermask ".($otherip & $othermask)." == $ipL & $othermask ".($ipL & $othermask)." ".decbin($otherip)." ".decbin($othermask)." ".decbin($otherip & $othermask)." ".decbin($ipL)." ".decbin($othermask)." ".decbin($ipL & $othermask)."\n";
430// echo "checking $otherip & $binmask ".($otherip & $binmask)." == $ipL & $binmask ".($ipL & $binmask)." ".decbin($otherip)." ".decbin($binmask)." ".decbin($otherip & $binmask)." ".decbin($ipL)." ".decbin($binmask)." ".decbin($ipL & $binmask)."\n";
431// echo "\n";
432// flush();
433 if (($otherip & $othermask) == ($ipL & $othermask))
434 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
435 if (($otherip & $binmask) == ($ipL & $binmask))
436 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
437 }
438 $result->closeCursor();
fa05e3de
DO
439 unset ($result);
440 $result = useInsertBlade
441 (
442 'IPRanges',
443 array
444 (
445 'ip' => sprintf ('%u', $ipL),
446 'mask' => "'${maskL}'",
447 'name' => "'${name}'"
448 )
449 );
2dee289e
DO
450
451 if ($is_bcast and $maskL < 31)
452 {
453 $network_addr = long2ip ($ipL);
454 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
455 updateAddress ($network_addr, 'network', 'yes');
456 updateAddress ($broadcast_addr, 'broadcast', 'yes');
457 }
fa05e3de
DO
458 if (!count ($taglist))
459 return '';
460 if (($result = useSelectBlade ('select last_insert_id()')) == NULL)
461 return 'Query #3 failed in ' . __FUNCTION__;
462 $row = $result->fetch (PDO::FETCH_NUM);
463 $netid = $row[0];
850a12ea
DO
464 $result->closeCursor();
465 unset ($result);
fa05e3de
DO
466 $errcount = 0;
467 foreach ($taglist as $tag_id)
468 if (useInsertBlade
469 (
470 'TagStorage',
471 array
472 (
473 'target_realm' => "'ipv4net'",
474 'target_id' => $netid,
475 'tag_id' => $tag_id
476 )
477 ) == FALSE)
478 $errcount++;
479 if (!$errcount)
480 return '';
481 else
482 return "Experienced ${errcount} errors adding tags for the network";
e673ee24
DO
483}
484
485function getIPRange ($id = 0)
486{
487 global $dbxlink;
488 $query =
489 "select ".
490 "id as IPRanges_id, ".
491 "INET_NTOA(ip) as IPRanges_ip, ".
e673ee24
DO
492 "mask as IPRanges_mask, ".
493 "name as IPRanges_name ".
494 "from IPRanges ".
495 "where id = '$id'";
602663f4 496 $result = useSelectBlade ($query);
5c43a978 497 $ret = array();
55cc3e4e
DO
498 $row = $result->fetch (PDO::FETCH_ASSOC);
499 if ($row == NULL)
500 return $ret;
501 $ret['id'] = $row['IPRanges_id'];
502 $ret['ip'] = $row['IPRanges_ip'];
7e039e88 503 $ret['ip_bin'] = ip2long ($row['IPRanges_ip']);
55cc3e4e
DO
504 $ret['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
505 $ret['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
506 $ret['name'] = $row['IPRanges_name'];
507 $ret['mask'] = $row['IPRanges_mask'];
508 $ret['addrlist'] = array();
55cc3e4e 509 $result->closeCursor();
602663f4 510 unset ($result);
7e039e88
DO
511 // We risk losing some significant bits in an unsigned 32bit integer,
512 // unless it is converted to a string.
513 $db_first = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']) . "'";
514 $db_last = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv'])) . "'";
5c43a978
DO
515
516 // Don't try to build up the whole structure in a single pass. Request
517 // the list of user comments and reservations and merge allocations in
518 // at a latter point.
55cc3e4e 519 $query =
7e039e88
DO
520 "select INET_NTOA(ip) as ip, name, reserved from IPAddress " .
521 "where ip between ${db_first} and ${db_last} " .
5c43a978 522 "and (reserved = 'yes' or name != '')";
602663f4
DO
523 $result = $dbxlink->query ($query);
524 while ($row = $result->fetch (PDO::FETCH_ASSOC))
55cc3e4e 525 {
7e039e88
DO
526 $ip_bin = ip2long ($row['ip']);
527 $ret['addrlist'][$ip_bin] = $row;
5c43a978
DO
528 $tmp = array();
529 foreach (array ('ip', 'name', 'reserved') as $cname)
530 $tmp[$cname] = $row[$cname];
531 $tmp['references'] = array();
602663f4
DO
532 $tmp['lbrefs'] = array();
533 $tmp['rsrefs'] = array();
7e039e88 534 $ret['addrlist'][$ip_bin] = $tmp;
5c43a978 535 }
602663f4
DO
536 $result->closeCursor();
537 unset ($result);
e673ee24 538
5c43a978 539 $query =
dda31a62
DO
540 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
541 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
542 "dict_value as objtype_name from " .
5c43a978 543 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
dda31a62 544 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
7e039e88 545 "where ip between ${db_first} and ${db_last} " .
dda31a62 546 "and chapter_name = 'RackObjectType'" .
5c43a978 547 "order by ipb.type, object_name";
602663f4
DO
548 $result = useSelectBlade ($query);
549 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5c43a978 550 {
7e039e88
DO
551 $ip_bin = ip2long ($row['ip']);
552 if (!isset ($ret['addrlist'][$ip_bin]))
55cc3e4e 553 {
7e039e88
DO
554 $ret['addrlist'][$ip_bin] = array();
555 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
556 $ret['addrlist'][$ip_bin]['name'] = '';
557 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
558 $ret['addrlist'][$ip_bin]['references'] = array();
602663f4
DO
559 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
560 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
e673ee24 561 }
5c43a978 562 $tmp = array();
dda31a62 563 foreach (array ('object_id', 'type', 'name') as $cname)
5c43a978 564 $tmp[$cname] = $row[$cname];
dda31a62
DO
565 $quasiobject['name'] = $row['object_name'];
566 $quasiobject['objtype_id'] = $row['objtype_id'];
567 $quasiobject['objtype_name'] = $row['objtype_name'];
568 $tmp['object_name'] = displayedName ($quasiobject);
7e039e88 569 $ret['addrlist'][$ip_bin]['references'][] = $tmp;
e673ee24 570 }
602663f4
DO
571 $result->closeCursor();
572 unset ($result);
573
574 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, " .
575 "object_id, objtype_id, ro.name, dict_value as objtype_name from " .
576 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
577 "inner join RackObject as ro on lb.object_id = ro.id " .
578 "left join Dictionary on objtype_id=dict_key " .
579 "natural join Chapter " .
580 "where vip between ${db_first} and ${db_last} " .
581 "and chapter_name = 'RackObjectType'" .
582 "order by vport, proto, ro.name, object_id";
583 $result = useSelectBlade ($query);
584 while ($row = $result->fetch (PDO::FETCH_ASSOC))
585 {
586 $ip_bin = ip2long ($row['ip']);
587 if (!isset ($ret['addrlist'][$ip_bin]))
588 {
589 $ret['addrlist'][$ip_bin] = array();
590 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
591 $ret['addrlist'][$ip_bin]['name'] = '';
592 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
593 $ret['addrlist'][$ip_bin]['references'] = array();
594 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
595 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
596 }
597 $tmp = $qbject = array();
598 foreach (array ('object_id', 'vport', 'proto', 'vs_id') as $cname)
599 $tmp[$cname] = $row[$cname];
600 foreach (array ('name', 'objtype_id', 'objtype_name') as $cname)
601 $qobject[$cname] = $row[$cname];
602 $tmp['object_name'] = displayedName ($qobject);
603 $ret['addrlist'][$ip_bin]['lbrefs'][] = $tmp;
604 }
605 $result->closeCursor();
606 unset ($result);
607
608 $query = "select inet_ntoa(rsip) as ip, rsport, rspool_id, rsp.name as rspool_name from " .
609 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
610 "where rsip between ${db_first} and ${db_last} " .
611 "order by ip, rsport, rspool_id";
612 $result = useSelectBlade ($query);
613 while ($row = $result->fetch (PDO::FETCH_ASSOC))
614 {
615 $ip_bin = ip2long ($row['ip']);
616 if (!isset ($ret['addrlist'][$ip_bin]))
617 {
618 $ret['addrlist'][$ip_bin] = array();
619 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
620 $ret['addrlist'][$ip_bin]['name'] = '';
621 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
622 $ret['addrlist'][$ip_bin]['references'] = array();
623 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
624 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
625 }
626 $tmp = array();
627 foreach (array ('rspool_id', 'rsport', 'rspool_name') as $cname)
628 $tmp[$cname] = $row[$cname];
629 $ret['addrlist'][$ip_bin]['rsrefs'][] = $tmp;
630 }
5c43a978 631
e673ee24
DO
632 return $ret;
633}
634
dda31a62
DO
635// Don't require any records in IPAddress, but if there is one,
636// merge the data between getting allocation list. Collect enough data
637// to call displayedName() ourselves.
b4c1ef87 638function getIPAddress ($ip = 0)
e673ee24
DO
639{
640 $ret = array();
e673ee24 641 $ret['bonds'] = array();
59bebe2b 642 // FIXME: below two aren't neither filled in with data nor rendered (ticket:23)
e673ee24
DO
643 $ret['outpf'] = array();
644 $ret['inpf'] = array();
59bebe2b
DO
645 $ret['vslist'] = array();
646 $ret['rslist'] = array();
e673ee24 647 $ret['exists'] = 0;
dda31a62 648 $ret['name'] = '';
e673ee24 649 $ret['reserved'] = 'no';
59bebe2b 650 $query =
e673ee24 651 "select ".
dda31a62 652 "name, reserved ".
e673ee24 653 "from IPAddress ".
dda31a62 654 "where ip = INET_ATON('$ip') and (reserved = 'yes' or name != '')";
b4c1ef87 655 $result = useSelectBlade ($query);
59bebe2b 656 if ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 657 {
959c4f4c 658 $ret['exists'] = 1;
959c4f4c
DO
659 $ret['name'] = $row['name'];
660 $ret['reserved'] = $row['reserved'];
e673ee24 661 }
59bebe2b
DO
662 $result->closeCursor();
663 unset ($result);
e673ee24 664
59bebe2b 665 $query =
dda31a62
DO
666 "select ".
667 "IPBonds.object_id as object_id, ".
668 "IPBonds.name as name, ".
669 "IPBonds.type as type, ".
670 "objtype_id, dict_value as objtype_name, " .
671 "RackObject.name as object_name ".
672 "from IPBonds join RackObject on IPBonds.object_id=RackObject.id ".
673 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
674 "where IPBonds.ip=INET_ATON('$ip') ".
675 "and chapter_name = 'RackObjectType' " .
676 "order by RackObject.id, IPBonds.name";
b4c1ef87 677 $result = useSelectBlade ($query);
dda31a62 678 $count=0;
59bebe2b 679 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 680 {
dda31a62
DO
681 $ret['bonds'][$count]['object_id'] = $row['object_id'];
682 $ret['bonds'][$count]['name'] = $row['name'];
683 $ret['bonds'][$count]['type'] = $row['type'];
684 $qo = array();
685 $qo['name'] = $row['object_name'];
686 $qo['objtype_id'] = $row['objtype_id'];
687 $qo['objtype_name'] = $row['objtype_name'];
688 $ret['bonds'][$count]['object_name'] = displayedName ($qo);
689 $count++;
690 $ret['exists'] = 1;
e673ee24 691 }
59bebe2b
DO
692 $result->closeCursor();
693 unset ($result);
694
5fe1ed76 695 $query = "select id, vport, proto, name from IPVirtualService where vip = inet_aton('${ip}')";
b4c1ef87 696 $result = useSelectBlade ($query);
59bebe2b 697 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5fe1ed76
DO
698 {
699 $new = $row;
700 $new['vip'] = $ip;
701 $ret['vslist'][] = $new;
702 }
703 $result->closeCursor();
704 unset ($result);
705
706 $query = "select inservice, rsport, IPRSPool.id as pool_id, IPRSPool.name as poolname from " .
707 "IPRealServer inner join IPRSPool on rspool_id = IPRSPool.id " .
708 "where rsip = inet_aton('${ip}')";
b4c1ef87 709 $result = useSelectBlade ($query);
5fe1ed76
DO
710 while ($row = $result->fetch (PDO::FETCH_ASSOC))
711 {
712 $new = $row;
713 $new['rsip'] = $ip;
714 $ret['rslist'][] = $new;
715 }
59bebe2b
DO
716 $result->closeCursor();
717 unset ($result);
e673ee24
DO
718
719 return $ret;
720}
721
b4c1ef87 722function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
e673ee24
DO
723{
724 global $dbxlink;
725
b4c1ef87 726 $range = getRangeByIp ($ip);
e673ee24
DO
727 if (!$range)
728 return 'Non-existant ip address. Try adding IP range first';
729
20a92aa2
DO
730 $result = useInsertBlade
731 (
732 'IPBonds',
733 array
734 (
dda31a62 735 'ip' => "INET_ATON('$ip')",
20a92aa2
DO
736 'object_id' => "'${object_id}'",
737 'name' => "'${name}'",
738 'type' => "'${type}'"
739 )
740 );
b4c1ef87 741 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
e673ee24
DO
742}
743
744// This function looks up 'has_problems' flag for 'T' atoms
745// and modifies 'hl' key. May be, this should be better done
746// in getRackData(). We don't honour 'skipped' key, because
747// the function is also used for thumb creation.
748function markupObjectProblems (&$rackData)
749{
750 for ($i = $rackData['height']; $i > 0; $i--)
751 for ($locidx = 0; $locidx < 3; $locidx++)
752 if ($rackData[$i][$locidx]['state'] == 'T')
753 {
754 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
755 if ($object['has_problems'] == 'yes')
756 {
757 // Object can be already highlighted.
758 if (isset ($rackData[$i][$locidx]['hl']))
759 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
760 else
761 $rackData[$i][$locidx]['hl'] = 'w';
762 }
763 }
764}
765
766function search_cmpObj ($a, $b)
767{
768 return ($a['score'] > $b['score'] ? -1 : 1);
769}
770
771// This function performs search and then calculates score for each result.
772// Given previous search results in $objects argument, it adds new results
773// to the array and updates score for existing results, if it is greater than
774// existing score.
775function mergeSearchResults (&$objects, $terms, $fieldname)
776{
777 global $dbxlink;
778 $query =
779 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
780 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
781 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
782 $count = 0;
783 foreach (explode (' ', $terms) as $term)
784 {
785 if ($count) $query .= ' or ';
786 $query .= "${fieldname} like '%$term%'";
787 $count++;
788 }
ea5fc465 789 $result = useSelectBlade ($query);
e673ee24
DO
790// FIXME: this dead call was executed 4 times per 1 object search!
791// $typeList = getObjectTypeList();
792 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
793 while ($row = $result->fetch(PDO::FETCH_ASSOC))
794 {
795 foreach ($clist as $cname)
796 $object[$cname] = $row[$cname];
797 $object['score'] = 0;
798 $object['dname'] = displayedName ($object);
799 unset ($object['objtype_id']);
800 foreach (explode (' ', $terms) as $term)
801 if (strstr ($object['name'], $term))
802 $object['score'] += 1;
803 unset ($object['name']);
804 if (!isset ($objects[$row['id']]))
805 $objects[$row['id']] = $object;
806 elseif ($objects[$row['id']]['score'] < $object['score'])
807 $objects[$row['id']]['score'] = $object['score'];
808 }
809 return $objects;
810}
811
ea5fc465 812function getObjectSearchResults ($terms)
e673ee24
DO
813{
814 $objects = array();
815 mergeSearchResults ($objects, $terms, 'name');
816 mergeSearchResults ($objects, $terms, 'label');
817 mergeSearchResults ($objects, $terms, 'asset_no');
818 mergeSearchResults ($objects, $terms, 'barcode');
819 if (count ($objects) == 1)
820 usort ($objects, 'search_cmpObj');
821 return $objects;
822}
823
824// This function removes all colons and dots from a string.
825function l2addressForDatabase ($string)
826{
827 if (empty ($string))
828 return 'NULL';
829 $pieces = explode (':', $string);
830 // This workaround is for SunOS ifconfig.
831 foreach ($pieces as &$byte)
832 if (strlen ($byte) == 1)
833 $byte = '0' . $byte;
834 // And this workaround is for PHP.
835 unset ($byte);
836 $string = implode ('', $pieces);
837 $pieces = explode ('.', $string);
838 $string = implode ('', $pieces);
839 $string = strtoupper ($string);
840 return "'$string'";
841}
842
843function l2addressFromDatabase ($string)
844{
845 switch (strlen ($string))
846 {
847 case 12: // Ethernet
848 case 16: // FireWire
849 $ret = implode (':', str_split ($string, 2));
850 break;
851 default:
852 $ret = $string;
853 break;
854 }
855 return $ret;
856}
857
858// The following 2 functions return previous and next rack IDs for
859// a given rack ID. The order of racks is the same as in renderRackspace()
860// or renderRow().
861function getPrevIDforRack ($row_id = 0, $rack_id = 0)
862{
863 if ($row_id <= 0 or $rack_id <= 0)
864 {
61e269b5 865 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
866 return NULL;
867 }
868 $rackList = getRacksForRow ($row_id);
869 doubleLink ($rackList);
870 if (isset ($rackList[$rack_id]['prev_key']))
871 return $rackList[$rack_id]['prev_key'];
872 return NULL;
873}
874
875function getNextIDforRack ($row_id = 0, $rack_id = 0)
876{
877 if ($row_id <= 0 or $rack_id <= 0)
878 {
61e269b5 879 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
880 return NULL;
881 }
882 $rackList = getRacksForRow ($row_id);
883 doubleLink ($rackList);
884 if (isset ($rackList[$rack_id]['next_key']))
885 return $rackList[$rack_id]['next_key'];
886 return NULL;
887}
888
889// This function finds previous and next array keys for each array key and
890// modifies its argument accordingly.
891function doubleLink (&$array)
892{
893 $prev_key = NULL;
894 foreach (array_keys ($array) as $key)
895 {
896 if ($prev_key)
897 {
898 $array[$key]['prev_key'] = $prev_key;
899 $array[$prev_key]['next_key'] = $key;
900 }
901 $prev_key = $key;
902 }
903}
904
905// After applying usort() to a rack list we will lose original array keys.
906// This function restores the keys so they are equal to rack IDs.
907function restoreRackIDs ($racks)
908{
909 $ret = array();
910 foreach ($racks as $rack)
911 $ret[$rack['id']] = $rack;
912 return $ret;
913}
914
915function sortTokenize ($a, $b)
916{
917 $aold='';
918 while ($a != $aold)
919 {
920 $aold=$a;
921 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
922 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
923 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
924 }
925
926 $bold='';
927 while ($b != $bold)
928 {
929 $bold=$b;
930 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
931 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
932 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
933 }
934
935
936
937 $ar = explode(' ', $a);
938 $br = explode(' ', $b);
939 for ($i=0; $i<count($ar) && $i<count($br); $i++)
940 {
941 $ret = 0;
942 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
943 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
944 else
945 $ret = strcasecmp($ar[$i], $br[$i]);
946 if ($ret != 0)
947 return $ret;
948 }
949 if ($i<count($ar))
950 return 1;
951 if ($i<count($br))
952 return -1;
953 return 0;
954}
955
956function sortByName ($a, $b)
957{
958 return sortTokenize($a['name'], $b['name']);
959}
960
6a3a37b2
DO
961function sortRacks ($a, $b)
962{
963 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
964}
965
e673ee24
DO
966function eq ($a, $b)
967{
968 return $a==$b;
969}
970
971function neq ($a, $b)
972{
973 return $a!=$b;
974}
975
976function countRefsOfType ($refs, $type, $eq)
977{
978 $count=0;
979 foreach ($refs as $ref)
980 {
981 if ($eq($ref['type'], $type))
982 $count++;
983 }
984 return $count;
985}
986
987function sortEmptyPorts ($a, $b)
988{
989 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
990 if ($objname_cmp == 0)
991 {
992 return sortTokenize($a['Port_name'], $b['Port_name']);
993 }
994 return $objname_cmp;
995}
996
997function sortObjectAddressesAndNames ($a, $b)
998{
999 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
1000 if ($objname_cmp == 0)
1001 {
79f22c3d
DO
1002 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
1003 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
1004 $objname_cmp = sortTokenize($name_a, $name_b);
e673ee24 1005 if ($objname_cmp == 0)
e673ee24 1006 sortTokenize($a['ip'], $b['ip']);
e673ee24
DO
1007 return $objname_cmp;
1008 }
1009 return $objname_cmp;
1010}
1011
1012
1013
1014function sortAddresses ($a, $b)
1015{
1016 $name_cmp = sortTokenize($a['name'], $b['name']);
1017 if ($name_cmp == 0)
1018 {
1019 return sortTokenize($a['ip'], $b['ip']);
1020 }
1021 return $name_cmp;
1022}
1023
1024// This function expands port compat list into a matrix.
1025function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
1026{
1027 $matrix = array();
1028 // Create type matrix and markup compatible types.
1029 foreach (array_keys ($portTypeList) as $type1)
1030 foreach (array_keys ($portTypeList) as $type2)
1031 $matrix[$type1][$type2] = FALSE;
1032 foreach ($portCompatList as $pair)
1033 $matrix[$pair['type1']][$pair['type2']] = TRUE;
1034 return $matrix;
1035}
1036
1037function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
1038{
1039 global $dbxlink;
1040
1041 $range = getRangeByIp($localip);
1042 if (!$range)
1043 return "$localip: Non existant ip";
1044
1045 $range = getRangeByIp($remoteip);
1046 if (!$range)
1047 return "$remoteip: Non existant ip";
1048
1049 if ( ($localport <= 0) or ($localport >= 65536) )
1050 return "$localport: invaild port";
1051
1052 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
1053 return "$remoteport: invaild port";
1054
9bea3a8b
DO
1055 $result = useInsertBlade
1056 (
1057 'PortForwarding',
1058 array
1059 (
1060 'object_id' => $object_id,
1061 'localip' => "INET_ATON('${localip}')",
1062 'remoteip' => "INET_ATON('$remoteip')",
1063 'localport' => $localport,
1064 'remoteport' => $remoteport,
1065 'proto' => "'${proto}'",
1066 'description' => "'${description}'",
1067 )
1068 );
1069 if ($result)
1070 return '';
1071 else
1072 return __FUNCTION__ . ': Failed to insert the rule.';
e673ee24
DO
1073}
1074
1075function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
1076{
1077 global $dbxlink;
1078
1079 $query =
1080 "delete from PortForwarding where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
1081 $result = $dbxlink->exec ($query);
1082 return '';
1083}
1084
1085function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
1086{
1087 global $dbxlink;
1088
1089 $query =
1090 "update PortForwarding set description='$description' where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
1091 $result = $dbxlink->exec ($query);
1092 return '';
1093}
1094
eeb4a5d8 1095function getNATv4ForObject ($object_id)
e673ee24 1096{
e673ee24
DO
1097 $ret = array();
1098 $ret['out'] = array();
1099 $ret['in'] = array();
1100 $query =
1101 "select ".
eeb4a5d8 1102 "proto, ".
e673ee24
DO
1103 "INET_NTOA(localip) as localip, ".
1104 "localport, ".
1105 "INET_NTOA(remoteip) as remoteip, ".
1106 "remoteport, ".
f28fbe8b
DO
1107 "ipa1.name as local_addr_name, " .
1108 "ipa2.name as remote_addr_name, " .
e673ee24 1109 "description ".
eeb4a5d8 1110 "from PortForwarding ".
f28fbe8b
DO
1111 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
1112 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
eeb4a5d8 1113 "where object_id='$object_id' ".
e673ee24 1114 "order by localip, localport, proto, remoteip, remoteport";
eeb4a5d8 1115 $result = useSelectBlade ($query);
e673ee24 1116 $count=0;
eeb4a5d8 1117 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 1118 {
eeb4a5d8 1119 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
f28fbe8b 1120 $ret['out'][$count][$cname] = $row[$cname];
e673ee24
DO
1121 $count++;
1122 }
eeb4a5d8
DO
1123 $result->closeCursor();
1124 unset ($result);
e673ee24
DO
1125
1126 $query =
1127 "select ".
eeb4a5d8 1128 "proto, ".
e673ee24
DO
1129 "INET_NTOA(localip) as localip, ".
1130 "localport, ".
1131 "INET_NTOA(remoteip) as remoteip, ".
1132 "remoteport, ".
1133 "PortForwarding.object_id as object_id, ".
1134 "RackObject.name as object_name, ".
1135 "description ".
eeb4a5d8
DO
1136 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
1137 "where IPBonds.object_id='$object_id' ".
e673ee24 1138 "order by remoteip, remoteport, proto, localip, localport";
eeb4a5d8 1139 $result = useSelectBlade ($query);
e673ee24 1140 $count=0;
eeb4a5d8 1141 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 1142 {
eeb4a5d8 1143 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
f28fbe8b 1144 $ret['in'][$count][$cname] = $row[$cname];
e673ee24
DO
1145 $count++;
1146 }
eeb4a5d8 1147 $result->closeCursor();
e673ee24
DO
1148
1149 return $ret;
1150}
1151
c31cd72c 1152// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
1153// if FQDN is set. The next choice is object's common name, if it looks like a
1154// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 1155// object is returned (which may appear 0 and more elements long).
f321b50a 1156function findAllEndpoints ($object_id, $fallback = '')
c31cd72c
DO
1157{
1158 $values = getAttrValues ($object_id);
1159 foreach ($values as $record)
f321b50a 1160 if ($record['name'] == 'FQDN' && !empty ($record['value']))
c31cd72c
DO
1161 return array ($record['value']);
1162 $addresses = getObjectAddresses ($object_id);
1163 $regular = array();
1164 foreach ($addresses as $idx => $address)
1165 if ($address['type'] == 'regular')
fa8112d1 1166 $regular[] = $address['ip'];
f321b50a
DO
1167 if (!count ($regular) && !empty ($fallback))
1168 return array ($fallback);
c31cd72c
DO
1169 return $regular;
1170}
1171
83ba6670
DO
1172// Some records in the dictionary may be written as plain text or as Wiki
1173// link in the following syntax:
1174// 1. word
1175// 2. [[word URL]] // FIXME: this isn't working
1176// 3. [[word word word | URL]]
1177// This function parses the line and returns text suitable for either A
1178// (rendering <A HREF>) or O (for <OPTION>).
24cbe8af 1179function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
83ba6670 1180{
010231c2 1181 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af
DO
1182 {
1183 if ($strip_optgroup)
f0b540a3 1184 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
24cbe8af
DO
1185 else
1186 return $line;
1187 }
010231c2
DO
1188 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
1189 $s = explode ('|', $line);
83ba6670 1190 $o_value = trim ($s[0]);
24cbe8af 1191 if ($strip_optgroup)
f0b540a3 1192 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
83ba6670
DO
1193 $a_value = trim ($s[1]);
1194 if ($which == 'a')
010231c2 1195 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
1196 if ($which == 'o')
1197 return $o_value;
1198}
1199
2de490b7
DO
1200function buildVServiceName ($vsinfo = NULL)
1201{
1202 if ($vsinfo == NULL)
1203 {
1204 showError ('NULL argument', __FUNCTION__);
1205 return NULL;
1206 }
8d790216 1207 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
2de490b7
DO
1208}
1209
05411ccd
DO
1210function buildRSPoolName ($rspool = NULL)
1211{
1212 if ($rspool == NULL)
1213 {
1214 showError ('NULL argument', __FUNCTION__);
1215 return NULL;
1216 }
1217 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
1218}
1219
177b1e9b
DO
1220// rackspace usage for a single rack
1221// (T + W + U) / (height * 3 - A)
11df133a 1222function getRSUforRack ($data = NULL)
177b1e9b 1223{
11df133a 1224 if ($data == NULL)
177b1e9b
DO
1225 {
1226 showError ('Invalid argument', __FUNCTION__);
1227 return NULL;
1228 }
6ffba290 1229 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
1230 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1231 for ($locidx = 0; $locidx < 3; $locidx++)
1232 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 1233 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
1234}
1235
11df133a
DO
1236// Same for row.
1237function getRSUforRackRow ($rowData = NULL)
1238{
bb26a59e 1239 if ($rowData === NULL)
11df133a
DO
1240 {
1241 showError ('Invalid argument', __FUNCTION__);
1242 return NULL;
1243 }
bb26a59e
DO
1244 if (!count ($rowData))
1245 return 0;
11df133a 1246 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 1247 $total_height = 0;
dfa3c075
DO
1248 foreach (array_keys ($rowData) as $rack_id)
1249 {
1250 $data = getRackData ($rack_id);
1251 $total_height += $data['height'];
11df133a
DO
1252 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1253 for ($locidx = 0; $locidx < 3; $locidx++)
1254 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
1255 }
1256 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
1257}
1258
f1a0477d
DO
1259function getObjectCount ($rackData)
1260{
1261 $objects = array();
1262 for ($i = $rackData['height']; $i > 0; $i--)
1263 for ($locidx = 0; $locidx < 3; $locidx++)
1264 if
1265 (
1266 $rackData[$i][$locidx]['state'] == 'T' and
1267 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
1268 )
1269 $objects[] = $rackData[$i][$locidx]['object_id'];
1270 return count ($objects);
1271}
1272
9af110b4
DO
1273// Perform substitutions and return resulting string
1274function apply_macros ($macros, $subject)
1275{
1276 $ret = $subject;
1277 foreach ($macros as $search => $replace)
1278 $ret = str_replace ($search, $replace, $ret);
1279 return $ret;
1280}
1281
1282// Make sure the string is always wrapped with LF characters
1283function lf_wrap ($str)
1284{
1285 $ret = trim ($str, "\r\n");
1286 if (!empty ($ret))
1287 $ret .= "\n";
1288 return $ret;
1289}
1290
e6e7d8b3
DO
1291// Adopted from Mantis BTS code.
1292function string_insert_hrefs ($s)
1293{
1294 if (getConfigVar ('DETECT_URLS') != 'yes')
1295 return $s;
1296 # Find any URL in a string and replace it by a clickable link
1297 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
1298 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
1299 $s);
1300 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
1301 '<a href="mailto:\0">\0</a>',
1302 $s);
1303 return $s;
1304}
1305
1306// Idem.
1307function email_regex_simple ()
1308{
1309 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
1310 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
1311}
1312
118e4c38
DO
1313// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
1314// for the requested object_type_id.
1315function getAutoPorts ($type_id)
1316{
1317 $ret = array();
1318 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
1319 foreach ($typemap as $equation)
1320 {
1321 $tmp = explode ('=', $equation);
1322 if (count ($tmp) != 2)
1323 continue;
1324 $objtype_id = $tmp[0];
1325 if ($objtype_id != $type_id)
1326 continue;
1327 $portlist = $tmp[1];
1328 foreach (explode ('+', $portlist) as $product)
1329 {
1330 $tmp = explode ('*', $product);
1331 if (count ($tmp) != 3)
1332 continue;
1333 $nports = $tmp[0];
1334 $port_type = $tmp[1];
1335 $format = $tmp[2];
1336 for ($i = 0; $i < $nports; $i++)
1337 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
1338 }
1339 }
1340 return $ret;
1341}
1342
9dfd4cc9
DO
1343// Find if a particular tag id exists on the tree, then attach the
1344// given child tag to it. If the parent tag doesn't exist, return FALSE.
1345function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
1346{
1347 foreach ($tree as $tagid => $taginfo)
1348 {
1349 if ($tagid == $parent_id)
1350 {
1351 $tree[$tagid]['kids'][$child_id] = $child_info;
1352 return TRUE;
1353 }
1354 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
1355 return TRUE;
1356 }
1357 return FALSE;
1358}
1359
1360// Build a tree from the tag list and return it.
1361function getTagTree ()
1362{
20c901a7
DO
1363 global $taglist;
1364 $mytaglist = $taglist;
1365 $ret = array();
1366 while (count ($mytaglist) > 0)
9dfd4cc9
DO
1367 {
1368 $picked = FALSE;
20c901a7 1369 foreach ($mytaglist as $tagid => $taginfo)
9dfd4cc9
DO
1370 {
1371 $taginfo['kids'] = array();
1372 if ($taginfo['parent_id'] == NULL)
1373 {
20c901a7 1374 $ret[$tagid] = $taginfo;
9dfd4cc9 1375 $picked = TRUE;
20c901a7 1376 unset ($mytaglist[$tagid]);
9dfd4cc9 1377 }
20c901a7 1378 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
9dfd4cc9
DO
1379 {
1380 $picked = TRUE;
20c901a7 1381 unset ($mytaglist[$tagid]);
9dfd4cc9
DO
1382 }
1383 }
1384 if (!$picked) // Only orphaned items on the list.
1385 break;
1386 }
20c901a7 1387 return $ret;
9dfd4cc9
DO
1388}
1389
49fb1027
DO
1390// Build a tree from the tag list and return everything _except_ the tree.
1391function getOrphanedTags ()
1392{
1393 global $taglist;
1394 $mytaglist = $taglist;
1395 $dummy = array();
1396 while (count ($mytaglist) > 0)
1397 {
1398 $picked = FALSE;
1399 foreach ($mytaglist as $tagid => $taginfo)
1400 {
1401 $taginfo['kids'] = array();
1402 if ($taginfo['parent_id'] == NULL)
1403 {
1404 $dummy[$tagid] = $taginfo;
1405 $picked = TRUE;
1406 unset ($mytaglist[$tagid]);
1407 }
1408 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
1409 {
1410 $picked = TRUE;
1411 unset ($mytaglist[$tagid]);
1412 }
1413 }
1414 if (!$picked) // Only orphaned items on the list.
1415 return $mytaglist;
1416 }
1417 return array();
1418}
1419
e2ac59cf 1420function serializeTags ($trail, $baseurl = '')
ba93bd98
DO
1421{
1422 $comma = '';
1423 $ret = '';
1424 foreach ($trail as $taginfo)
1425 {
e2ac59cf
DO
1426 $ret .= $comma .
1427 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
1428 $taginfo['tag'] .
1429 ($baseurl == '' ? '' : '</a>');
ba93bd98
DO
1430 $comma = ', ';
1431 }
1432 return $ret;
1433}
1434
ab379543 1435// a helper for getTrailExpansion()
ba93bd98
DO
1436function traceTrail ($tree, $trail)
1437{
1438 // For each tag find its path from the root, then combine items
1439 // of all paths and add them to the trail, if they aren't there yet.
1440 $ret = array();
1441 foreach ($tree as $taginfo1)
1442 {
1443 $hit = FALSE;
1444 foreach ($trail as $taginfo2)
1445 if ($taginfo1['id'] == $taginfo2['id'])
1446 {
1447 $hit = TRUE;
1448 break;
1449 }
1450 if (count ($taginfo1['kids']) > 0)
1451 {
1452 $subsearch = traceTrail ($taginfo1['kids'], $trail);
1453 if (count ($subsearch))
1454 {
1455 $hit = TRUE;
1456 $ret = array_merge ($ret, $subsearch);
1457 }
1458 }
1459 if ($hit)
1460 $ret[] = $taginfo1;
1461 }
1462 return $ret;
1463}
1464
1465// For each tag add all its parent tags onto the list. Don't expect anything
1466// except user's tags on the trail.
1467function getTrailExpansion ($trail)
1468{
20c901a7
DO
1469 global $tagtree;
1470 return traceTrail ($tagtree, $trail);
ba93bd98
DO
1471}
1472
1473// Return the list of missing implicit tags.
1474function getImplicitTags ($oldtags)
1475{
1476 $ret = array();
1477 $newtags = getTrailExpansion ($oldtags);
1478 foreach ($newtags as $newtag)
1479 {
1480 $already_exists = FALSE;
1481 foreach ($oldtags as $oldtag)
1482 if ($newtag['id'] == $oldtag['id'])
1483 {
1484 $already_exists = TRUE;
1485 break;
1486 }
1487 if ($already_exists)
1488 continue;
d6089951 1489 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
ba93bd98
DO
1490 }
1491 return $ret;
1492}
1493
ab379543
DO
1494// Minimize the trail: exclude all implicit tags and return the resulting trail.
1495function getExplicitTagsOnly ($trail, $tree = NULL)
1496{
20c901a7 1497 global $tagtree;
ab379543 1498 if ($tree === NULL)
20c901a7 1499 $tree = $tagtree;
ab379543
DO
1500 $ret = array();
1501 foreach ($tree as $taginfo)
1502 {
1503 if (isset ($taginfo['kids']))
1504 {
1505 $harvest = getExplicitTagsOnly ($trail, $taginfo['kids']);
1506 if (count ($harvest) > 0)
1507 {
1508 $ret = array_merge ($ret, $harvest);
1509 continue;
1510 }
1511 }
1512 // This tag isn't implicit, test is for being explicit.
1513 foreach ($trail as $testtag)
1514 if ($taginfo['id'] == $testtag['id'])
1515 {
1516 $ret[] = $testtag;
1517 break;
1518 }
1519 }
1520 return $ret;
1521}
1522
74ccacff
DO
1523// Maximize the trail: for each tag add all tags, for which it is direct or indirect parent.
1524// Unlike other functions, this one accepts and returns a list of integer tag IDs, not
1525// a list of tag structures.
1526function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1527{
20c901a7 1528 global $tagtree;
74ccacff 1529 if ($tree === NULL)
20c901a7 1530 $tree = $tagtree;
74ccacff
DO
1531 $getallkids = $getall;
1532 $ret = array();
1533 foreach ($tree as $taginfo)
1534 {
1535 foreach ($idlist as $test_id)
1536 if ($getall or $taginfo['id'] == $test_id)
1537 {
1538 $ret[] = $taginfo['id'];
1539 // Once matched node makes all sub-nodes match, but don't make
1540 // a mistake of matching every other node at the current level.
1541 $getallkids = TRUE;
1542 break;
1543 }
1544 if (isset ($taginfo['kids']))
1545 $ret = array_merge ($ret, complementByKids ($idlist, $taginfo['kids'], $getallkids));
1546 $getallkids = FALSE;
1547 }
1548 return $ret;
1549}
1550
2fb24351 1551function loadRackObjectAutoTags()
ba93bd98 1552{
2c6c7645 1553 assertUIntArg ('object_id', __FUNCTION__);
2fb24351
DO
1554 $object_id = $_REQUEST['object_id'];
1555 $oinfo = getObjectInfo ($object_id);
1556 $ret = array();
1557 $ret[] = array ('tag' => '$id_' . $_REQUEST['object_id']);
d817ba03 1558 $ret[] = array ('tag' => '$any_object');
2fb24351
DO
1559 return $ret;
1560}
1561
f9bc186f
DO
1562function loadIPv4PrefixAutoTags()
1563{
2c6c7645 1564 assertUIntArg ('id', __FUNCTION__);
41bd8c87 1565 $subnet = getIPRange ($_REQUEST['id']);
f9bc186f
DO
1566 $ret = array();
1567 $ret[] = array ('tag' => '$id_' . $_REQUEST['id']);
41bd8c87 1568 $ret[] = array ('tag' => '$ipv4net-' . str_replace ('.', '-', $subnet['ip']) . '-' . $subnet['mask']);
d817ba03
DO
1569 // FIXME: find and list tags for all parent networks
1570 $ret[] = array ('tag' => '$any_ipv4net');
1571 $ret[] = array ('tag' => '$any_net');
41bd8c87
DO
1572 return $ret;
1573}
1574
1575function loadRackAutoTags()
1576{
2c6c7645 1577 assertUIntArg ('rack_id', __FUNCTION__);
41bd8c87
DO
1578 $ret = array();
1579 $ret[] = array ('tag' => '$id_' . $_REQUEST['rack_id']);
d817ba03
DO
1580 $ret[] = array ('tag' => '$any_rack');
1581 return $ret;
1582}
1583
1584function loadIPv4AddressAutoTags()
1585{
2c6c7645 1586 assertIPv4Arg ('ip', __FUNCTION__);
d817ba03
DO
1587 $ret = array();
1588 $ret[] = array ('tag' => '$ipv4net-' . str_replace ('.', '-', $subnet['ip']) . '-32');
1589 // FIXME: find and list tags for all parent networks
1590 $ret[] = array ('tag' => '$any_ipv4net');
1591 $ret[] = array ('tag' => '$any_net');
1592 return $ret;
1593}
1594
1595function loadIPv4VSAutoTags()
1596{
2c6c7645 1597 assertUIntArg ('id', __FUNCTION__);
d817ba03
DO
1598 $ret = array();
1599 $ret[] = array ('tag' => '$id_' . $_REQUEST['id']);
1600 $ret[] = array ('tag' => '$any_ipv4vs');
1601 $ret[] = array ('tag' => '$any_vs');
1602 return $ret;
1603}
1604
1605function loadIPv4RSPoolAutoTags()
1606{
2c6c7645 1607 assertUIntArg ('pool_id', __FUNCTION__);
d817ba03 1608 $ret = array();
6aff02cf 1609 $ret[] = array ('tag' => '$id_' . $_REQUEST['pool_id']);
d817ba03
DO
1610 $ret[] = array ('tag' => '$any_ipv4rspool');
1611 $ret[] = array ('tag' => '$any_rspool');
f9bc186f
DO
1612 return $ret;
1613}
1614
2fb24351
DO
1615function getGlobalAutoTags()
1616{
1617 global $remote_username, $accounts;
1618 $ret = array();
1619 $user_id = 0;
1620 foreach ($accounts as $a)
1621 if ($a['user_name'] == $remote_username)
1622 {
1623 $user_id = $a['user_id'];
1624 break;
1625 }
1626 $ret[] = array ('tag' => '$username_' . $remote_username);
1627 $ret[] = array ('tag' => '$userid_' . $user_id);
1628 return $ret;
ba93bd98
DO
1629}
1630
ab379543
DO
1631// Build a tag trail from supplied tag id list and return it.
1632function buildTrailFromIds ($tagidlist)
1633{
20c901a7 1634 global $taglist;
ab379543
DO
1635 $ret = array();
1636 foreach ($tagidlist as $tag_id)
1637 if (isset ($taglist[$tag_id]))
1638 $ret[] = $taglist[$tag_id];
1639 return $ret;
1640}
1641
7cc02fc1
DO
1642// Process a given tag tree and return only meaningful branches. The resulting
1643// (sub)tree will have refcnt leaves on every last branch.
1644function getObjectiveTagTree ($tree, $realm)
1645{
1646 $ret = array();
1647 foreach ($tree as $taginfo)
1648 {
1649 $subsearch = array();
1650 $pick = FALSE;
1651 if (count ($taginfo['kids']))
1652 {
1653 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1654 $pick = count ($subsearch) > 0;
1655 }
5bdc04ec 1656 if (isset ($taginfo['refcnt'][$realm]))
7cc02fc1
DO
1657 $pick = TRUE;
1658 if (!$pick)
1659 continue;
1660 $ret[] = array
1661 (
1662 'id' => $taginfo['id'],
1663 'tag' => $taginfo['tag'],
1664 'parent_id' => $taginfo['parent_id'],
1665 'refcnt' => $taginfo['refcnt'],
1666 'kids' => $subsearch
1667 );
1668 }
1669 return $ret;
1670}
1671
a0d54e7e 1672function getTagFilter ()
7cc02fc1 1673{
a0d54e7e 1674 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
7cc02fc1
DO
1675}
1676
a0d54e7e 1677function getTagFilterStr ($tagfilter = array())
932cf41f 1678{
a0d54e7e 1679 $ret = '';
a0d54e7e
DO
1680 foreach (getExplicitTagsOnly (buildTrailFromIds ($tagfilter)) as $taginfo)
1681 $ret .= "&tagfilter[]=" . $taginfo['id'];
1682 return $ret;
932cf41f 1683}
a0d54e7e 1684
e673ee24 1685?>