r1679 + fix typo
[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'";
466 $result = $dbxlink->query ($query);
467 if ($result == NULL)
e673ee24 468 return NULL;
5c43a978 469 $ret = array();
55cc3e4e
DO
470 $row = $result->fetch (PDO::FETCH_ASSOC);
471 if ($row == NULL)
472 return $ret;
473 $ret['id'] = $row['IPRanges_id'];
474 $ret['ip'] = $row['IPRanges_ip'];
7e039e88 475 $ret['ip_bin'] = ip2long ($row['IPRanges_ip']);
55cc3e4e
DO
476 $ret['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
477 $ret['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
478 $ret['name'] = $row['IPRanges_name'];
479 $ret['mask'] = $row['IPRanges_mask'];
480 $ret['addrlist'] = array();
55cc3e4e 481 $result->closeCursor();
7e039e88
DO
482 // We risk losing some significant bits in an unsigned 32bit integer,
483 // unless it is converted to a string.
484 $db_first = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']) . "'";
485 $db_last = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv'])) . "'";
5c43a978
DO
486
487 // Don't try to build up the whole structure in a single pass. Request
488 // the list of user comments and reservations and merge allocations in
489 // at a latter point.
55cc3e4e 490 $query =
7e039e88
DO
491 "select INET_NTOA(ip) as ip, name, reserved from IPAddress " .
492 "where ip between ${db_first} and ${db_last} " .
5c43a978
DO
493 "and (reserved = 'yes' or name != '')";
494 $ipa_res = $dbxlink->query ($query);
495 if ($ipa_res == NULL)
55cc3e4e 496 return $ret;
5c43a978 497 while ($row = $ipa_res->fetch (PDO::FETCH_ASSOC))
55cc3e4e 498 {
7e039e88
DO
499 $ip_bin = ip2long ($row['ip']);
500 $ret['addrlist'][$ip_bin] = $row;
5c43a978
DO
501 $tmp = array();
502 foreach (array ('ip', 'name', 'reserved') as $cname)
503 $tmp[$cname] = $row[$cname];
504 $tmp['references'] = array();
7e039e88 505 $ret['addrlist'][$ip_bin] = $tmp;
5c43a978
DO
506 }
507 $ipa_res->closeCursor();
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
DO
517 "order by ipb.type, object_name";
518 $ipb_res = $dbxlink->query ($query);
519 while ($row = $ipb_res->fetch (PDO::FETCH_ASSOC))
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();
e673ee24 529 }
5c43a978 530 $tmp = array();
dda31a62 531 foreach (array ('object_id', 'type', 'name') as $cname)
5c43a978 532 $tmp[$cname] = $row[$cname];
dda31a62
DO
533 $quasiobject['name'] = $row['object_name'];
534 $quasiobject['objtype_id'] = $row['objtype_id'];
535 $quasiobject['objtype_name'] = $row['objtype_name'];
536 $tmp['object_name'] = displayedName ($quasiobject);
7e039e88 537 $ret['addrlist'][$ip_bin]['references'][] = $tmp;
e673ee24 538 }
5c43a978
DO
539 $ipb_res->closeCursor();
540
e673ee24
DO
541 return $ret;
542}
543
dda31a62
DO
544// Don't require any records in IPAddress, but if there is one,
545// merge the data between getting allocation list. Collect enough data
546// to call displayedName() ourselves.
e673ee24
DO
547function getIPAddress ($ip=0)
548{
549 $ret = array();
e673ee24
DO
550 $ret['bonds'] = array();
551 $ret['outpf'] = array();
552 $ret['inpf'] = array();
553 $ret['exists'] = 0;
dda31a62 554 $ret['name'] = '';
e673ee24
DO
555 $ret['reserved'] = 'no';
556 global $dbxlink;
ebdce584 557 $query1 =
e673ee24 558 "select ".
dda31a62 559 "name, reserved ".
e673ee24 560 "from IPAddress ".
dda31a62 561 "where ip = INET_ATON('$ip') and (reserved = 'yes' or name != '')";
ebdce584
DO
562 $result1 = $dbxlink->query ($query1);
563 if ($result1 == NULL)
e673ee24 564 return NULL;
ebdce584 565 if ($row = $result1->fetch (PDO::FETCH_ASSOC))
e673ee24 566 {
959c4f4c 567 $ret['exists'] = 1;
959c4f4c
DO
568 $ret['name'] = $row['name'];
569 $ret['reserved'] = $row['reserved'];
e673ee24 570 }
ebdce584 571 $result1->closeCursor();
e673ee24 572
ebdce584 573 $query2 =
dda31a62
DO
574 "select ".
575 "IPBonds.object_id as object_id, ".
576 "IPBonds.name as name, ".
577 "IPBonds.type as type, ".
578 "objtype_id, dict_value as objtype_name, " .
579 "RackObject.name as object_name ".
580 "from IPBonds join RackObject on IPBonds.object_id=RackObject.id ".
581 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
582 "where IPBonds.ip=INET_ATON('$ip') ".
583 "and chapter_name = 'RackObjectType' " .
584 "order by RackObject.id, IPBonds.name";
ebdce584 585 $result2 = $dbxlink->query ($query2);
dda31a62 586 $count=0;
ebdce584 587 while ($row = $result2->fetch (PDO::FETCH_ASSOC))
e673ee24 588 {
dda31a62
DO
589 $ret['bonds'][$count]['object_id'] = $row['object_id'];
590 $ret['bonds'][$count]['name'] = $row['name'];
591 $ret['bonds'][$count]['type'] = $row['type'];
592 $qo = array();
593 $qo['name'] = $row['object_name'];
594 $qo['objtype_id'] = $row['objtype_id'];
595 $qo['objtype_name'] = $row['objtype_name'];
596 $ret['bonds'][$count]['object_name'] = displayedName ($qo);
597 $count++;
598 $ret['exists'] = 1;
e673ee24 599 }
ebdce584 600 $result2->closeCursor();
e673ee24
DO
601
602 return $ret;
603}
604
605function bindIpToObject ($ip='', $object_id=0, $name='', $type='')
606{
607 global $dbxlink;
608
609 $range = getRangeByIp($ip);
e673ee24
DO
610 if (!$range)
611 return 'Non-existant ip address. Try adding IP range first';
612
20a92aa2
DO
613 $result = useInsertBlade
614 (
615 'IPBonds',
616 array
617 (
dda31a62 618 'ip' => "INET_ATON('$ip')",
20a92aa2
DO
619 'object_id' => "'${object_id}'",
620 'name' => "'${name}'",
621 'type' => "'${type}'"
622 )
623 );
624 return $result ? '' : 'useInsertBlade() failed in bindIpToObject()';
e673ee24
DO
625}
626
627// This function looks up 'has_problems' flag for 'T' atoms
628// and modifies 'hl' key. May be, this should be better done
629// in getRackData(). We don't honour 'skipped' key, because
630// the function is also used for thumb creation.
631function markupObjectProblems (&$rackData)
632{
633 for ($i = $rackData['height']; $i > 0; $i--)
634 for ($locidx = 0; $locidx < 3; $locidx++)
635 if ($rackData[$i][$locidx]['state'] == 'T')
636 {
637 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
638 if ($object['has_problems'] == 'yes')
639 {
640 // Object can be already highlighted.
641 if (isset ($rackData[$i][$locidx]['hl']))
642 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
643 else
644 $rackData[$i][$locidx]['hl'] = 'w';
645 }
646 }
647}
648
649function search_cmpObj ($a, $b)
650{
651 return ($a['score'] > $b['score'] ? -1 : 1);
652}
653
654// This function performs search and then calculates score for each result.
655// Given previous search results in $objects argument, it adds new results
656// to the array and updates score for existing results, if it is greater than
657// existing score.
658function mergeSearchResults (&$objects, $terms, $fieldname)
659{
660 global $dbxlink;
661 $query =
662 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
663 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
664 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
665 $count = 0;
666 foreach (explode (' ', $terms) as $term)
667 {
668 if ($count) $query .= ' or ';
669 $query .= "${fieldname} like '%$term%'";
670 $count++;
671 }
672 $query .= "";
673 $result = $dbxlink->query($query);
674 if ($result == NULL)
675 {
61e269b5 676 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
677 return NULL;
678 }
679// FIXME: this dead call was executed 4 times per 1 object search!
680// $typeList = getObjectTypeList();
681 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
682 while ($row = $result->fetch(PDO::FETCH_ASSOC))
683 {
684 foreach ($clist as $cname)
685 $object[$cname] = $row[$cname];
686 $object['score'] = 0;
687 $object['dname'] = displayedName ($object);
688 unset ($object['objtype_id']);
689 foreach (explode (' ', $terms) as $term)
690 if (strstr ($object['name'], $term))
691 $object['score'] += 1;
692 unset ($object['name']);
693 if (!isset ($objects[$row['id']]))
694 $objects[$row['id']] = $object;
695 elseif ($objects[$row['id']]['score'] < $object['score'])
696 $objects[$row['id']]['score'] = $object['score'];
697 }
698 return $objects;
699}
700
701function getSearchResults ($terms)
702{
703 $objects = array();
704 mergeSearchResults ($objects, $terms, 'name');
705 mergeSearchResults ($objects, $terms, 'label');
706 mergeSearchResults ($objects, $terms, 'asset_no');
707 mergeSearchResults ($objects, $terms, 'barcode');
708 if (count ($objects) == 1)
709 usort ($objects, 'search_cmpObj');
710 return $objects;
711}
712
713// This function removes all colons and dots from a string.
714function l2addressForDatabase ($string)
715{
716 if (empty ($string))
717 return 'NULL';
718 $pieces = explode (':', $string);
719 // This workaround is for SunOS ifconfig.
720 foreach ($pieces as &$byte)
721 if (strlen ($byte) == 1)
722 $byte = '0' . $byte;
723 // And this workaround is for PHP.
724 unset ($byte);
725 $string = implode ('', $pieces);
726 $pieces = explode ('.', $string);
727 $string = implode ('', $pieces);
728 $string = strtoupper ($string);
729 return "'$string'";
730}
731
732function l2addressFromDatabase ($string)
733{
734 switch (strlen ($string))
735 {
736 case 12: // Ethernet
737 case 16: // FireWire
738 $ret = implode (':', str_split ($string, 2));
739 break;
740 default:
741 $ret = $string;
742 break;
743 }
744 return $ret;
745}
746
747// The following 2 functions return previous and next rack IDs for
748// a given rack ID. The order of racks is the same as in renderRackspace()
749// or renderRow().
750function getPrevIDforRack ($row_id = 0, $rack_id = 0)
751{
752 if ($row_id <= 0 or $rack_id <= 0)
753 {
61e269b5 754 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
755 return NULL;
756 }
757 $rackList = getRacksForRow ($row_id);
758 doubleLink ($rackList);
759 if (isset ($rackList[$rack_id]['prev_key']))
760 return $rackList[$rack_id]['prev_key'];
761 return NULL;
762}
763
764function getNextIDforRack ($row_id = 0, $rack_id = 0)
765{
766 if ($row_id <= 0 or $rack_id <= 0)
767 {
61e269b5 768 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
769 return NULL;
770 }
771 $rackList = getRacksForRow ($row_id);
772 doubleLink ($rackList);
773 if (isset ($rackList[$rack_id]['next_key']))
774 return $rackList[$rack_id]['next_key'];
775 return NULL;
776}
777
778// This function finds previous and next array keys for each array key and
779// modifies its argument accordingly.
780function doubleLink (&$array)
781{
782 $prev_key = NULL;
783 foreach (array_keys ($array) as $key)
784 {
785 if ($prev_key)
786 {
787 $array[$key]['prev_key'] = $prev_key;
788 $array[$prev_key]['next_key'] = $key;
789 }
790 $prev_key = $key;
791 }
792}
793
794// After applying usort() to a rack list we will lose original array keys.
795// This function restores the keys so they are equal to rack IDs.
796function restoreRackIDs ($racks)
797{
798 $ret = array();
799 foreach ($racks as $rack)
800 $ret[$rack['id']] = $rack;
801 return $ret;
802}
803
804function sortTokenize ($a, $b)
805{
806 $aold='';
807 while ($a != $aold)
808 {
809 $aold=$a;
810 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
811 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
812 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
813 }
814
815 $bold='';
816 while ($b != $bold)
817 {
818 $bold=$b;
819 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
820 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
821 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
822 }
823
824
825
826 $ar = explode(' ', $a);
827 $br = explode(' ', $b);
828 for ($i=0; $i<count($ar) && $i<count($br); $i++)
829 {
830 $ret = 0;
831 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
832 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
833 else
834 $ret = strcasecmp($ar[$i], $br[$i]);
835 if ($ret != 0)
836 return $ret;
837 }
838 if ($i<count($ar))
839 return 1;
840 if ($i<count($br))
841 return -1;
842 return 0;
843}
844
845function sortByName ($a, $b)
846{
847 return sortTokenize($a['name'], $b['name']);
848}
849
6a3a37b2
DO
850function sortRacks ($a, $b)
851{
852 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
853}
854
e673ee24
DO
855function eq ($a, $b)
856{
857 return $a==$b;
858}
859
860function neq ($a, $b)
861{
862 return $a!=$b;
863}
864
865function countRefsOfType ($refs, $type, $eq)
866{
867 $count=0;
868 foreach ($refs as $ref)
869 {
870 if ($eq($ref['type'], $type))
871 $count++;
872 }
873 return $count;
874}
875
876function sortEmptyPorts ($a, $b)
877{
878 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
879 if ($objname_cmp == 0)
880 {
881 return sortTokenize($a['Port_name'], $b['Port_name']);
882 }
883 return $objname_cmp;
884}
885
886function sortObjectAddressesAndNames ($a, $b)
887{
888 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
889 if ($objname_cmp == 0)
890 {
891 $objname_cmp = sortTokenize($a['port_name'], $b['port_name']);
892 if ($objname_cmp == 0)
893 {
894 sortTokenize($a['ip'], $b['ip']);
895 }
896 return $objname_cmp;
897 }
898 return $objname_cmp;
899}
900
901
902
903function sortAddresses ($a, $b)
904{
905 $name_cmp = sortTokenize($a['name'], $b['name']);
906 if ($name_cmp == 0)
907 {
908 return sortTokenize($a['ip'], $b['ip']);
909 }
910 return $name_cmp;
911}
912
913// This function expands port compat list into a matrix.
914function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
915{
916 $matrix = array();
917 // Create type matrix and markup compatible types.
918 foreach (array_keys ($portTypeList) as $type1)
919 foreach (array_keys ($portTypeList) as $type2)
920 $matrix[$type1][$type2] = FALSE;
921 foreach ($portCompatList as $pair)
922 $matrix[$pair['type1']][$pair['type2']] = TRUE;
923 return $matrix;
924}
925
926function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
927{
928 global $dbxlink;
929
930 $range = getRangeByIp($localip);
931 if (!$range)
932 return "$localip: Non existant ip";
933
934 $range = getRangeByIp($remoteip);
935 if (!$range)
936 return "$remoteip: Non existant ip";
937
938 if ( ($localport <= 0) or ($localport >= 65536) )
939 return "$localport: invaild port";
940
941 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
942 return "$remoteport: invaild port";
943
944 $query =
945 "insert into PortForwarding set object_id='$object_id', localip=INET_ATON('$localip'), remoteip=INET_ATON('$remoteip'), localport='$localport', remoteport='$remoteport', proto='$proto', description='$description'";
946 $result = $dbxlink->exec ($query);
947
948 return '';
949}
950
951function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
952{
953 global $dbxlink;
954
955 $query =
956 "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'";
957 $result = $dbxlink->exec ($query);
958 return '';
959}
960
961function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
962{
963 global $dbxlink;
964
965 $query =
966 "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'";
967 $result = $dbxlink->exec ($query);
968 return '';
969}
970
971function getObjectForwards($object_id)
972{
973 global $dbxlink;
974
975 $ret = array();
976 $ret['out'] = array();
977 $ret['in'] = array();
978 $query =
979 "select ".
980 "dict_value as proto, ".
981 "proto as proto_bin, ".
982 "INET_NTOA(localip) as localip, ".
983 "localport, ".
984 "INET_NTOA(remoteip) as remoteip, ".
985 "remoteport, ".
f28fbe8b
DO
986 "ipa1.name as local_addr_name, " .
987 "ipa2.name as remote_addr_name, " .
e673ee24
DO
988 "description ".
989 "from PortForwarding inner join Dictionary on proto = dict_key natural join Chapter ".
f28fbe8b
DO
990 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
991 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
e673ee24
DO
992 "where object_id='$object_id' and chapter_name = 'Protocols' ".
993 "order by localip, localport, proto, remoteip, remoteport";
994 $result2 = $dbxlink->query ($query);
995 $count=0;
996 while ($row = $result2->fetch (PDO::FETCH_ASSOC))
997 {
f28fbe8b
DO
998 foreach (array ('proto', 'proto_bin', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
999 $ret['out'][$count][$cname] = $row[$cname];
e673ee24
DO
1000 $count++;
1001 }
1002 $result2->closeCursor();
1003
1004 $query =
1005 "select ".
1006 "dict_value as proto, ".
1007 "proto as proto_bin, ".
1008 "INET_NTOA(localip) as localip, ".
1009 "localport, ".
1010 "INET_NTOA(remoteip) as remoteip, ".
1011 "remoteport, ".
1012 "PortForwarding.object_id as object_id, ".
1013 "RackObject.name as object_name, ".
1014 "description ".
f28fbe8b 1015 "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
1016 "where IPBonds.object_id='$object_id' and chapter_name = 'Protocols' ".
1017 "order by remoteip, remoteport, proto, localip, localport";
1018 $result3 = $dbxlink->query ($query);
1019 $count=0;
1020 while ($row = $result3->fetch (PDO::FETCH_ASSOC))
1021 {
603ad85f 1022 foreach (array ('proto', 'proto_bin', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
f28fbe8b 1023 $ret['in'][$count][$cname] = $row[$cname];
e673ee24
DO
1024 $count++;
1025 }
1026 $result3->closeCursor();
1027
1028 return $ret;
1029}
1030
c31cd72c 1031// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
1032// if FQDN is set. The next choice is object's common name, if it looks like a
1033// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 1034// object is returned (which may appear 0 and more elements long).
f321b50a 1035function findAllEndpoints ($object_id, $fallback = '')
c31cd72c
DO
1036{
1037 $values = getAttrValues ($object_id);
1038 foreach ($values as $record)
f321b50a 1039 if ($record['name'] == 'FQDN' && !empty ($record['value']))
c31cd72c
DO
1040 return array ($record['value']);
1041 $addresses = getObjectAddresses ($object_id);
1042 $regular = array();
1043 foreach ($addresses as $idx => $address)
1044 if ($address['type'] == 'regular')
fa8112d1 1045 $regular[] = $address['ip'];
f321b50a
DO
1046 if (!count ($regular) && !empty ($fallback))
1047 return array ($fallback);
c31cd72c
DO
1048 return $regular;
1049}
1050
83ba6670
DO
1051// Some records in the dictionary may be written as plain text or as Wiki
1052// link in the following syntax:
1053// 1. word
1054// 2. [[word URL]] // FIXME: this isn't working
1055// 3. [[word word word | URL]]
1056// This function parses the line and returns text suitable for either A
1057// (rendering <A HREF>) or O (for <OPTION>).
1058function parseWikiLink ($line, $which)
1059{
010231c2 1060 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
83ba6670 1061 return $line;
010231c2
DO
1062 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
1063 $s = explode ('|', $line);
83ba6670
DO
1064 $o_value = trim ($s[0]);
1065 $a_value = trim ($s[1]);
1066 if ($which == 'a')
010231c2 1067 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
1068 if ($which == 'o')
1069 return $o_value;
1070}
1071
2de490b7
DO
1072function buildVServiceName ($vsinfo = NULL)
1073{
1074 if ($vsinfo == NULL)
1075 {
1076 showError ('NULL argument', __FUNCTION__);
1077 return NULL;
1078 }
8d790216 1079 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
2de490b7
DO
1080}
1081
177b1e9b
DO
1082// rackspace usage for a single rack
1083// (T + W + U) / (height * 3 - A)
11df133a 1084function getRSUforRack ($data = NULL)
177b1e9b 1085{
11df133a 1086 if ($data == NULL)
177b1e9b
DO
1087 {
1088 showError ('Invalid argument', __FUNCTION__);
1089 return NULL;
1090 }
6ffba290 1091 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
1092 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1093 for ($locidx = 0; $locidx < 3; $locidx++)
1094 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 1095 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
1096}
1097
11df133a
DO
1098// Same for row.
1099function getRSUforRackRow ($rowData = NULL)
1100{
bb26a59e 1101 if ($rowData === NULL)
11df133a
DO
1102 {
1103 showError ('Invalid argument', __FUNCTION__);
1104 return NULL;
1105 }
bb26a59e
DO
1106 if (!count ($rowData))
1107 return 0;
11df133a 1108 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 1109 $total_height = 0;
dfa3c075
DO
1110 foreach (array_keys ($rowData) as $rack_id)
1111 {
1112 $data = getRackData ($rack_id);
1113 $total_height += $data['height'];
11df133a
DO
1114 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1115 for ($locidx = 0; $locidx < 3; $locidx++)
1116 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
1117 }
1118 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
1119}
1120
f1a0477d
DO
1121function getObjectCount ($rackData)
1122{
1123 $objects = array();
1124 for ($i = $rackData['height']; $i > 0; $i--)
1125 for ($locidx = 0; $locidx < 3; $locidx++)
1126 if
1127 (
1128 $rackData[$i][$locidx]['state'] == 'T' and
1129 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
1130 )
1131 $objects[] = $rackData[$i][$locidx]['object_id'];
1132 return count ($objects);
1133}
1134
9af110b4
DO
1135// Perform substitutions and return resulting string
1136function apply_macros ($macros, $subject)
1137{
1138 $ret = $subject;
1139 foreach ($macros as $search => $replace)
1140 $ret = str_replace ($search, $replace, $ret);
1141 return $ret;
1142}
1143
1144// Make sure the string is always wrapped with LF characters
1145function lf_wrap ($str)
1146{
1147 $ret = trim ($str, "\r\n");
1148 if (!empty ($ret))
1149 $ret .= "\n";
1150 return $ret;
1151}
1152
e6e7d8b3
DO
1153// Adopted from Mantis BTS code.
1154function string_insert_hrefs ($s)
1155{
1156 if (getConfigVar ('DETECT_URLS') != 'yes')
1157 return $s;
1158 # Find any URL in a string and replace it by a clickable link
1159 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
1160 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
1161 $s);
1162 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
1163 '<a href="mailto:\0">\0</a>',
1164 $s);
1165 return $s;
1166}
1167
1168// Idem.
1169function email_regex_simple ()
1170{
1171 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
1172 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
1173}
1174
e673ee24 1175?>