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