r2017 + change VS bypass arg name to "vs_id"
[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 }
fb45e432 629 $query .= " order by ${fieldname}";
065eeb52 630 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
631// FIXME: this dead call was executed 4 times per 1 object search!
632// $typeList = getObjectTypeList();
633 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
105a3bc8 634 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
635 {
636 foreach ($clist as $cname)
637 $object[$cname] = $row[$cname];
638 $object['score'] = 0;
639 $object['dname'] = displayedName ($object);
640 unset ($object['objtype_id']);
641 foreach (explode (' ', $terms) as $term)
642 if (strstr ($object['name'], $term))
643 $object['score'] += 1;
644 unset ($object['name']);
645 if (!isset ($objects[$row['id']]))
646 $objects[$row['id']] = $object;
647 elseif ($objects[$row['id']]['score'] < $object['score'])
648 $objects[$row['id']]['score'] = $object['score'];
649 }
650 return $objects;
651}
652
ea5fc465 653function getObjectSearchResults ($terms)
e673ee24
DO
654{
655 $objects = array();
656 mergeSearchResults ($objects, $terms, 'name');
657 mergeSearchResults ($objects, $terms, 'label');
658 mergeSearchResults ($objects, $terms, 'asset_no');
659 mergeSearchResults ($objects, $terms, 'barcode');
660 if (count ($objects) == 1)
661 usort ($objects, 'search_cmpObj');
662 return $objects;
663}
664
665// This function removes all colons and dots from a string.
666function l2addressForDatabase ($string)
667{
668 if (empty ($string))
669 return 'NULL';
670 $pieces = explode (':', $string);
671 // This workaround is for SunOS ifconfig.
672 foreach ($pieces as &$byte)
673 if (strlen ($byte) == 1)
674 $byte = '0' . $byte;
675 // And this workaround is for PHP.
676 unset ($byte);
677 $string = implode ('', $pieces);
678 $pieces = explode ('.', $string);
679 $string = implode ('', $pieces);
680 $string = strtoupper ($string);
681 return "'$string'";
682}
683
684function l2addressFromDatabase ($string)
685{
686 switch (strlen ($string))
687 {
688 case 12: // Ethernet
689 case 16: // FireWire
690 $ret = implode (':', str_split ($string, 2));
691 break;
692 default:
693 $ret = $string;
694 break;
695 }
696 return $ret;
697}
698
699// The following 2 functions return previous and next rack IDs for
700// a given rack ID. The order of racks is the same as in renderRackspace()
701// or renderRow().
702function getPrevIDforRack ($row_id = 0, $rack_id = 0)
703{
704 if ($row_id <= 0 or $rack_id <= 0)
705 {
61e269b5 706 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
707 return NULL;
708 }
709 $rackList = getRacksForRow ($row_id);
710 doubleLink ($rackList);
711 if (isset ($rackList[$rack_id]['prev_key']))
712 return $rackList[$rack_id]['prev_key'];
713 return NULL;
714}
715
716function getNextIDforRack ($row_id = 0, $rack_id = 0)
717{
718 if ($row_id <= 0 or $rack_id <= 0)
719 {
61e269b5 720 showError ('Invalid arguments passed', __FUNCTION__);
e673ee24
DO
721 return NULL;
722 }
723 $rackList = getRacksForRow ($row_id);
724 doubleLink ($rackList);
725 if (isset ($rackList[$rack_id]['next_key']))
726 return $rackList[$rack_id]['next_key'];
727 return NULL;
728}
729
730// This function finds previous and next array keys for each array key and
731// modifies its argument accordingly.
732function doubleLink (&$array)
733{
734 $prev_key = NULL;
735 foreach (array_keys ($array) as $key)
736 {
737 if ($prev_key)
738 {
739 $array[$key]['prev_key'] = $prev_key;
740 $array[$prev_key]['next_key'] = $key;
741 }
742 $prev_key = $key;
743 }
744}
745
746// After applying usort() to a rack list we will lose original array keys.
747// This function restores the keys so they are equal to rack IDs.
748function restoreRackIDs ($racks)
749{
750 $ret = array();
751 foreach ($racks as $rack)
752 $ret[$rack['id']] = $rack;
753 return $ret;
754}
755
756function sortTokenize ($a, $b)
757{
758 $aold='';
759 while ($a != $aold)
760 {
761 $aold=$a;
762 $a = ereg_replace('[^a-zA-Z0-9]',' ',$a);
763 $a = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$a);
764 $a = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$a);
765 }
766
767 $bold='';
768 while ($b != $bold)
769 {
770 $bold=$b;
771 $b = ereg_replace('[^a-zA-Z0-9]',' ',$b);
772 $b = ereg_replace('([0-9])([a-zA-Z])','\\1 \\2',$b);
773 $b = ereg_replace('([a-zA-Z])([0-9])','\\1 \\2',$b);
774 }
775
776
777
778 $ar = explode(' ', $a);
779 $br = explode(' ', $b);
780 for ($i=0; $i<count($ar) && $i<count($br); $i++)
781 {
782 $ret = 0;
783 if (is_numeric($ar[$i]) and is_numeric($br[$i]))
784 $ret = ($ar[$i]==$br[$i])?0:($ar[$i]<$br[$i]?-1:1);
785 else
786 $ret = strcasecmp($ar[$i], $br[$i]);
787 if ($ret != 0)
788 return $ret;
789 }
790 if ($i<count($ar))
791 return 1;
792 if ($i<count($br))
793 return -1;
794 return 0;
795}
796
797function sortByName ($a, $b)
798{
799 return sortTokenize($a['name'], $b['name']);
800}
801
6a3a37b2
DO
802function sortRacks ($a, $b)
803{
804 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
805}
806
e673ee24
DO
807function eq ($a, $b)
808{
809 return $a==$b;
810}
811
812function neq ($a, $b)
813{
814 return $a!=$b;
815}
816
817function countRefsOfType ($refs, $type, $eq)
818{
819 $count=0;
820 foreach ($refs as $ref)
821 {
822 if ($eq($ref['type'], $type))
823 $count++;
824 }
825 return $count;
826}
827
828function sortEmptyPorts ($a, $b)
829{
830 $objname_cmp = sortTokenize($a['Object_name'], $b['Object_name']);
831 if ($objname_cmp == 0)
832 {
833 return sortTokenize($a['Port_name'], $b['Port_name']);
834 }
835 return $objname_cmp;
836}
837
838function sortObjectAddressesAndNames ($a, $b)
839{
840 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
841 if ($objname_cmp == 0)
842 {
79f22c3d
DO
843 $name_a = (isset ($a['port_name'])) ? $a['port_name'] : '';
844 $name_b = (isset ($b['port_name'])) ? $b['port_name'] : '';
845 $objname_cmp = sortTokenize($name_a, $name_b);
e673ee24 846 if ($objname_cmp == 0)
e673ee24 847 sortTokenize($a['ip'], $b['ip']);
e673ee24
DO
848 return $objname_cmp;
849 }
850 return $objname_cmp;
851}
852
853
854
855function sortAddresses ($a, $b)
856{
857 $name_cmp = sortTokenize($a['name'], $b['name']);
858 if ($name_cmp == 0)
859 {
860 return sortTokenize($a['ip'], $b['ip']);
861 }
862 return $name_cmp;
863}
864
865// This function expands port compat list into a matrix.
866function buildPortCompatMatrixFromList ($portTypeList, $portCompatList)
867{
868 $matrix = array();
869 // Create type matrix and markup compatible types.
870 foreach (array_keys ($portTypeList) as $type1)
871 foreach (array_keys ($portTypeList) as $type2)
872 $matrix[$type1][$type2] = FALSE;
873 foreach ($portCompatList as $pair)
874 $matrix[$pair['type1']][$pair['type2']] = TRUE;
875 return $matrix;
876}
877
878function newPortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
879{
880 global $dbxlink;
881
882 $range = getRangeByIp($localip);
883 if (!$range)
884 return "$localip: Non existant ip";
885
886 $range = getRangeByIp($remoteip);
887 if (!$range)
888 return "$remoteip: Non existant ip";
889
890 if ( ($localport <= 0) or ($localport >= 65536) )
891 return "$localport: invaild port";
892
893 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
894 return "$remoteport: invaild port";
895
9bea3a8b
DO
896 $result = useInsertBlade
897 (
898 'PortForwarding',
899 array
900 (
901 'object_id' => $object_id,
902 'localip' => "INET_ATON('${localip}')",
903 'remoteip' => "INET_ATON('$remoteip')",
904 'localport' => $localport,
905 'remoteport' => $remoteport,
906 'proto' => "'${proto}'",
907 'description' => "'${description}'",
908 )
909 );
910 if ($result)
911 return '';
912 else
913 return __FUNCTION__ . ': Failed to insert the rule.';
e673ee24
DO
914}
915
916function deletePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
917{
918 global $dbxlink;
919
920 $query =
921 "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'";
922 $result = $dbxlink->exec ($query);
923 return '';
924}
925
926function updatePortForwarding($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
927{
928 global $dbxlink;
929
930 $query =
931 "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'";
932 $result = $dbxlink->exec ($query);
933 return '';
934}
935
eeb4a5d8 936function getNATv4ForObject ($object_id)
e673ee24 937{
e673ee24
DO
938 $ret = array();
939 $ret['out'] = array();
940 $ret['in'] = array();
941 $query =
942 "select ".
eeb4a5d8 943 "proto, ".
e673ee24
DO
944 "INET_NTOA(localip) as localip, ".
945 "localport, ".
946 "INET_NTOA(remoteip) as remoteip, ".
947 "remoteport, ".
f28fbe8b
DO
948 "ipa1.name as local_addr_name, " .
949 "ipa2.name as remote_addr_name, " .
e673ee24 950 "description ".
eeb4a5d8 951 "from PortForwarding ".
f28fbe8b
DO
952 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
953 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
eeb4a5d8 954 "where object_id='$object_id' ".
e673ee24 955 "order by localip, localport, proto, remoteip, remoteport";
065eeb52 956 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 957 $count=0;
eeb4a5d8 958 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 959 {
eeb4a5d8 960 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
f28fbe8b 961 $ret['out'][$count][$cname] = $row[$cname];
e673ee24
DO
962 $count++;
963 }
eeb4a5d8
DO
964 $result->closeCursor();
965 unset ($result);
e673ee24
DO
966
967 $query =
968 "select ".
eeb4a5d8 969 "proto, ".
e673ee24
DO
970 "INET_NTOA(localip) as localip, ".
971 "localport, ".
972 "INET_NTOA(remoteip) as remoteip, ".
973 "remoteport, ".
974 "PortForwarding.object_id as object_id, ".
975 "RackObject.name as object_name, ".
976 "description ".
eeb4a5d8
DO
977 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
978 "where IPBonds.object_id='$object_id' ".
e673ee24 979 "order by remoteip, remoteport, proto, localip, localport";
065eeb52 980 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24 981 $count=0;
eeb4a5d8 982 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24 983 {
eeb4a5d8 984 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
f28fbe8b 985 $ret['in'][$count][$cname] = $row[$cname];
e673ee24
DO
986 $count++;
987 }
eeb4a5d8 988 $result->closeCursor();
e673ee24
DO
989
990 return $ret;
991}
992
c31cd72c 993// This function returns an array of single element of object's FQDN attribute,
f321b50a
DO
994// if FQDN is set. The next choice is object's common name, if it looks like a
995// hostname. Otherwise an array of all 'regular' IP addresses of the
c31cd72c 996// object is returned (which may appear 0 and more elements long).
f321b50a 997function findAllEndpoints ($object_id, $fallback = '')
c31cd72c
DO
998{
999 $values = getAttrValues ($object_id);
1000 foreach ($values as $record)
f321b50a 1001 if ($record['name'] == 'FQDN' && !empty ($record['value']))
c31cd72c
DO
1002 return array ($record['value']);
1003 $addresses = getObjectAddresses ($object_id);
1004 $regular = array();
1005 foreach ($addresses as $idx => $address)
1006 if ($address['type'] == 'regular')
fa8112d1 1007 $regular[] = $address['ip'];
f321b50a
DO
1008 if (!count ($regular) && !empty ($fallback))
1009 return array ($fallback);
c31cd72c
DO
1010 return $regular;
1011}
1012
83ba6670
DO
1013// Some records in the dictionary may be written as plain text or as Wiki
1014// link in the following syntax:
1015// 1. word
1016// 2. [[word URL]] // FIXME: this isn't working
1017// 3. [[word word word | URL]]
1018// This function parses the line and returns text suitable for either A
1019// (rendering <A HREF>) or O (for <OPTION>).
24cbe8af 1020function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
83ba6670 1021{
010231c2 1022 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
24cbe8af
DO
1023 {
1024 if ($strip_optgroup)
f0b540a3 1025 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
24cbe8af
DO
1026 else
1027 return $line;
1028 }
010231c2
DO
1029 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
1030 $s = explode ('|', $line);
83ba6670 1031 $o_value = trim ($s[0]);
24cbe8af 1032 if ($strip_optgroup)
f0b540a3 1033 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
83ba6670
DO
1034 $a_value = trim ($s[1]);
1035 if ($which == 'a')
010231c2 1036 return "<a href='${a_value}'>${o_value}</a>";
83ba6670
DO
1037 if ($which == 'o')
1038 return $o_value;
1039}
1040
2de490b7
DO
1041function buildVServiceName ($vsinfo = NULL)
1042{
1043 if ($vsinfo == NULL)
1044 {
1045 showError ('NULL argument', __FUNCTION__);
1046 return NULL;
1047 }
8d790216 1048 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
2de490b7
DO
1049}
1050
05411ccd
DO
1051function buildRSPoolName ($rspool = NULL)
1052{
1053 if ($rspool == NULL)
1054 {
1055 showError ('NULL argument', __FUNCTION__);
1056 return NULL;
1057 }
1058 return strlen ($rspool['name']) ? $rspool['name'] : 'ANONYMOUS pool';
1059}
1060
177b1e9b
DO
1061// rackspace usage for a single rack
1062// (T + W + U) / (height * 3 - A)
11df133a 1063function getRSUforRack ($data = NULL)
177b1e9b 1064{
11df133a 1065 if ($data == NULL)
177b1e9b
DO
1066 {
1067 showError ('Invalid argument', __FUNCTION__);
1068 return NULL;
1069 }
6ffba290 1070 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
9e60f7df
DO
1071 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1072 for ($locidx = 0; $locidx < 3; $locidx++)
1073 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075 1074 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
177b1e9b
DO
1075}
1076
11df133a
DO
1077// Same for row.
1078function getRSUforRackRow ($rowData = NULL)
1079{
bb26a59e 1080 if ($rowData === NULL)
11df133a
DO
1081 {
1082 showError ('Invalid argument', __FUNCTION__);
1083 return NULL;
1084 }
bb26a59e
DO
1085 if (!count ($rowData))
1086 return 0;
11df133a 1087 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
f81a2012 1088 $total_height = 0;
dfa3c075
DO
1089 foreach (array_keys ($rowData) as $rack_id)
1090 {
1091 $data = getRackData ($rack_id);
1092 $total_height += $data['height'];
11df133a
DO
1093 for ($unit_no = $data['height']; $unit_no > 0; $unit_no--)
1094 for ($locidx = 0; $locidx < 3; $locidx++)
1095 $counter[$data[$unit_no][$locidx]['state']]++;
dfa3c075
DO
1096 }
1097 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
11df133a
DO
1098}
1099
f1a0477d
DO
1100function getObjectCount ($rackData)
1101{
1102 $objects = array();
1103 for ($i = $rackData['height']; $i > 0; $i--)
1104 for ($locidx = 0; $locidx < 3; $locidx++)
1105 if
1106 (
1107 $rackData[$i][$locidx]['state'] == 'T' and
1108 !in_array ($rackData[$i][$locidx]['object_id'], $objects)
1109 )
1110 $objects[] = $rackData[$i][$locidx]['object_id'];
1111 return count ($objects);
1112}
1113
9af110b4
DO
1114// Perform substitutions and return resulting string
1115function apply_macros ($macros, $subject)
1116{
1117 $ret = $subject;
1118 foreach ($macros as $search => $replace)
1119 $ret = str_replace ($search, $replace, $ret);
1120 return $ret;
1121}
1122
1123// Make sure the string is always wrapped with LF characters
1124function lf_wrap ($str)
1125{
1126 $ret = trim ($str, "\r\n");
1127 if (!empty ($ret))
1128 $ret .= "\n";
1129 return $ret;
1130}
1131
e6e7d8b3
DO
1132// Adopted from Mantis BTS code.
1133function string_insert_hrefs ($s)
1134{
1135 if (getConfigVar ('DETECT_URLS') != 'yes')
1136 return $s;
1137 # Find any URL in a string and replace it by a clickable link
1138 $s = preg_replace( '/(([[:alpha:]][-+.[:alnum:]]*):\/\/(%[[:digit:]A-Fa-f]{2}|[-_.!~*\';\/?%^\\\\:@&={\|}+$#\(\),\[\][:alnum:]])+)/se',
1139 "'<a href=\"'.rtrim('\\1','.').'\">\\1</a> [<a href=\"'.rtrim('\\1','.').'\" target=\"_blank\">^</a>]'",
1140 $s);
1141 $s = preg_replace( '/\b' . email_regex_simple() . '\b/i',
1142 '<a href="mailto:\0">\0</a>',
1143 $s);
1144 return $s;
1145}
1146
1147// Idem.
1148function email_regex_simple ()
1149{
1150 return "(([a-z0-9!#*+\/=?^_{|}~-]+(?:\.[a-z0-9!#*+\/=?^_{|}~-]+)*)" . # recipient
1151 "\@((?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))"; # @domain
1152}
1153
118e4c38
DO
1154// Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
1155// for the requested object_type_id.
1156function getAutoPorts ($type_id)
1157{
1158 $ret = array();
1159 $typemap = explode (';', str_replace (' ', '', getConfigVar ('AUTOPORTS_CONFIG')));
1160 foreach ($typemap as $equation)
1161 {
1162 $tmp = explode ('=', $equation);
1163 if (count ($tmp) != 2)
1164 continue;
1165 $objtype_id = $tmp[0];
1166 if ($objtype_id != $type_id)
1167 continue;
1168 $portlist = $tmp[1];
1169 foreach (explode ('+', $portlist) as $product)
1170 {
1171 $tmp = explode ('*', $product);
1172 if (count ($tmp) != 3)
1173 continue;
1174 $nports = $tmp[0];
1175 $port_type = $tmp[1];
1176 $format = $tmp[2];
1177 for ($i = 0; $i < $nports; $i++)
1178 $ret[] = array ('type' => $port_type, 'name' => @sprintf ($format, $i));
1179 }
1180 }
1181 return $ret;
1182}
1183
9dfd4cc9
DO
1184// Find if a particular tag id exists on the tree, then attach the
1185// given child tag to it. If the parent tag doesn't exist, return FALSE.
1186function attachChildTag (&$tree, $parent_id, $child_id, $child_info)
1187{
1188 foreach ($tree as $tagid => $taginfo)
1189 {
1190 if ($tagid == $parent_id)
1191 {
1192 $tree[$tagid]['kids'][$child_id] = $child_info;
1193 return TRUE;
1194 }
1195 elseif (attachChildTag ($tree[$tagid]['kids'], $parent_id, $child_id, $child_info))
1196 return TRUE;
1197 }
1198 return FALSE;
1199}
1200
1201// Build a tree from the tag list and return it.
1202function getTagTree ()
1203{
20c901a7
DO
1204 global $taglist;
1205 $mytaglist = $taglist;
1206 $ret = array();
1207 while (count ($mytaglist) > 0)
9dfd4cc9
DO
1208 {
1209 $picked = FALSE;
20c901a7 1210 foreach ($mytaglist as $tagid => $taginfo)
9dfd4cc9
DO
1211 {
1212 $taginfo['kids'] = array();
1213 if ($taginfo['parent_id'] == NULL)
1214 {
20c901a7 1215 $ret[$tagid] = $taginfo;
9dfd4cc9 1216 $picked = TRUE;
20c901a7 1217 unset ($mytaglist[$tagid]);
9dfd4cc9 1218 }
20c901a7 1219 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
9dfd4cc9
DO
1220 {
1221 $picked = TRUE;
20c901a7 1222 unset ($mytaglist[$tagid]);
9dfd4cc9
DO
1223 }
1224 }
1225 if (!$picked) // Only orphaned items on the list.
1226 break;
1227 }
20c901a7 1228 return $ret;
9dfd4cc9
DO
1229}
1230
49fb1027
DO
1231// Build a tree from the tag list and return everything _except_ the tree.
1232function getOrphanedTags ()
1233{
1234 global $taglist;
1235 $mytaglist = $taglist;
1236 $dummy = array();
1237 while (count ($mytaglist) > 0)
1238 {
1239 $picked = FALSE;
1240 foreach ($mytaglist as $tagid => $taginfo)
1241 {
1242 $taginfo['kids'] = array();
1243 if ($taginfo['parent_id'] == NULL)
1244 {
1245 $dummy[$tagid] = $taginfo;
1246 $picked = TRUE;
1247 unset ($mytaglist[$tagid]);
1248 }
1249 elseif (attachChildTag ($dummy, $taginfo['parent_id'], $tagid, $taginfo))
1250 {
1251 $picked = TRUE;
1252 unset ($mytaglist[$tagid]);
1253 }
1254 }
1255 if (!$picked) // Only orphaned items on the list.
1256 return $mytaglist;
1257 }
1258 return array();
1259}
1260
6e49bd1f 1261function serializeTags ($chain, $baseurl = '')
ba93bd98
DO
1262{
1263 $comma = '';
1264 $ret = '';
6e49bd1f 1265 foreach ($chain as $taginfo)
ba93bd98 1266 {
e2ac59cf
DO
1267 $ret .= $comma .
1268 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
1269 $taginfo['tag'] .
1270 ($baseurl == '' ? '' : '</a>');
ba93bd98
DO
1271 $comma = ', ';
1272 }
1273 return $ret;
1274}
1275
6e49bd1f
DO
1276// a helper for getTagChainExpansion()
1277function traceTagChain ($tree, $chain)
ba93bd98
DO
1278{
1279 // For each tag find its path from the root, then combine items
6e49bd1f 1280 // of all paths and add them to the chain, if they aren't there yet.
ba93bd98
DO
1281 $ret = array();
1282 foreach ($tree as $taginfo1)
1283 {
1284 $hit = FALSE;
6e49bd1f 1285 foreach ($chain as $taginfo2)
ba93bd98
DO
1286 if ($taginfo1['id'] == $taginfo2['id'])
1287 {
1288 $hit = TRUE;
1289 break;
1290 }
1291 if (count ($taginfo1['kids']) > 0)
1292 {
6e49bd1f 1293 $subsearch = traceTagChain ($taginfo1['kids'], $chain);
ba93bd98
DO
1294 if (count ($subsearch))
1295 {
1296 $hit = TRUE;
1297 $ret = array_merge ($ret, $subsearch);
1298 }
1299 }
1300 if ($hit)
1301 $ret[] = $taginfo1;
1302 }
1303 return $ret;
1304}
1305
1306// For each tag add all its parent tags onto the list. Don't expect anything
6e49bd1f
DO
1307// except user's tags on the chain.
1308function getTagChainExpansion ($chain)
ba93bd98 1309{
20c901a7 1310 global $tagtree;
6e49bd1f 1311 return traceTagChain ($tagtree, $chain);
ba93bd98
DO
1312}
1313
1314// Return the list of missing implicit tags.
1315function getImplicitTags ($oldtags)
1316{
1317 $ret = array();
6e49bd1f 1318 $newtags = getTagChainExpansion ($oldtags);
ba93bd98
DO
1319 foreach ($newtags as $newtag)
1320 {
1321 $already_exists = FALSE;
1322 foreach ($oldtags as $oldtag)
1323 if ($newtag['id'] == $oldtag['id'])
1324 {
1325 $already_exists = TRUE;
1326 break;
1327 }
1328 if ($already_exists)
1329 continue;
d6089951 1330 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
ba93bd98
DO
1331 }
1332 return $ret;
1333}
1334
6e49bd1f
DO
1335// Minimize the chain: exclude all implicit tags and return the result.
1336function getExplicitTagsOnly ($chain, $tree = NULL)
ab379543 1337{
20c901a7 1338 global $tagtree;
ab379543 1339 if ($tree === NULL)
20c901a7 1340 $tree = $tagtree;
ab379543
DO
1341 $ret = array();
1342 foreach ($tree as $taginfo)
1343 {
1344 if (isset ($taginfo['kids']))
1345 {
6e49bd1f 1346 $harvest = getExplicitTagsOnly ($chain, $taginfo['kids']);
ab379543
DO
1347 if (count ($harvest) > 0)
1348 {
1349 $ret = array_merge ($ret, $harvest);
1350 continue;
1351 }
1352 }
1353 // This tag isn't implicit, test is for being explicit.
6e49bd1f 1354 foreach ($chain as $testtag)
ab379543
DO
1355 if ($taginfo['id'] == $testtag['id'])
1356 {
1357 $ret[] = $testtag;
1358 break;
1359 }
1360 }
1361 return $ret;
1362}
1363
6e49bd1f 1364// Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
74ccacff
DO
1365// Unlike other functions, this one accepts and returns a list of integer tag IDs, not
1366// a list of tag structures.
1367function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1368{
20c901a7 1369 global $tagtree;
74ccacff 1370 if ($tree === NULL)
20c901a7 1371 $tree = $tagtree;
74ccacff
DO
1372 $getallkids = $getall;
1373 $ret = array();
1374 foreach ($tree as $taginfo)
1375 {
1376 foreach ($idlist as $test_id)
1377 if ($getall or $taginfo['id'] == $test_id)
1378 {
1379 $ret[] = $taginfo['id'];
1380 // Once matched node makes all sub-nodes match, but don't make
1381 // a mistake of matching every other node at the current level.
1382 $getallkids = TRUE;
1383 break;
1384 }
1385 if (isset ($taginfo['kids']))
1386 $ret = array_merge ($ret, complementByKids ($idlist, $taginfo['kids'], $getallkids));
1387 $getallkids = FALSE;
1388 }
1389 return $ret;
1390}
1391
68225375 1392function loadRackObjectAutoTags ()
ba93bd98 1393{
2c6c7645 1394 assertUIntArg ('object_id', __FUNCTION__);
2fb24351
DO
1395 $object_id = $_REQUEST['object_id'];
1396 $oinfo = getObjectInfo ($object_id);
1397 $ret = array();
c396cbf4 1398 $ret[] = array ('tag' => '$objectid_' . $object_id);
d817ba03 1399 $ret[] = array ('tag' => '$any_object');
c396cbf4
DO
1400 if (validTagName ($oinfo['name']))
1401 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
2fb24351
DO
1402 return $ret;
1403}
1404
68225375
DO
1405// Common code for both prefix and address tag listers.
1406function getIPv4PrefixTags ($prefix)
f9bc186f 1407{
f9bc186f 1408 $ret = array();
da958e52
DO
1409 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $prefix['ip']) . '-' . $prefix['mask']);
1410 // FIXME: find and list tags for all parent networks?
1411 $ret[] = array ('tag' => '$any_ip4net');
d817ba03 1412 $ret[] = array ('tag' => '$any_net');
41bd8c87
DO
1413 return $ret;
1414}
1415
68225375 1416function loadIPv4PrefixAutoTags ()
41bd8c87 1417{
68225375
DO
1418 assertUIntArg ('id', __FUNCTION__);
1419 return array_merge
1420 (
da958e52 1421 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
68225375
DO
1422 getIPv4PrefixTags (getIPRange ($_REQUEST['id']))
1423 );
d817ba03
DO
1424}
1425
68225375 1426function loadIPv4AddressAutoTags ()
d817ba03 1427{
2c6c7645 1428 assertIPv4Arg ('ip', __FUNCTION__);
68225375
DO
1429 return array_merge
1430 (
da958e52 1431 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
68225375
DO
1432 getIPv4PrefixTags (getRangeByIP ($_REQUEST['ip']))
1433 );
1434}
1435
1436function loadRackAutoTags ()
1437{
1438 assertUIntArg ('rack_id', __FUNCTION__);
d817ba03 1439 $ret = array();
da958e52 1440 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
68225375 1441 $ret[] = array ('tag' => '$any_rack');
d817ba03
DO
1442 return $ret;
1443}
1444
68225375 1445function loadIPv4VSAutoTags ()
d817ba03 1446{
49fb2686 1447 assertUIntArg ('vs_id', __FUNCTION__);
d817ba03 1448 $ret = array();
49fb2686 1449 $ret[] = array ('tag' => '$id_' . $_REQUEST['vs_id']);
d817ba03
DO
1450 $ret[] = array ('tag' => '$any_ipv4vs');
1451 $ret[] = array ('tag' => '$any_vs');
1452 return $ret;
1453}
1454
68225375 1455function loadIPv4RSPoolAutoTags ()
d817ba03 1456{
2c6c7645 1457 assertUIntArg ('pool_id', __FUNCTION__);
d817ba03 1458 $ret = array();
6aff02cf 1459 $ret[] = array ('tag' => '$id_' . $_REQUEST['pool_id']);
d817ba03
DO
1460 $ret[] = array ('tag' => '$any_ipv4rspool');
1461 $ret[] = array ('tag' => '$any_rspool');
f9bc186f
DO
1462 return $ret;
1463}
1464
da958e52
DO
1465function fixContext ()
1466{
1467 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
1468 if (isset ($page[$pageno]['autotagloader']))
1469 $auto_tags = $page[$pageno]['autotagloader'] ();
1470 if
1471 (
1472 isset ($page[$pageno]['tagloader']) and
1473 isset ($page[$pageno]['bypass']) and
1474 isset ($_REQUEST[$page[$pageno]['bypass']])
1475 )
1476 {
1477 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1478 $impl_tags = getImplicitTags ($expl_tags);
1479 }
1480}
1481
7e525721 1482function getUserAutoTags ()
2fb24351 1483{
7e525721 1484 global $remote_username, $accounts;
2fb24351 1485 $ret = array();
2fb24351 1486 $ret[] = array ('tag' => '$username_' . $remote_username);
7e525721 1487 $ret[] = array ('tag' => '$userid_' . $accounts[$remote_username]['user_id']);
2fb24351 1488 return $ret;
ba93bd98
DO
1489}
1490
6e49bd1f
DO
1491// Build a tag chain from supplied tag id list and return it.
1492function buildTagChainFromIds ($tagidlist)
ab379543 1493{
20c901a7 1494 global $taglist;
ab379543
DO
1495 $ret = array();
1496 foreach ($tagidlist as $tag_id)
1497 if (isset ($taglist[$tag_id]))
1498 $ret[] = $taglist[$tag_id];
1499 return $ret;
1500}
1501
7cc02fc1
DO
1502// Process a given tag tree and return only meaningful branches. The resulting
1503// (sub)tree will have refcnt leaves on every last branch.
1504function getObjectiveTagTree ($tree, $realm)
1505{
1506 $ret = array();
1507 foreach ($tree as $taginfo)
1508 {
1509 $subsearch = array();
1510 $pick = FALSE;
1511 if (count ($taginfo['kids']))
1512 {
1513 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1514 $pick = count ($subsearch) > 0;
1515 }
5bdc04ec 1516 if (isset ($taginfo['refcnt'][$realm]))
7cc02fc1
DO
1517 $pick = TRUE;
1518 if (!$pick)
1519 continue;
1520 $ret[] = array
1521 (
1522 'id' => $taginfo['id'],
1523 'tag' => $taginfo['tag'],
1524 'parent_id' => $taginfo['parent_id'],
1525 'refcnt' => $taginfo['refcnt'],
1526 'kids' => $subsearch
1527 );
1528 }
1529 return $ret;
1530}
1531
a0d54e7e 1532function getTagFilter ()
7cc02fc1 1533{
a0d54e7e 1534 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
7cc02fc1
DO
1535}
1536
a0d54e7e 1537function getTagFilterStr ($tagfilter = array())
932cf41f 1538{
a0d54e7e 1539 $ret = '';
6e49bd1f 1540 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
a0d54e7e
DO
1541 $ret .= "&tagfilter[]=" . $taginfo['id'];
1542 return $ret;
932cf41f 1543}
a0d54e7e 1544
46f92ff7 1545function buildWideRedirectURL ($log, $p = NULL, $t = NULL)
da958e52 1546{
46f92ff7
DO
1547 global $root, $page, $pageno, $tabno;
1548 if ($p === NULL)
1549 $p = $pageno;
1550 if ($t === NULL)
1551 $t = $tabno;
da958e52
DO
1552 $url = "${root}?page=${pageno}&tab=${tabno}";
1553 if (isset ($page[$pageno]['bypass']))
1554 $url .= '&' . $page[$pageno]['bypass'] . '=' . $_REQUEST[$page[$pageno]['bypass']];
46f92ff7 1555 $url .= "&log=" . base64_encode (serialize ($log));
da958e52
DO
1556 return $url;
1557}
1558
46f92ff7
DO
1559function buildRedirectURL_OK ($text, $p = NULL, $t = NULL)
1560{
1561 return buildWideRedirectURL (array (array ('code' => 'success', 'message' => $text)), $p, $t);
1562}
1563
1564function buildRedirectURL_ERR ($text, $p = NULL, $t = NULL)
1565{
1566 return buildWideRedirectURL (array (array ('code' => 'error', 'message' => $text)), $p, $t);
1567}
1568
9f54e6e9 1569function validTagName ($s, $allow_autotag = FALSE)
2eeeca80 1570{
9f54e6e9
DO
1571 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1572 return TRUE;
1573 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1574 return TRUE;
1575 return FALSE;
2eeeca80
DO
1576}
1577
e673ee24 1578?>