r1680 + getIPAddress(): release PDO handle; return VS data for address
[racktables] / inc / functions.php
1 <?php
2 /*
3 *
4 * This file is a library of computational functions for RackTables.
5 *
6 */
7
8 $loclist[0] = 'front';
9 $loclist[1] = 'interior';
10 $loclist[2] = 'rear';
11 $loclist['front'] = 0;
12 $loclist['interior'] = 1;
13 $loclist['rear'] = 2;
14 $template[0] = array (TRUE, TRUE, TRUE);
15 $template[1] = array (TRUE, TRUE, FALSE);
16 $template[2] = array (FALSE, TRUE, TRUE);
17 $template[3] = array (TRUE, FALSE, FALSE);
18 $template[4] = array (FALSE, TRUE, FALSE);
19 $template[5] = array (FALSE, FALSE, TRUE);
20 $templateWidth[0] = 3;
21 $templateWidth[1] = 2;
22 $templateWidth[2] = 2;
23 $templateWidth[3] = 1;
24 $templateWidth[4] = 1;
25 $templateWidth[5] = 1;
26
27 // 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.
30 function displayedName ($objectData)
31 {
32 if ($objectData['name'] != '')
33 return $objectData['name'];
34 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
35 return "ANONYMOUS " . $objectData['objtype_name'];
36 else
37 return "[${objectData['objtype_name']}]";
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.
43 function 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;
60 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
61 break 2;
62 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
63 break 2;
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);
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";
81 return $height;
82 }
83
84 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
85 // attributes.
86 function 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.
97 // Explicitly show even single-cell spanned atoms, because rectHeight()
98 // is expeciting this data for correct calculation.
99 if ($colspan != 0)
100 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
101 else
102 {
103 $colspan = $templateWidth[$template_idx];
104 if ($colspan >= 1)
105 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
106 if ($maxheight >= 1)
107 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
108 }
109 }
110 }
111 }
112 return;
113 }
114
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.
118 function markAllSpans (&$rackData = NULL)
119 {
120 if ($rackData == NULL)
121 {
122 showError ('Invalid rackData', __FUNCTION__);
123 return;
124 }
125 for ($i = $rackData['height']; $i > 0; $i--)
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).
131 function markBestSpan (&$rackData, $i)
132 {
133 global $template, $templateWidth;
134 for ($j = 0; $j < 6; $j++)
135 {
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)
146 {
147 $best_template_index = $j;
148 $bestheight = $height[$j];
149 break;
150 }
151 // distribute span marks
152 markSpan ($rackData, $i, $bestheight, $best_template_index);
153 return TRUE;
154 }
155
156 function delRow ($row_id = 0)
157 {
158 if ($row_id == 0)
159 {
160 showError ('Not all required args are present.', __FUNCTION__);
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 {
173 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1', __FUNCTION__);
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
181 function delRack ($rack_id = 0)
182 {
183 if ($rack_id == 0)
184 {
185 showError ('Not all required args are present.', __FUNCTION__);
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 {
198 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1', __FUNCTION__);
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
206 function delObject ($object_id = 0)
207 {
208 if ($object_id == 0)
209 {
210 showError ('Not all required args are present.', __FUNCTION__);
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 {
223 showError ('Marked ' . $result.rowCount() . ' rows as deleted, but expected 1', __FUNCTION__);
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.
232 function 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.
250 function 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'.
266 function 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.
282 function 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).
298 function 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.
313 function 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.
331 function 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
347 function 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
362 function 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
377 function addRange ($range='', $name='', $is_bcast = FALSE)
378 {
379 // $range is in x.x.x.x/x format, split into ip/mask vars
380 $rangeArray = explode('/', $range);
381 if (count ($rangeArray) != 2)
382 return "Invalid IP subnet '${range}'";
383 $ip = $rangeArray[0];
384 $mask = $rangeArray[1];
385
386 if (empty ($ip) or empty ($mask))
387 return "Invalid IP subnet '${range}'";
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);
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 }
452 return '';
453 }
454
455 function getIPRange ($id = 0)
456 {
457 global $dbxlink;
458 $query =
459 "select ".
460 "id as IPRanges_id, ".
461 "INET_NTOA(ip) as IPRanges_ip, ".
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)
468 return NULL;
469 $ret = array();
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'];
475 $ret['ip_bin'] = ip2long ($row['IPRanges_ip']);
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();
481 $result->closeCursor();
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'])) . "'";
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.
490 $query =
491 "select INET_NTOA(ip) as ip, name, reserved from IPAddress " .
492 "where ip between ${db_first} and ${db_last} " .
493 "and (reserved = 'yes' or name != '')";
494 $ipa_res = $dbxlink->query ($query);
495 if ($ipa_res == NULL)
496 return $ret;
497 while ($row = $ipa_res->fetch (PDO::FETCH_ASSOC))
498 {
499 $ip_bin = ip2long ($row['ip']);
500 $ret['addrlist'][$ip_bin] = $row;
501 $tmp = array();
502 foreach (array ('ip', 'name', 'reserved') as $cname)
503 $tmp[$cname] = $row[$cname];
504 $tmp['references'] = array();
505 $ret['addrlist'][$ip_bin] = $tmp;
506 }
507 $ipa_res->closeCursor();
508
509 $query =
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 " .
513 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
514 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
515 "where ip between ${db_first} and ${db_last} " .
516 "and chapter_name = 'RackObjectType'" .
517 "order by ipb.type, object_name";
518 $ipb_res = $dbxlink->query ($query);
519 while ($row = $ipb_res->fetch (PDO::FETCH_ASSOC))
520 {
521 $ip_bin = ip2long ($row['ip']);
522 if (!isset ($ret['addrlist'][$ip_bin]))
523 {
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();
529 }
530 $tmp = array();
531 foreach (array ('object_id', 'type', 'name') as $cname)
532 $tmp[$cname] = $row[$cname];
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);
537 $ret['addrlist'][$ip_bin]['references'][] = $tmp;
538 }
539 $ipb_res->closeCursor();
540
541 return $ret;
542 }
543
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.
547 function getIPAddress ($ip=0)
548 {
549 $ret = array();
550 $ret['bonds'] = array();
551 // FIXME: below two aren't neither filled in with data nor rendered (ticket:23)
552 $ret['outpf'] = array();
553 $ret['inpf'] = array();
554 $ret['vslist'] = array();
555 $ret['rslist'] = array();
556 $ret['exists'] = 0;
557 $ret['name'] = '';
558 $ret['reserved'] = 'no';
559 global $dbxlink;
560 $query =
561 "select ".
562 "name, reserved ".
563 "from IPAddress ".
564 "where ip = INET_ATON('$ip') and (reserved = 'yes' or name != '')";
565 $result = $dbxlink->query ($query);
566 if ($result == NULL)
567 {
568 showError ('Query #1 failed', __FUNCTION__);
569 return NULL;
570 }
571 if ($row = $result->fetch (PDO::FETCH_ASSOC))
572 {
573 $ret['exists'] = 1;
574 $ret['name'] = $row['name'];
575 $ret['reserved'] = $row['reserved'];
576 }
577 $result->closeCursor();
578 unset ($result);
579
580 $query =
581 "select ".
582 "IPBonds.object_id as object_id, ".
583 "IPBonds.name as name, ".
584 "IPBonds.type as type, ".
585 "objtype_id, dict_value as objtype_name, " .
586 "RackObject.name as object_name ".
587 "from IPBonds join RackObject on IPBonds.object_id=RackObject.id ".
588 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
589 "where IPBonds.ip=INET_ATON('$ip') ".
590 "and chapter_name = 'RackObjectType' " .
591 "order by RackObject.id, IPBonds.name";
592 $result = $dbxlink->query ($query);
593 $count=0;
594 while ($row = $result->fetch (PDO::FETCH_ASSOC))
595 {
596 $ret['bonds'][$count]['object_id'] = $row['object_id'];
597 $ret['bonds'][$count]['name'] = $row['name'];
598 $ret['bonds'][$count]['type'] = $row['type'];
599 $qo = array();
600 $qo['name'] = $row['object_name'];
601 $qo['objtype_id'] = $row['objtype_id'];
602 $qo['objtype_name'] = $row['objtype_name'];
603 $ret['bonds'][$count]['object_name'] = displayedName ($qo);
604 $count++;
605 $ret['exists'] = 1;
606 }
607 $result->closeCursor();
608 unset ($result);
609
610 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where vip = inet_aton('${ip}')";
611 $result = $dbxlink->query ($query);
612 while ($row = $result->fetch (PDO::FETCH_ASSOC))
613 $ret['vslist'][] = $row;
614 $result->closeCursor();
615 unset ($result);
616
617 return $ret;
618 }
619
620 function bindIpToObject ($ip='', $object_id=0, $name='', $type='')
621 {
622 global $dbxlink;
623
624 $range = getRangeByIp($ip);
625 if (!$range)
626 return 'Non-existant ip address. Try adding IP range first';
627
628 $result = useInsertBlade
629 (
630 'IPBonds',
631 array
632 (
633 'ip' => "INET_ATON('$ip')",
634 'object_id' => "'${object_id}'",
635 'name' => "'${name}'",
636 'type' => "'${type}'"
637 )
638 );
639 return $result ? '' : 'useInsertBlade() failed in bindIpToObject()';
640 }
641
642 // This function looks up 'has_problems' flag for 'T' atoms
643 // and modifies 'hl' key. May be, this should be better done
644 // in getRackData(). We don't honour 'skipped' key, because
645 // the function is also used for thumb creation.
646 function markupObjectProblems (&$rackData)
647 {
648 for ($i = $rackData['height']; $i > 0; $i--)
649 for ($locidx = 0; $locidx < 3; $locidx++)
650 if ($rackData[$i][$locidx]['state'] == 'T')
651 {
652 $object = getObjectInfo ($rackData[$i][$locidx]['object_id']);
653 if ($object['has_problems'] == 'yes')
654 {
655 // Object can be already highlighted.
656 if (isset ($rackData[$i][$locidx]['hl']))
657 $rackData[$i][$locidx]['hl'] = $rackData[$i][$locidx]['hl'] . 'w';
658 else
659 $rackData[$i][$locidx]['hl'] = 'w';
660 }
661 }
662 }
663
664 function search_cmpObj ($a, $b)
665 {
666 return ($a['score'] > $b['score'] ? -1 : 1);
667 }
668
669 // This function performs search and then calculates score for each result.
670 // Given previous search results in $objects argument, it adds new results
671 // to the array and updates score for existing results, if it is greater than
672 // existing score.
673 function mergeSearchResults (&$objects, $terms, $fieldname)
674 {
675 global $dbxlink;
676 $query =
677 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
678 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
679 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
680 $count = 0;
681 foreach (explode (' ', $terms) as $term)
682 {
683 if ($count) $query .= ' or ';
684 $query .= "${fieldname} like '%$term%'";
685 $count++;
686 }
687 $query .= "";
688 $result = $dbxlink->query($query);
689 if ($result == NULL)
690 {
691 showError ("SQL query failed", __FUNCTION__);
692 return NULL;
693 }
694 // FIXME: this dead call was executed 4 times per 1 object search!
695 // $typeList = getObjectTypeList();
696 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
697 while ($row = $result->fetch(PDO::FETCH_ASSOC))
698 {
699 foreach ($clist as $cname)
700 $object[$cname] = $row[$cname];
701 $object['score'] = 0;
702 $object['dname'] = displayedName ($object);
703 unset ($object['objtype_id']);
704 foreach (explode (' ', $terms) as $term)
705 if (strstr ($object['name'], $term))
706 $object['score'] += 1;
707 unset ($object['name']);
708 if (!isset ($objects[$row['id']]))
709 $objects[$row['id']] = $object;
710 elseif ($objects[$row['id']]['score'] < $object['score'])
711 $objects[$row['id']]['score'] = $object['score'];
712 }
713 return $objects;
714 }
715
716 function getSearchResults ($terms)
717 {
718 $objects = array();
719 mergeSearchResults ($objects, $terms, 'name');
720 mergeSearchResults ($objects, $terms, 'label');
721 mergeSearchResults ($objects, $terms, 'asset_no');
722 mergeSearchResults ($objects, $terms, 'barcode');
723 if (count ($objects) == 1)
724 usort ($objects, 'search_cmpObj');
725 return $objects;
726 }
727
728 // This function removes all colons and dots from a string.
729 function l2addressForDatabase ($string)
730 {
731 if (empty ($string))
732 return 'NULL';
733 $pieces = explode (':', $string);
734 // This workaround is for SunOS ifconfig.
735 foreach ($pieces as &$byte)
736 if (strlen ($byte) == 1)
737 $byte = '0' . $byte;
738 // And this workaround is for PHP.
739 unset ($byte);
740 $string = implode ('', $pieces);
741 $pieces = explode ('.', $string);
742 $string = implode ('', $pieces);
743 $string = strtoupper ($string);
744 return "'$string'";
745 }
746
747 function l2addressFromDatabase ($string)
748 {
749 switch (strlen ($string))
750 {
751 case 12: // Ethernet
752 case 16: // FireWire
753 $ret = implode (':', str_split ($string, 2));
754 break;
755 default:
756 $ret = $string;
757 break;
758 }
759 return $ret;
760 }
761
762 // The following 2 functions return previous and next rack IDs for
763 // a given rack ID. The order of racks is the same as in renderRackspace()
764 // or renderRow().
765 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
766 {
767 if ($row_id <= 0 or $rack_id <= 0)
768 {
769 showError ('Invalid arguments passed', __FUNCTION__);
770 return NULL;
771 }
772 $rackList = getRacksForRow ($row_id);
773 doubleLink ($rackList);
774 if (isset ($rackList[$rack_id]['prev_key']))
775 return $rackList[$rack_id]['prev_key'];
776 return NULL;
777 }
778
779 function getNextIDforRack ($row_id = 0, $rack_id = 0)
780 {
781 if ($row_id <= 0 or $rack_id <= 0)
782 {
783 showError ('Invalid arguments passed', __FUNCTION__);
784 return NULL;
785 }
786 $rackList = getRacksForRow ($row_id);
787 doubleLink ($rackList);
788 if (isset ($rackList[$rack_id]['next_key']))
789 return $rackList[$rack_id]['next_key'];
790 return NULL;
791 }
792
793 // This function finds previous and next array keys for each array key and
794 // modifies its argument accordingly.
795 function doubleLink (&$array)
796 {
797 $prev_key = NULL;
798 foreach (array_keys ($array) as $key)
799 {
800 if ($prev_key)
801 {
802 $array[$key]['prev_key'] = $prev_key;
803 $array[$prev_key]['next_key'] = $key;
804 }
805 $prev_key = $key;
806 }
807 }
808
809 // After applying usort() to a rack list we will lose original array keys.
810 // This function restores the keys so they are equal to rack IDs.
811 function restoreRackIDs ($racks)
812 {
813 $ret = array();
814 foreach ($racks as $rack)
815 $ret[$rack['id']] = $rack;
816 return $ret;
817 }
818
819 function sortTokenize ($a, $b)
820 {
821 $aold='';
822 while ($a != $aold)
823 {
824 $aold=$a;
825 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
826 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
827 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
828 }
829
830 $bold='';
831 while ($b != $bold)
832 {
833 $bold=$b;
834 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
835 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
836 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
837 }
838
839
840
841 $ar = explode(' ', $a);
842 $br = explode(' ', $b);
843 for ($i=0; $i<count($ar) && $i<count($br); $i++)
844 {
845 $ret = 0;
846 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
847 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
848 else
849 $ret = strcasecmp($ar[$i], $br[$i]);
850 if ($ret != 0)
851 return $ret;
852 }
853 if ($i<count($ar))
854 return 1;
855 if ($i<count($br))
856 return -1;
857 return 0;
858 }
859
860 function sortByName ($a, $b)
861 {
862 return sortTokenize($a['name'], $b['name']);
863 }
864
865 function sortRacks ($a, $b)
866 {
867 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
868 }
869
870 function eq ($a, $b)
871 {
872 return $a==$b;
873 }
874
875 function neq ($a, $b)
876 {
877 return $a!=$b;
878 }
879
880 function countRefsOfType ($refs, $type, $eq)
881 {
882 $count=0;
883 foreach ($refs as $ref)
884 {
885 if ($eq($ref['type'], $type))
886 $count++;
887 }
888 return $count;
889 }
890
891 function sortEmptyPorts ($a, $b)
892 {
893 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
894 if ($objname_cmp == 0)
895 {
896 return sortTokenize($a['Port_name'], $b['Port_name']);
897 }
898 return $objname_cmp;
899 }
900
901 function sortObjectAddressesAndNames ($a, $b)
902 {
903 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
904 if ($objname_cmp == 0)
905 {
906 $objname_cmp = sortTokenize($a['port_name'], $b['port_name']);
907 if ($objname_cmp == 0)
908 {
909 sortTokenize($a['ip'], $b['ip']);
910 }
911 return $objname_cmp;
912 }
913 return $objname_cmp;
914 }
915
916
917
918 function sortAddresses ($a, $b)
919 {
920 $name_cmp = sortTokenize($a['name'], $b['name']);
921 if ($name_cmp == 0)
922 {
923 return sortTokenize($a['ip'], $b['ip']);
924 }
925 return $name_cmp;
926 }
927
928 // This function expands port compat list into a matrix.
929 function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
930 {
931 $matrix = array();
932 // Create type matrix and markup compatible types.
933 foreach (array_keys ($portTypeList) as $type1)
934 foreach (array_keys ($portTypeList) as $type2)
935 $matrix[$type1][$type2] = FALSE;
936 foreach ($portCompatList as $pair)
937 $matrix[$pair['type1']][$pair['type2']] = TRUE;
938 return $matrix;
939 }
940
941 function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
942 {
943 global $dbxlink;
944
945 $range = getRangeByIp($localip);
946 if (!$range)
947 return "$localip: Non existant ip";
948
949 $range = getRangeByIp($remoteip);
950 if (!$range)
951 return "$remoteip: Non existant ip";
952
953 if ( ($localport <= 0) or ($localport >= 65536) )
954 return "$localport: invaild port";
955
956 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
957 return "$remoteport: invaild port";
958
959 $query =
960 "insert into PortForwarding set object_id='$object_id', localip=INET_ATON('$localip'), remoteip=INET_ATON('$remoteip'), localport='$localport', remoteport='$remoteport', proto='$proto', description='$description'";
961 $result = $dbxlink->exec ($query);
962
963 return '';
964 }
965
966 function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
967 {
968 global $dbxlink;
969
970 $query =
971 "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'";
972 $result = $dbxlink->exec ($query);
973 return '';
974 }
975
976 function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
977 {
978 global $dbxlink;
979
980 $query =
981 "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'";
982 $result = $dbxlink->exec ($query);
983 return '';
984 }
985
986 function getObjectForwards($object_id)
987 {
988 global $dbxlink;
989
990 $ret = array();
991 $ret['out'] = array();
992 $ret['in'] = array();
993 $query =
994 "select ".
995 "dict_value as proto, ".
996 "proto as proto_bin, ".
997 "INET_NTOA(localip) as localip, ".
998 "localport, ".
999 "INET_NTOA(remoteip) as remoteip, ".
1000 "remoteport, ".
1001 "ipa1.name as local_addr_name, " .
1002 "ipa2.name as remote_addr_name, " .
1003 "description ".
1004 "from PortForwarding inner join Dictionary on proto = dict_key natural join Chapter ".
1005 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
1006 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
1007 "where object_id='$object_id' and chapter_name = 'Protocols' ".
1008 "order by localip, localport, proto, remoteip, remoteport";
1009 $result2 = $dbxlink->query ($query);
1010 $count=0;
1011 while ($row = $result2->fetch (PDO::FETCH_ASSOC))
1012 {
1013 foreach (array ('proto', 'proto_bin', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
1014 $ret['out'][$count][$cname] = $row[$cname];
1015 $count++;
1016 }
1017 $result2->closeCursor();
1018
1019 $query =
1020 "select ".
1021 "dict_value as proto, ".
1022 "proto as proto_bin, ".
1023 "INET_NTOA(localip) as localip, ".
1024 "localport, ".
1025 "INET_NTOA(remoteip) as remoteip, ".
1026 "remoteport, ".
1027 "PortForwarding.object_id as object_id, ".
1028 "RackObject.name as object_name, ".
1029 "description ".
1030 "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 ".
1031 "where IPBonds.object_id='$object_id' and chapter_name = 'Protocols' ".
1032 "order by remoteip, remoteport, proto, localip, localport";
1033 $result3 = $dbxlink->query ($query);
1034 $count=0;
1035 while ($row = $result3->fetch (PDO::FETCH_ASSOC))
1036 {
1037 foreach (array ('proto', 'proto_bin', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
1038 $ret['in'][$count][$cname] = $row[$cname];
1039 $count++;
1040 }
1041 $result3->closeCursor();
1042
1043 return $ret;
1044 }
1045
1046 // This function returns an array of single element of object's FQDN attribute,
1047 // if FQDN is set. The next choice is object's common name, if it looks like a
1048 // hostname. Otherwise an array of all 'regular' IP addresses of the
1049 // object is returned (which may appear 0 and more elements long).
1050 function findAllEndpoints ($object_id, $fallback = '')
1051 {
1052 $values = getAttrValues ($object_id);
1053 foreach ($values as $record)
1054 if ($record['name'] == 'FQDN' && !empty ($record['value']))
1055 return array ($record['value']);
1056 $addresses = getObjectAddresses ($object_id);
1057 $regular = array();
1058 foreach ($addresses as $idx => $address)
1059 if ($address['type'] == 'regular')
1060 $regular[] = $address['ip'];
1061 if (!count ($regular) && !empty ($fallback))
1062 return array ($fallback);
1063 return $regular;
1064 }
1065
1066 // Some records in the dictionary may be written as plain text or as Wiki
1067 // link in the following syntax:
1068 // 1. word
1069 // 2. [[word URL]] // FIXME: this isn't working
1070 // 3. [[word word word | URL]]
1071 // This function parses the line and returns text suitable for either A
1072 // (rendering <A HREF>) or O (for <OPTION>).
1073 function parseWikiLink ($line, $which)
1074 {
1075 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
1076 return $line;
1077 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
1078 $s = explode ('|', $line);
1079 $o_value = trim ($s[0]);
1080 $a_value = trim ($s[1]);
1081 if ($which == 'a')
1082 return "<a href='${a_value}'>${o_value}</a>";
1083 if ($which == 'o')
1084 return $o_value;
1085 }
1086
1087 function buildVServiceName ($vsinfo = NULL)
1088 {
1089 if ($vsinfo == NULL)
1090 {
1091 showError ('NULL argument', __FUNCTION__);
1092 return NULL;
1093 }
1094 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
1095 }
1096
1097 // rackspace usage for a single rack
1098 // (T + W + U) / (height * 3 - A)
1099 function getRSUforRack ($data = NULL)
1100 {
1101 if ($data == NULL)
1102 {
1103 showError ('Invalid argument', __FUNCTION__);
1104 return NULL;
1105 }
1106 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
1107 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1108 for ($locidx = 0; $locidx < 3; $locidx++)
1109 $counter[$data[$unit_no][$locidx]['state']]++;
1110 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
1111 }
1112
1113 // Same for row.
1114 function getRSUforRackRow ($rowData = NULL)
1115 {
1116 if ($rowData === NULL)
1117 {
1118 showError ('Invalid argument', __FUNCTION__);
1119 return NULL;
1120 }
1121 if (!count ($rowData))
1122 return 0;
1123 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
1124 $total_height = 0;
1125 foreach (array_keys ($rowData) as $rack_id)
1126 {
1127 $data = getRackData ($rack_id);
1128 $total_height += $data['height'];
1129 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1130 for ($locidx = 0; $locidx < 3; $locidx++)
1131 $counter[$data[$unit_no][$locidx]['state']]++;
1132 }
1133 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
1134 }
1135
1136 function getObjectCount ($rackData)
1137 {
1138 $objects = array();
1139 for ($i = $rackData['height']; $i > 0; $i--)
1140 for ($locidx = 0; $locidx < 3; $locidx++)
1141 if
1142 (
1143 $rackData[$i][$locidx]['state'] == 'T' and
1144 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
1145 )
1146 $objects[] = $rackData[$i][$locidx]['object_id'];
1147 return count ($objects);
1148 }
1149
1150 // Perform substitutions and return resulting string
1151 function apply_macros ($macros, $subject)
1152 {
1153 $ret = $subject;
1154 foreach ($macros as $search => $replace)
1155 $ret = str_replace ($search, $replace, $ret);
1156 return $ret;
1157 }
1158
1159 // Make sure the string is always wrapped with LF characters
1160 function lf_wrap ($str)
1161 {
1162 $ret = trim ($str, "\r\n");
1163 if (!empty ($ret))
1164 $ret .= "\n";
1165 return $ret;
1166 }
1167
1168 // Adopted from Mantis BTS code.
1169 function string_insert_hrefs ($s)
1170 {
1171 if (getConfigVar ('DETECT_URLS') != 'yes')
1172 return $s;
1173 # Find any URL in a string and replace it by a clickable link
1174 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
1175 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
1176 $s);
1177 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
1178 '<a href="mailto:\0">\0</a>',
1179 $s);
1180 return $s;
1181 }
1182
1183 // Idem.
1184 function email_regex_simple ()
1185 {
1186 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
1187 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
1188 }
1189
1190 ?>