r1809 + finally stick with sorting stickers one way
[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
2dee289e 377function addRange ($range='', $name='', $is_bcast = FALSE)
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
423 global $dbxlink;
424
425 $result = $dbxlink->query ($query);
426
427 while ($row = $result->fetch (PDO::FETCH_ASSOC))
428 {
429 $otherip = $row['ip'];
430 $othermask = binMaskFromDec($row['mask']);
431// 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";
432// 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";
433// echo "\n";
434// flush();
435 if (($otherip & $othermask) == ($ipL & $othermask))
436 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
437 if (($otherip & $binmask) == ($ipL & $binmask))
438 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
439 }
440 $result->closeCursor();
441 $query =
442 "insert into IPRanges set ip=".sprintf('%u', $ipL).", mask='$maskL', name='$name'";
443 $result = $dbxlink->exec ($query);
2dee289e
DO
444
445 if ($is_bcast and $maskL < 31)
446 {
447 $network_addr = long2ip ($ipL);
448 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
449 updateAddress ($network_addr, 'network', 'yes');
450 updateAddress ($broadcast_addr, 'broadcast', 'yes');
451 }
e673ee24
DO
452 return '';
453}
454
455function getIPRange ($id = 0)
456{
457 global $dbxlink;
458 $query =
459 "select ".
460 "id as IPRanges_id, ".
461 "INET_NTOA(ip) as IPRanges_ip, ".
e673ee24
DO
462 "mask as IPRanges_mask, ".
463 "name as IPRanges_name ".
464 "from IPRanges ".
465 "where id = '$id'";
602663f4 466 $result = useSelectBlade ($query);
5c43a978 467 $ret = array();
55cc3e4e
DO
468 $row = $result->fetch (PDO::FETCH_ASSOC);
469 if ($row == NULL)
470 return $ret;
471 $ret['id'] = $row['IPRanges_id'];
472 $ret['ip'] = $row['IPRanges_ip'];
7e039e88 473 $ret['ip_bin'] = ip2long ($row['IPRanges_ip']);
55cc3e4e
DO
474 $ret['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
475 $ret['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
476 $ret['name'] = $row['IPRanges_name'];
477 $ret['mask'] = $row['IPRanges_mask'];
478 $ret['addrlist'] = array();
55cc3e4e 479 $result->closeCursor();
602663f4 480 unset ($result);
7e039e88
DO
481 // We risk losing some significant bits in an unsigned 32bit integer,
482 // unless it is converted to a string.
483 $db_first = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']) . "'";
484 $db_last = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv'])) . "'";
5c43a978
DO
485
486 // Don't try to build up the whole structure in a single pass. Request
487 // the list of user comments and reservations and merge allocations in
488 // at a latter point.
55cc3e4e 489 $query =
7e039e88
DO
490 "select INET_NTOA(ip) as ip, name, reserved from IPAddress " .
491 "where ip between ${db_first} and ${db_last} " .
5c43a978 492 "and (reserved = 'yes' or name != '')";
602663f4
DO
493 $result = $dbxlink->query ($query);
494 while ($row = $result->fetch (PDO::FETCH_ASSOC))
55cc3e4e 495 {
7e039e88
DO
496 $ip_bin = ip2long ($row['ip']);
497 $ret['addrlist'][$ip_bin] = $row;
5c43a978
DO
498 $tmp = array();
499 foreach (array ('ip', 'name', 'reserved') as $cname)
500 $tmp[$cname] = $row[$cname];
501 $tmp['references'] = array();
602663f4
DO
502 $tmp['lbrefs'] = array();
503 $tmp['rsrefs'] = array();
7e039e88 504 $ret['addrlist'][$ip_bin] = $tmp;
5c43a978 505 }
602663f4
DO
506 $result->closeCursor();
507 unset ($result);
e673ee24 508
5c43a978 509 $query =
dda31a62
DO
510 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
511 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
512 "dict_value as objtype_name from " .
5c43a978 513 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
dda31a62 514 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
7e039e88 515 "where ip between ${db_first} and ${db_last} " .
dda31a62 516 "and chapter_name = 'RackObjectType'" .
5c43a978 517 "order by ipb.type, object_name";
602663f4
DO
518 $result = useSelectBlade ($query);
519 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5c43a978 520 {
7e039e88
DO
521 $ip_bin = ip2long ($row['ip']);
522 if (!isset ($ret['addrlist'][$ip_bin]))
55cc3e4e 523 {
7e039e88
DO
524 $ret['addrlist'][$ip_bin] = array();
525 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
526 $ret['addrlist'][$ip_bin]['name'] = '';
527 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
528 $ret['addrlist'][$ip_bin]['references'] = array();
602663f4
DO
529 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
530 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
e673ee24 531 }
5c43a978 532 $tmp = array();
dda31a62 533 foreach (array ('object_id', 'type', 'name') as $cname)
5c43a978 534 $tmp[$cname] = $row[$cname];
dda31a62
DO
535 $quasiobject['name'] = $row['object_name'];
536 $quasiobject['objtype_id'] = $row['objtype_id'];
537 $quasiobject['objtype_name'] = $row['objtype_name'];
538 $tmp['object_name'] = displayedName ($quasiobject);
7e039e88 539 $ret['addrlist'][$ip_bin]['references'][] = $tmp;
e673ee24 540 }
602663f4
DO
541 $result->closeCursor();
542 unset ($result);
543
544 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, " .
545 "object_id, objtype_id, ro.name, dict_value as objtype_name from " .
546 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
547 "inner join RackObject as ro on lb.object_id = ro.id " .
548 "left join Dictionary on objtype_id=dict_key " .
549 "natural join Chapter " .
550 "where vip between ${db_first} and ${db_last} " .
551 "and chapter_name = 'RackObjectType'" .
552 "order by vport, proto, ro.name, object_id";
553 $result = useSelectBlade ($query);
554 while ($row = $result->fetch (PDO::FETCH_ASSOC))
555 {
556 $ip_bin = ip2long ($row['ip']);
557 if (!isset ($ret['addrlist'][$ip_bin]))
558 {
559 $ret['addrlist'][$ip_bin] = array();
560 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
561 $ret['addrlist'][$ip_bin]['name'] = '';
562 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
563 $ret['addrlist'][$ip_bin]['references'] = array();
564 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
565 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
566 }
567 $tmp = $qbject = array();
568 foreach (array ('object_id', 'vport', 'proto', 'vs_id') as $cname)
569 $tmp[$cname] = $row[$cname];
570 foreach (array ('name', 'objtype_id', 'objtype_name') as $cname)
571 $qobject[$cname] = $row[$cname];
572 $tmp['object_name'] = displayedName ($qobject);
573 $ret['addrlist'][$ip_bin]['lbrefs'][] = $tmp;
574 }
575 $result->closeCursor();
576 unset ($result);
577
578 $query = "select inet_ntoa(rsip) as ip, rsport, rspool_id, rsp.name as rspool_name from " .
579 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
580 "where rsip between ${db_first} and ${db_last} " .
581 "order by ip, rsport, rspool_id";
582 $result = useSelectBlade ($query);
583 while ($row = $result->fetch (PDO::FETCH_ASSOC))
584 {
585 $ip_bin = ip2long ($row['ip']);
586 if (!isset ($ret['addrlist'][$ip_bin]))
587 {
588 $ret['addrlist'][$ip_bin] = array();
589 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
590 $ret['addrlist'][$ip_bin]['name'] = '';
591 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
592 $ret['addrlist'][$ip_bin]['references'] = array();
593 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
594 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
595 }
596 $tmp = array();
597 foreach (array ('rspool_id', 'rsport', 'rspool_name') as $cname)
598 $tmp[$cname] = $row[$cname];
599 $ret['addrlist'][$ip_bin]['rsrefs'][] = $tmp;
600 }
5c43a978 601
e673ee24
DO
602 return $ret;
603}
604
dda31a62
DO
605// Don't require any records in IPAddress, but if there is one,
606// merge the data between getting allocation list. Collect enough data
607// to call displayedName() ourselves.
e673ee24
DO
608function getIPAddress ($ip=0)
609{
610 $ret = array();
e673ee24 611 $ret['bonds'] = array();
59bebe2b 612 // FIXME: below two aren't neither filled in with data nor rendered (ticket:23)
e673ee24
DO
613 $ret['outpf'] = array();
614 $ret['inpf'] = array();
59bebe2b
DO
615 $ret['vslist'] = array();
616 $ret['rslist'] = array();
e673ee24 617 $ret['exists'] = 0;
dda31a62 618 $ret['name'] = '';
e673ee24
DO
619 $ret['reserved'] = 'no';
620 global $dbxlink;
59bebe2b 621 $query =
e673ee24 622 "select ".
dda31a62 623 "name, reserved ".
e673ee24 624 "from IPAddress ".
dda31a62 625 "where ip = INET_ATON('$ip') and (reserved = 'yes' or name != '')";
59bebe2b
DO
626 $result = $dbxlink->query ($query);
627 if ($result == NULL)
628 {
629 showError ('Query #1 failed', __FUNCTION__);
e673ee24 630 return NULL;
59bebe2b
DO
631 }
632 if ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 633 {
959c4f4c 634 $ret['exists'] = 1;
959c4f4c
DO
635 $ret['name'] = $row['name'];
636 $ret['reserved'] = $row['reserved'];
e673ee24 637 }
59bebe2b
DO
638 $result->closeCursor();
639 unset ($result);
e673ee24 640
59bebe2b 641 $query =
dda31a62
DO
642 "select ".
643 "IPBonds.object_id as object_id, ".
644 "IPBonds.name as name, ".
645 "IPBonds.type as type, ".
646 "objtype_id, dict_value as objtype_name, " .
647 "RackObject.name as object_name ".
648 "from IPBonds join RackObject on IPBonds.object_id=RackObject.id ".
649 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
650 "where IPBonds.ip=INET_ATON('$ip') ".
651 "and chapter_name = 'RackObjectType' " .
652 "order by RackObject.id, IPBonds.name";
59bebe2b 653 $result = $dbxlink->query ($query);
dda31a62 654 $count=0;
59bebe2b 655 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 656 {
dda31a62
DO
657 $ret['bonds'][$count]['object_id'] = $row['object_id'];
658 $ret['bonds'][$count]['name'] = $row['name'];
659 $ret['bonds'][$count]['type'] = $row['type'];
660 $qo = array();
661 $qo['name'] = $row['object_name'];
662 $qo['objtype_id'] = $row['objtype_id'];
663 $qo['objtype_name'] = $row['objtype_name'];
664 $ret['bonds'][$count]['object_name'] = displayedName ($qo);
665 $count++;
666 $ret['exists'] = 1;
e673ee24 667 }
59bebe2b
DO
668 $result->closeCursor();
669 unset ($result);
670
5fe1ed76 671 $query = "select id, vport, proto, name from IPVirtualService where vip = inet_aton('${ip}')";
59bebe2b
DO
672 $result = $dbxlink->query ($query);
673 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5fe1ed76
DO
674 {
675 $new = $row;
676 $new['vip'] = $ip;
677 $ret['vslist'][] = $new;
678 }
679 $result->closeCursor();
680 unset ($result);
681
682 $query = "select inservice, rsport, IPRSPool.id as pool_id, IPRSPool.name as poolname from " .
683 "IPRealServer inner join IPRSPool on rspool_id = IPRSPool.id " .
684 "where rsip = inet_aton('${ip}')";
685 $result = $dbxlink->query ($query);
686 while ($row = $result->fetch (PDO::FETCH_ASSOC))
687 {
688 $new = $row;
689 $new['rsip'] = $ip;
690 $ret['rslist'][] = $new;
691 }
59bebe2b
DO
692 $result->closeCursor();
693 unset ($result);
e673ee24
DO
694
695 return $ret;
696}
697
698function bindIpToObject ($ip='', $object_id=0, $name='', $type='')
699{
700 global $dbxlink;
701
702 $range = getRangeByIp($ip);
e673ee24
DO
703 if (!$range)
704 return 'Non-existant ip address. Try adding IP range first';
705
20a92aa2
DO
706 $result = useInsertBlade
707 (
708 'IPBonds',
709 array
710 (
dda31a62 711 'ip' => "INET_ATON('$ip')",
20a92aa2
DO
712 'object_id' => "'${object_id}'",
713 'name' => "'${name}'",
714 'type' => "'${type}'"
715 )
716 );
717 return $result ? '' : 'useInsertBlade() failed in bindIpToObject()';
e673ee24
DO
718}
719
720// This function looks up 'has_problems' flag for 'T' atoms
721// and modifies 'hl' key. May be, this should be better done
722// in getRackData(). We don't honour 'skipped' key, because
723// the function is also used for thumb creation.
724function markupObjectProblems (&$rackData)
725{
726 for ($i = $rackData['height']; $i > 0; $i--)
727 for ($locidx = 0; $locidx < 3; $locidx++)
728 if ($rackData[$i][$locidx]['state'] == 'T')
729 {
730 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
731 if ($object['has_problems'] == 'yes')
732 {
733 // Object can be already highlighted.
734 if (isset ($rackData[$i][$locidx]['hl']))
735 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
736 else
737 $rackData[$i][$locidx]['hl'] = 'w';
738 }
739 }
740}
741
742function search_cmpObj ($a, $b)
743{
744 return ($a['score'] > $b['score'] ? -1 : 1);
745}
746
747// This function performs search and then calculates score for each result.
748// Given previous search results in $objects argument, it adds new results
749// to the array and updates score for existing results, if it is greater than
750// existing score.
751function mergeSearchResults (&$objects, $terms, $fieldname)
752{
753 global $dbxlink;
754 $query =
755 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
756 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
757 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
758 $count = 0;
759 foreach (explode (' ', $terms) as $term)
760 {
761 if ($count) $query .= ' or ';
762 $query .= "${fieldname} like '%$term%'";
763 $count++;
764 }
765 $query .= "";
766 $result = $dbxlink->query($query);
767 if ($result == NULL)
768 {
61e269b5 769 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
770 return NULL;
771 }
772// FIXME: this dead call was executed 4 times per 1 object search!
773// $typeList = getObjectTypeList();
774 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
775 while ($row = $result->fetch(PDO::FETCH_ASSOC))
776 {
777 foreach ($clist as $cname)
778 $object[$cname] = $row[$cname];
779 $object['score'] = 0;
780 $object['dname'] = displayedName ($object);
781 unset ($object['objtype_id']);
782 foreach (explode (' ', $terms) as $term)
783 if (strstr ($object['name'], $term))
784 $object['score'] += 1;
785 unset ($object['name']);
786 if (!isset ($objects[$row['id']]))
787 $objects[$row['id']] = $object;
788 elseif ($objects[$row['id']]['score'] < $object['score'])
789 $objects[$row['id']]['score'] = $object['score'];
790 }
791 return $objects;
792}
793
794function getSearchResults ($terms)
795{
796 $objects = array();
797 mergeSearchResults ($objects, $terms, 'name');
798 mergeSearchResults ($objects, $terms, 'label');
799 mergeSearchResults ($objects, $terms, 'asset_no');
800 mergeSearchResults ($objects, $terms, 'barcode');
801 if (count ($objects) == 1)
802 usort ($objects, 'search_cmpObj');
803 return $objects;
804}
805
806// This function removes all colons and dots from a string.
807function l2addressForDatabase ($string)
808{
809 if (empty ($string))
810 return 'NULL';
811 $pieces = explode (':', $string);
812 // This workaround is for SunOS ifconfig.
813 foreach ($pieces as &$byte)
814 if (strlen ($byte) == 1)
815 $byte = '0' . $byte;
816 // And this workaround is for PHP.
817 unset ($byte);
818 $string = implode ('', $pieces);
819 $pieces = explode ('.', $string);
820 $string = implode ('', $pieces);
821 $string = strtoupper ($string);
822 return "'$string'";
823}
824
825function l2addressFromDatabase ($string)
826{
827 switch (strlen ($string))
828 {
829 case 12: // Ethernet
830 case 16: // FireWire
831 $ret = implode (':', str_split ($string, 2));
832 break;
833 default:
834 $ret = $string;
835 break;
836 }
837 return $ret;
838}
839
840// The following 2 functions return previous and next rack IDs for
841// a given rack ID. The order of racks is the same as in renderRackspace()
842// or renderRow().
843function getPrevIDforRack ($row_id = 0, $rack_id = 0)
844{
845 if ($row_id <= 0 or $rack_id <= 0)
846 {
61e269b5 847 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
848 return NULL;
849 }
850 $rackList = getRacksForRow ($row_id);
851 doubleLink ($rackList);
852 if (isset ($rackList[$rack_id]['prev_key']))
853 return $rackList[$rack_id]['prev_key'];
854 return NULL;
855}
856
857function getNextIDforRack ($row_id = 0, $rack_id = 0)
858{
859 if ($row_id <= 0 or $rack_id <= 0)
860 {
61e269b5 861 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
862 return NULL;
863 }
864 $rackList = getRacksForRow ($row_id);
865 doubleLink ($rackList);
866 if (isset ($rackList[$rack_id]['next_key']))
867 return $rackList[$rack_id]['next_key'];
868 return NULL;
869}
870
871// This function finds previous and next array keys for each array key and
872// modifies its argument accordingly.
873function doubleLink (&$array)
874{
875 $prev_key = NULL;
876 foreach (array_keys ($array) as $key)
877 {
878 if ($prev_key)
879 {
880 $array[$key]['prev_key'] = $prev_key;
881 $array[$prev_key]['next_key'] = $key;
882 }
883 $prev_key = $key;
884 }
885}
886
887// After applying usort() to a rack list we will lose original array keys.
888// This function restores the keys so they are equal to rack IDs.
889function restoreRackIDs ($racks)
890{
891 $ret = array();
892 foreach ($racks as $rack)
893 $ret[$rack['id']] = $rack;
894 return $ret;
895}
896
897function sortTokenize ($a, $b)
898{
899 $aold='';
900 while ($a != $aold)
901 {
902 $aold=$a;
903 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
904 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
905 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
906 }
907
908 $bold='';
909 while ($b != $bold)
910 {
911 $bold=$b;
912 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
913 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
914 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
915 }
916
917
918
919 $ar = explode(' ', $a);
920 $br = explode(' ', $b);
921 for ($i=0; $i<count($ar) && $i<count($br); $i++)
922 {
923 $ret = 0;
924 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
925 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
926 else
927 $ret = strcasecmp($ar[$i], $br[$i]);
928 if ($ret != 0)
929 return $ret;
930 }
931 if ($i<count($ar))
932 return 1;
933 if ($i<count($br))
934 return -1;
935 return 0;
936}
937
938function sortByName ($a, $b)
939{
940 return sortTokenize($a['name'], $b['name']);
941}
942
6a3a37b2
DO
943function sortRacks ($a, $b)
944{
945 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
946}
947
e673ee24
DO
948function eq ($a, $b)
949{
950 return $a==$b;
951}
952
953function neq ($a, $b)
954{
955 return $a!=$b;
956}
957
958function countRefsOfType ($refs, $type, $eq)
959{
960 $count=0;
961 foreach ($refs as $ref)
962 {
963 if ($eq($ref['type'], $type))
964 $count++;
965 }
966 return $count;
967}
968
969function sortEmptyPorts ($a, $b)
970{
971 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
972 if ($objname_cmp == 0)
973 {
974 return sortTokenize($a['Port_name'], $b['Port_name']);
975 }
976 return $objname_cmp;
977}
978
979function sortObjectAddressesAndNames ($a, $b)
980{
981 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
982 if ($objname_cmp == 0)
983 {
79f22c3d
DO
984 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
985 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
986 $objname_cmp = sortTokenize($name_a, $name_b);
e673ee24 987 if ($objname_cmp == 0)
e673ee24 988 sortTokenize($a['ip'], $b['ip']);
e673ee24
DO
989 return $objname_cmp;
990 }
991 return $objname_cmp;
992}
993
994
995
996function sortAddresses ($a, $b)
997{
998 $name_cmp = sortTokenize($a['name'], $b['name']);
999 if ($name_cmp == 0)
1000 {
1001 return sortTokenize($a['ip'], $b['ip']);
1002 }
1003 return $name_cmp;
1004}
1005
1006// This function expands port compat list into a matrix.
1007function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
1008{
1009 $matrix = array();
1010 // Create type matrix and markup compatible types.
1011 foreach (array_keys ($portTypeList) as $type1)
1012 foreach (array_keys ($portTypeList) as $type2)
1013 $matrix[$type1][$type2] = FALSE;
1014 foreach ($portCompatList as $pair)
1015 $matrix[$pair['type1']][$pair['type2']] = TRUE;
1016 return $matrix;
1017}
1018
1019function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
1020{
1021 global $dbxlink;
1022
1023 $range = getRangeByIp($localip);
1024 if (!$range)
1025 return "$localip: Non existant ip";
1026
1027 $range = getRangeByIp($remoteip);
1028 if (!$range)
1029 return "$remoteip: Non existant ip";
1030
1031 if ( ($localport <= 0) or ($localport >= 65536) )
1032 return "$localport: invaild port";
1033
1034 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
1035 return "$remoteport: invaild port";
1036
1037 $query =
1038 "insert into PortForwarding set object_id='$object_id', localip=INET_ATON('$localip'), remoteip=INET_ATON('$remoteip'), localport='$localport', remoteport='$remoteport', proto='$proto', description='$description'";
1039 $result = $dbxlink->exec ($query);
1040
1041 return '';
1042}
1043
1044function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
1045{
1046 global $dbxlink;
1047
1048 $query =
1049 "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'";
1050 $result = $dbxlink->exec ($query);
1051 return '';
1052}
1053
1054function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
1055{
1056 global $dbxlink;
1057
1058 $query =
1059 "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'";
1060 $result = $dbxlink->exec ($query);
1061 return '';
1062}
1063
1064function getObjectForwards($object_id)
1065{
1066 global $dbxlink;
1067
1068 $ret = array();
1069 $ret['out'] = array();
1070 $ret['in'] = array();
1071 $query =
1072 "select ".
1073 "dict_value as proto, ".
1074 "proto as proto_bin, ".
1075 "INET_NTOA(localip) as localip, ".
1076 "localport, ".
1077 "INET_NTOA(remoteip) as remoteip, ".
1078 "remoteport, ".
f28fbe8b
DO
1079 "ipa1.name as local_addr_name, " .
1080 "ipa2.name as remote_addr_name, " .
e673ee24
DO
1081 "description ".
1082 "from PortForwarding inner join Dictionary on proto = dict_key natural join Chapter ".
f28fbe8b
DO
1083 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
1084 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
e673ee24
DO
1085 "where object_id='$object_id' and chapter_name = 'Protocols' ".
1086 "order by localip, localport, proto, remoteip, remoteport";
1087 $result2 = $dbxlink->query ($query);
1088 $count=0;
1089 while ($row = $result2->fetch (PDO::FETCH_ASSOC))
1090 {
f28fbe8b
DO
1091 foreach (array ('proto', 'proto_bin', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
1092 $ret['out'][$count][$cname] = $row[$cname];
e673ee24
DO
1093 $count++;
1094 }
1095 $result2->closeCursor();
1096
1097 $query =
1098 "select ".
1099 "dict_value as proto, ".
1100 "proto as proto_bin, ".
1101 "INET_NTOA(localip) as localip, ".
1102 "localport, ".
1103 "INET_NTOA(remoteip) as remoteip, ".
1104 "remoteport, ".
1105 "PortForwarding.object_id as object_id, ".
1106 "RackObject.name as object_name, ".
1107 "description ".
f28fbe8b 1108 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) inner join Dictionary on proto = dict_key natural join Chapter ".
e673ee24
DO
1109 "where IPBonds.object_id='$object_id' and chapter_name = 'Protocols' ".
1110 "order by remoteip, remoteport, proto, localip, localport";
1111 $result3 = $dbxlink->query ($query);
1112 $count=0;
1113 while ($row = $result3->fetch (PDO::FETCH_ASSOC))
1114 {
603ad85f 1115 foreach (array ('proto', 'proto_bin', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
f28fbe8b 1116 $ret['in'][$count][$cname] = $row[$cname];
e673ee24
DO
1117 $count++;
1118 }
1119 $result3->closeCursor();
1120
1121 return $ret;
1122}
1123
c31cd72c 1124// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
1125// if FQDN is set. The next choice is object's common name, if it looks like a
1126// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 1127// object is returned (which may appear 0 and more elements long).
f321b50a 1128function findAllEndpoints ($object_id, $fallback = '')
c31cd72c
DO
1129{
1130 $values = getAttrValues ($object_id);
1131 foreach ($values as $record)
f321b50a 1132 if ($record['name'] == 'FQDN' && !empty ($record['value']))
c31cd72c
DO
1133 return array ($record['value']);
1134 $addresses = getObjectAddresses ($object_id);
1135 $regular = array();
1136 foreach ($addresses as $idx => $address)
1137 if ($address['type'] == 'regular')
fa8112d1 1138 $regular[] = $address['ip'];
f321b50a
DO
1139 if (!count ($regular) && !empty ($fallback))
1140 return array ($fallback);
c31cd72c
DO
1141 return $regular;
1142}
1143
83ba6670
DO
1144// Some records in the dictionary may be written as plain text or as Wiki
1145// link in the following syntax:
1146// 1. word
1147// 2. [[word URL]] // FIXME: this isn't working
1148// 3. [[word word word | URL]]
1149// This function parses the line and returns text suitable for either A
1150// (rendering <A HREF>) or O (for <OPTION>).
24cbe8af 1151function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
83ba6670 1152{
010231c2 1153 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af
DO
1154 {
1155 if ($strip_optgroup)
1156 return ereg_replace ('^.+\^', '', $line);
1157 else
1158 return $line;
1159 }
010231c2
DO
1160 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
1161 $s = explode ('|', $line);
83ba6670 1162 $o_value = trim ($s[0]);
24cbe8af
DO
1163 if ($strip_optgroup)
1164 $o_value = ereg_replace ('^.+\^', '', $o_value);
83ba6670
DO
1165 $a_value = trim ($s[1]);
1166 if ($which == 'a')
010231c2 1167 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
1168 if ($which == 'o')
1169 return $o_value;
1170}
1171
2de490b7
DO
1172function buildVServiceName ($vsinfo = NULL)
1173{
1174 if ($vsinfo == NULL)
1175 {
1176 showError ('NULL argument', __FUNCTION__);
1177 return NULL;
1178 }
8d790216 1179 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
2de490b7
DO
1180}
1181
177b1e9b
DO
1182// rackspace usage for a single rack
1183// (T + W + U) / (height * 3 - A)
11df133a 1184function getRSUforRack ($data = NULL)
177b1e9b 1185{
11df133a 1186 if ($data == NULL)
177b1e9b
DO
1187 {
1188 showError ('Invalid argument', __FUNCTION__);
1189 return NULL;
1190 }
6ffba290 1191 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
1192 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1193 for ($locidx = 0; $locidx < 3; $locidx++)
1194 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 1195 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
1196}
1197
11df133a
DO
1198// Same for row.
1199function getRSUforRackRow ($rowData = NULL)
1200{
bb26a59e 1201 if ($rowData === NULL)
11df133a
DO
1202 {
1203 showError ('Invalid argument', __FUNCTION__);
1204 return NULL;
1205 }
bb26a59e
DO
1206 if (!count ($rowData))
1207 return 0;
11df133a 1208 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 1209 $total_height = 0;
dfa3c075
DO
1210 foreach (array_keys ($rowData) as $rack_id)
1211 {
1212 $data = getRackData ($rack_id);
1213 $total_height += $data['height'];
11df133a
DO
1214 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1215 for ($locidx = 0; $locidx < 3; $locidx++)
1216 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
1217 }
1218 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
1219}
1220
f1a0477d
DO
1221function getObjectCount ($rackData)
1222{
1223 $objects = array();
1224 for ($i = $rackData['height']; $i > 0; $i--)
1225 for ($locidx = 0; $locidx < 3; $locidx++)
1226 if
1227 (
1228 $rackData[$i][$locidx]['state'] == 'T' and
1229 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
1230 )
1231 $objects[] = $rackData[$i][$locidx]['object_id'];
1232 return count ($objects);
1233}
1234
9af110b4
DO
1235// Perform substitutions and return resulting string
1236function apply_macros ($macros, $subject)
1237{
1238 $ret = $subject;
1239 foreach ($macros as $search => $replace)
1240 $ret = str_replace ($search, $replace, $ret);
1241 return $ret;
1242}
1243
1244// Make sure the string is always wrapped with LF characters
1245function lf_wrap ($str)
1246{
1247 $ret = trim ($str, "\r\n");
1248 if (!empty ($ret))
1249 $ret .= "\n";
1250 return $ret;
1251}
1252
e6e7d8b3
DO
1253// Adopted from Mantis BTS code.
1254function string_insert_hrefs ($s)
1255{
1256 if (getConfigVar ('DETECT_URLS') != 'yes')
1257 return $s;
1258 # Find any URL in a string and replace it by a clickable link
1259 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
1260 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
1261 $s);
1262 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
1263 '<a href="mailto:\0">\0</a>',
1264 $s);
1265 return $s;
1266}
1267
1268// Idem.
1269function email_regex_simple ()
1270{
1271 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
1272 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
1273}
1274
118e4c38
DO
1275// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
1276// for the requested object_type_id.
1277function getAutoPorts ($type_id)
1278{
1279 $ret = array();
1280 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
1281 foreach ($typemap as $equation)
1282 {
1283 $tmp = explode ('=', $equation);
1284 if (count ($tmp) != 2)
1285 continue;
1286 $objtype_id = $tmp[0];
1287 if ($objtype_id != $type_id)
1288 continue;
1289 $portlist = $tmp[1];
1290 foreach (explode ('+', $portlist) as $product)
1291 {
1292 $tmp = explode ('*', $product);
1293 if (count ($tmp) != 3)
1294 continue;
1295 $nports = $tmp[0];
1296 $port_type = $tmp[1];
1297 $format = $tmp[2];
1298 for ($i = 0; $i < $nports; $i++)
1299 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
1300 }
1301 }
1302 return $ret;
1303}
1304
9dfd4cc9
DO
1305// Find if a particular tag id exists on the tree, then attach the
1306// given child tag to it. If the parent tag doesn't exist, return FALSE.
1307function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
1308{
1309 foreach ($tree as $tagid => $taginfo)
1310 {
1311 if ($tagid == $parent_id)
1312 {
1313 $tree[$tagid]['kids'][$child_id] = $child_info;
1314 return TRUE;
1315 }
1316 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
1317 return TRUE;
1318 }
1319 return FALSE;
1320}
1321
1322// Build a tree from the tag list and return it.
1323function getTagTree ()
1324{
1325 $tagtree = array();
1326 $taglist = getTagList();
1327 while (count ($taglist) > 0)
1328 {
1329 $picked = FALSE;
1330 foreach ($taglist as $tagid => $taginfo)
1331 {
1332 $taginfo['kids'] = array();
1333 if ($taginfo['parent_id'] == NULL)
1334 {
1335 $tagtree[$tagid] = $taginfo;
1336 $picked = TRUE;
1337 unset ($taglist[$tagid]);
1338 }
1339 elseif (attachChildTag ($tagtree, $taginfo['parent_id'], $tagid, $taginfo))
1340 {
1341 $picked = TRUE;
1342 unset ($taglist[$tagid]);
1343 }
1344 }
1345 if (!$picked) // Only orphaned items on the list.
1346 break;
1347 }
1348 return $tagtree;
1349}
1350
ba93bd98
DO
1351function serializeTags ($trail)
1352{
1353 $comma = '';
1354 $ret = '';
1355 foreach ($trail as $taginfo)
1356 {
1357 $ret .= $comma . $taginfo['tag'];
1358 $comma = ', ';
1359 }
1360 return $ret;
1361}
1362
ab379543 1363// a helper for getTrailExpansion()
ba93bd98
DO
1364function traceTrail ($tree, $trail)
1365{
1366 // For each tag find its path from the root, then combine items
1367 // of all paths and add them to the trail, if they aren't there yet.
1368 $ret = array();
1369 foreach ($tree as $taginfo1)
1370 {
1371 $hit = FALSE;
1372 foreach ($trail as $taginfo2)
1373 if ($taginfo1['id'] == $taginfo2['id'])
1374 {
1375 $hit = TRUE;
1376 break;
1377 }
1378 if (count ($taginfo1['kids']) > 0)
1379 {
1380 $subsearch = traceTrail ($taginfo1['kids'], $trail);
1381 if (count ($subsearch))
1382 {
1383 $hit = TRUE;
1384 $ret = array_merge ($ret, $subsearch);
1385 }
1386 }
1387 if ($hit)
1388 $ret[] = $taginfo1;
1389 }
1390 return $ret;
1391}
1392
1393// For each tag add all its parent tags onto the list. Don't expect anything
1394// except user's tags on the trail.
1395function getTrailExpansion ($trail)
1396{
1397 $tree = getTagTree();
1398 return traceTrail ($tree, $trail);
1399}
1400
1401// Return the list of missing implicit tags.
1402function getImplicitTags ($oldtags)
1403{
1404 $ret = array();
1405 $newtags = getTrailExpansion ($oldtags);
1406 foreach ($newtags as $newtag)
1407 {
1408 $already_exists = FALSE;
1409 foreach ($oldtags as $oldtag)
1410 if ($newtag['id'] == $oldtag['id'])
1411 {
1412 $already_exists = TRUE;
1413 break;
1414 }
1415 if ($already_exists)
1416 continue;
1417 $ret[] = $newtag;
1418 }
1419 return $ret;
1420}
1421
ab379543
DO
1422// Minimize the trail: exclude all implicit tags and return the resulting trail.
1423function getExplicitTagsOnly ($trail, $tree = NULL)
1424{
1425 if ($tree === NULL)
1426 $tree = getTagTree();
1427 $ret = array();
1428 foreach ($tree as $taginfo)
1429 {
1430 if (isset ($taginfo['kids']))
1431 {
1432 $harvest = getExplicitTagsOnly ($trail, $taginfo['kids']);
1433 if (count ($harvest) > 0)
1434 {
1435 $ret = array_merge ($ret, $harvest);
1436 continue;
1437 }
1438 }
1439 // This tag isn't implicit, test is for being explicit.
1440 foreach ($trail as $testtag)
1441 if ($taginfo['id'] == $testtag['id'])
1442 {
1443 $ret[] = $testtag;
1444 break;
1445 }
1446 }
1447 return $ret;
1448}
1449
2fb24351 1450function loadRackObjectAutoTags()
ba93bd98 1451{
2fb24351
DO
1452 assertUIntArg ('object_id');
1453 $object_id = $_REQUEST['object_id'];
1454 $oinfo = getObjectInfo ($object_id);
1455 $ret = array();
1456 $ret[] = array ('tag' => '$id_' . $_REQUEST['object_id']);
1457 $ret[] = array ('tag' => '$allobjects');
1458 return $ret;
1459}
1460
1461function getGlobalAutoTags()
1462{
1463 global $remote_username, $accounts;
1464 $ret = array();
1465 $user_id = 0;
1466 foreach ($accounts as $a)
1467 if ($a['user_name'] == $remote_username)
1468 {
1469 $user_id = $a['user_id'];
1470 break;
1471 }
1472 $ret[] = array ('tag' => '$username_' . $remote_username);
1473 $ret[] = array ('tag' => '$userid_' . $user_id);
1474 return $ret;
ba93bd98
DO
1475}
1476
ab379543
DO
1477// Build a tag trail from supplied tag id list and return it.
1478function buildTrailFromIds ($tagidlist)
1479{
1480 $taglist = getTagList();
1481 $ret = array();
1482 foreach ($tagidlist as $tag_id)
1483 if (isset ($taglist[$tag_id]))
1484 $ret[] = $taglist[$tag_id];
1485 return $ret;
1486}
1487
e673ee24 1488?>