r1956 + merged some cleanups sent by Jonathan Thurman
[racktables] / inc / functions.php
1 <?php
2 /*
3 *
4 * This file is a library of computational functions for RackTables.
5 *
6 */
7
8 $loclist[0] = 'front';
9 $loclist[1] = 'interior';
10 $loclist[2] = 'rear';
11 $loclist['front'] = 0;
12 $loclist['interior'] = 1;
13 $loclist['rear'] = 2;
14 $template[0] = array (TRUE, TRUE, TRUE);
15 $template[1] = array (TRUE, TRUE, FALSE);
16 $template[2] = array (FALSE, TRUE, TRUE);
17 $template[3] = array (TRUE, FALSE, FALSE);
18 $template[4] = array (FALSE, TRUE, FALSE);
19 $template[5] = array (FALSE, FALSE, TRUE);
20 $templateWidth[0] = 3;
21 $templateWidth[1] = 2;
22 $templateWidth[2] = 2;
23 $templateWidth[3] = 1;
24 $templateWidth[4] = 1;
25 $templateWidth[5] = 1;
26
27 // Objects of some types should be explicitly shown as
28 // anonymous (labelless). This function is a single place where the
29 // decision about displayed name is made.
30 function displayedName ($objectData)
31 {
32 if ($objectData['name'] != '')
33 return $objectData['name'];
34 elseif (in_array ($objectData['objtype_id'], explode (',', getConfigVar ('NAMEFUL_OBJTYPES'))))
35 return "ANONYMOUS " . $objectData['objtype_name'];
36 else
37 return "[${objectData['objtype_name']}]";
38 }
39
40 // This function finds height of solid rectangle of atoms, which are all
41 // assigned to the same object. Rectangle base is defined by specified
42 // template.
43 function rectHeight ($rackData, $startRow, $template_idx)
44 {
45 $height = 0;
46 // The first met object_id is used to match all the folowing IDs.
47 $object_id = 0;
48 global $template;
49 do
50 {
51 for ($locidx = 0; $locidx < 3; $locidx++)
52 {
53 // At least one value in template is TRUE, but the following block
54 // can meet 'skipped' atoms. Let's ensure we have something after processing
55 // the first row.
56 if ($template[$template_idx][$locidx])
57 {
58 if (isset ($rackData[$startRow - $height][$locidx]['skipped']))
59 break 2;
60 if (isset ($rackData[$startRow - $height][$locidx]['rowspan']))
61 break 2;
62 if (isset ($rackData[$startRow - $height][$locidx]['colspan']))
63 break 2;
64 if ($rackData[$startRow - $height][$locidx]['state'] != 'T')
65 break 2;
66 if ($object_id == 0)
67 $object_id = $rackData[$startRow - $height][$locidx]['object_id'];
68 if ($object_id != $rackData[$startRow - $height][$locidx]['object_id'])
69 break 2;
70 }
71 }
72 // If the first row can't offer anything, bail out.
73 if ($height == 0 and $object_id == 0)
74 break;
75 $height++;
76 }
77 while ($startRow - $height > 0);
78 # echo "for startRow==${startRow} and template==(" . ($template[$template_idx][0] ? 'T' : 'F');
79 # echo ', ' . ($template[$template_idx][1] ? 'T' : 'F') . ', ' . ($template[$template_idx][2] ? 'T' : 'F');
80 # echo ") height==${height}<br>\n";
81 return $height;
82 }
83
84 // This function marks atoms to be avoided by rectHeight() and assigns rowspan/colspan
85 // attributes.
86 function markSpan (&$rackData, $startRow, $maxheight, $template_idx)
87 {
88 global $template, $templateWidth;
89 $colspan = 0;
90 for ($height = 0; $height < $maxheight; $height++)
91 {
92 for ($locidx = 0; $locidx < 3; $locidx++)
93 {
94 if ($template[$template_idx][$locidx])
95 {
96 // Add colspan/rowspan to the first row met and mark the following ones to skip.
97 // Explicitly show even single-cell spanned atoms, because rectHeight()
98 // is expeciting this data for correct calculation.
99 if ($colspan != 0)
100 $rackData[$startRow - $height][$locidx]['skipped'] = TRUE;
101 else
102 {
103 $colspan = $templateWidth[$template_idx];
104 if ($colspan >= 1)
105 $rackData[$startRow - $height][$locidx]['colspan'] = $colspan;
106 if ($maxheight >= 1)
107 $rackData[$startRow - $height][$locidx]['rowspan'] = $maxheight;
108 }
109 }
110 }
111 }
112 return;
113 }
114
115 // This function sets rowspan/solspan/skipped atom attributes for renderRack()
116 // What we actually have to do is to find _all_ possible rectangles for each unit
117 // and then select the widest of those with the maximal square.
118 function markAllSpans (&$rackData = NULL)
119 {
120 if ($rackData == NULL)
121 {
122 showError ('Invalid rackData', __FUNCTION__);
123 return;
124 }
125 for ($i = $rackData['height']; $i > 0; $i--)
126 while (markBestSpan ($rackData, $i));
127 }
128
129 // Calculate height of 6 possible span templates (array is presorted by width
130 // descending) and mark the best (if any).
131 function markBestSpan (&$rackData, $i)
132 {
133 global $template, $templateWidth;
134 for ($j = 0; $j < 6; $j++)
135 {
136 $height[$j] = rectHeight ($rackData, $i, $j);
137 $square[$j] = $height[$j] * $templateWidth[$j];
138 }
139 // find the widest rectangle of those with maximal height
140 $maxsquare = max ($square);
141 if (!$maxsquare)
142 return FALSE;
143 $best_template_index = 0;
144 for ($j = 0; $j < 6; $j++)
145 if ($square[$j] == $maxsquare)
146 {
147 $best_template_index = $j;
148 $bestheight = $height[$j];
149 break;
150 }
151 // distribute span marks
152 markSpan ($rackData, $i, $bestheight, $best_template_index);
153 return TRUE;
154 }
155
156 // We can mount 'F' atoms and unmount our own 'T' atoms.
157 function 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.
175 function 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'.
191 function 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.
207 function 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).
223 function 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.
238 function 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.
256 function 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
272 function 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
287 function 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
302 function getIPRange ($id = 0)
303 {
304 global $dbxlink;
305 $query =
306 "select ".
307 "id as IPRanges_id, ".
308 "INET_NTOA(ip) as IPRanges_ip, ".
309 "mask as IPRanges_mask, ".
310 "name as IPRanges_name ".
311 "from IPRanges ".
312 "where id = '$id'";
313 $result = useSelectBlade ($query, __FUNCTION__);
314 $ret = array();
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'];
320 $ret['ip_bin'] = ip2long ($row['IPRanges_ip']);
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();
326 $result->closeCursor();
327 unset ($result);
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'])) . "'";
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.
336 $query =
337 "select INET_NTOA(ip) as ip, name, reserved from IPAddress " .
338 "where ip between ${db_first} and ${db_last} " .
339 "and (reserved = 'yes' or name != '')";
340 $result = $dbxlink->query ($query);
341 while ($row = $result->fetch (PDO::FETCH_ASSOC))
342 {
343 $ip_bin = ip2long ($row['ip']);
344 $ret['addrlist'][$ip_bin] = $row;
345 $tmp = array();
346 foreach (array ('ip', 'name', 'reserved') as $cname)
347 $tmp[$cname] = $row[$cname];
348 $tmp['references'] = array();
349 $tmp['lbrefs'] = array();
350 $tmp['rsrefs'] = array();
351 $ret['addrlist'][$ip_bin] = $tmp;
352 }
353 $result->closeCursor();
354 unset ($result);
355
356 $query =
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 " .
360 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
361 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
362 "where ip between ${db_first} and ${db_last} " .
363 "and chapter_name = 'RackObjectType'" .
364 "order by ipb.type, object_name";
365 $result = useSelectBlade ($query, __FUNCTION__);
366 while ($row = $result->fetch (PDO::FETCH_ASSOC))
367 {
368 $ip_bin = ip2long ($row['ip']);
369 if (!isset ($ret['addrlist'][$ip_bin]))
370 {
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();
376 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
377 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
378 }
379 $tmp = array();
380 foreach (array ('object_id', 'type', 'name') as $cname)
381 $tmp[$cname] = $row[$cname];
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);
386 $ret['addrlist'][$ip_bin]['references'][] = $tmp;
387 }
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";
400 $result = useSelectBlade ($query, __FUNCTION__);
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";
429 $result = useSelectBlade ($query, __FUNCTION__);
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 }
448
449 return $ret;
450 }
451
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.
455 function getIPAddress ($ip = 0)
456 {
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 );
468 $query =
469 "select ".
470 "name, reserved ".
471 "from IPAddress ".
472 "where ip = INET_ATON('$ip') and (reserved = 'yes' or name != '')";
473 $result = useSelectBlade ($query, __FUNCTION__);
474 if ($row = $result->fetch (PDO::FETCH_ASSOC))
475 {
476 $ret['exists'] = 1;
477 $ret['name'] = $row['name'];
478 $ret['reserved'] = $row['reserved'];
479 }
480 $result->closeCursor();
481 unset ($result);
482
483 $query =
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";
495 $result = useSelectBlade ($query, __FUNCTION__);
496 $count = 0;
497 while ($row = $result->fetch (PDO::FETCH_ASSOC))
498 {
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;
509 }
510 $result->closeCursor();
511 unset ($result);
512
513 $query = "select id, vport, proto, name from IPVirtualService where vip = inet_aton('${ip}')";
514 $result = useSelectBlade ($query, __FUNCTION__);
515 while ($row = $result->fetch (PDO::FETCH_ASSOC))
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}')";
527 $result = useSelectBlade ($query, __FUNCTION__);
528 while ($row = $result->fetch (PDO::FETCH_ASSOC))
529 {
530 $new = $row;
531 $new['rsip'] = $ip;
532 $ret['rslist'][] = $new;
533 }
534 $result->closeCursor();
535 unset ($result);
536
537 $query =
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__);
549 while ($row = $result->fetch (PDO::FETCH_ASSOC))
550 {
551 if ($row['remoteip'] == $ip)
552 $ret['inpf'][] = $row;
553 if ($row['localip'] == $ip)
554 $ret['outpf'][] = $row;
555 }
556 $result->closeCursor();
557 unset ($result);
558
559 return $ret;
560 }
561
562 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
563 {
564 global $dbxlink;
565
566 $range = getRangeByIp ($ip);
567 if (!$range)
568 return 'Non-existant ip address. Try adding IP range first';
569
570 $result = useInsertBlade
571 (
572 'IPBonds',
573 array
574 (
575 'ip' => "INET_ATON('$ip')",
576 'object_id' => "'${object_id}'",
577 'name' => "'${name}'",
578 'type' => "'${type}'"
579 )
580 );
581 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
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.
588 function 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
606 function 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.
615 function 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 }
629 $result = useSelectBlade ($query, __FUNCTION__);
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');
633 while ($row = $result->fetch (PDO::FETCH_ASSOC))
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
652 function getObjectSearchResults ($terms)
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.
665 function 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
683 function 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().
701 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
702 {
703 if ($row_id <= 0 or $rack_id <= 0)
704 {
705 showError ('Invalid arguments passed', __FUNCTION__);
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
715 function getNextIDforRack ($row_id = 0, $rack_id = 0)
716 {
717 if ($row_id <= 0 or $rack_id <= 0)
718 {
719 showError ('Invalid arguments passed', __FUNCTION__);
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.
731 function 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.
747 function restoreRackIDs ($racks)
748 {
749 $ret = array();
750 foreach ($racks as $rack)
751 $ret[$rack['id']] = $rack;
752 return $ret;
753 }
754
755 function 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
796 function sortByName ($a, $b)
797 {
798 return sortTokenize($a['name'], $b['name']);
799 }
800
801 function sortRacks ($a, $b)
802 {
803 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
804 }
805
806 function eq ($a, $b)
807 {
808 return $a==$b;
809 }
810
811 function neq ($a, $b)
812 {
813 return $a!=$b;
814 }
815
816 function 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
827 function 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
837 function sortObjectAddressesAndNames ($a, $b)
838 {
839 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
840 if ($objname_cmp == 0)
841 {
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);
845 if ($objname_cmp == 0)
846 sortTokenize($a['ip'], $b['ip']);
847 return $objname_cmp;
848 }
849 return $objname_cmp;
850 }
851
852
853
854 function 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.
865 function 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
877 function 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
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.';
913 }
914
915 function 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
925 function 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
935 function getNATv4ForObject ($object_id)
936 {
937 $ret = array();
938 $ret['out'] = array();
939 $ret['in'] = array();
940 $query =
941 "select ".
942 "proto, ".
943 "INET_NTOA(localip) as localip, ".
944 "localport, ".
945 "INET_NTOA(remoteip) as remoteip, ".
946 "remoteport, ".
947 "ipa1.name as local_addr_name, " .
948 "ipa2.name as remote_addr_name, " .
949 "description ".
950 "from PortForwarding ".
951 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
952 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
953 "where object_id='$object_id' ".
954 "order by localip, localport, proto, remoteip, remoteport";
955 $result = useSelectBlade ($query, __FUNCTION__);
956 $count=0;
957 while ($row = $result->fetch (PDO::FETCH_ASSOC))
958 {
959 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
960 $ret['out'][$count][$cname] = $row[$cname];
961 $count++;
962 }
963 $result->closeCursor();
964 unset ($result);
965
966 $query =
967 "select ".
968 "proto, ".
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 ".
976 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
977 "where IPBonds.object_id='$object_id' ".
978 "order by remoteip, remoteport, proto, localip, localport";
979 $result = useSelectBlade ($query, __FUNCTION__);
980 $count=0;
981 while ($row = $result->fetch (PDO::FETCH_ASSOC))
982 {
983 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
984 $ret['in'][$count][$cname] = $row[$cname];
985 $count++;
986 }
987 $result->closeCursor();
988
989 return $ret;
990 }
991
992 // This function returns an array of single element of object's FQDN attribute,
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
995 // object is returned (which may appear 0 and more elements long).
996 function findAllEndpoints ($object_id, $fallback = '')
997 {
998 $values = getAttrValues ($object_id);
999 foreach ($values as $record)
1000 if ($record['name'] == 'FQDN' && !empty ($record['value']))
1001 return array ($record['value']);
1002 $addresses = getObjectAddresses ($object_id);
1003 $regular = array();
1004 foreach ($addresses as $idx => $address)
1005 if ($address['type'] == 'regular')
1006 $regular[] = $address['ip'];
1007 if (!count ($regular) && !empty ($fallback))
1008 return array ($fallback);
1009 return $regular;
1010 }
1011
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>).
1019 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
1020 {
1021 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
1022 {
1023 if ($strip_optgroup)
1024 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
1025 else
1026 return $line;
1027 }
1028 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
1029 $s = explode ('|', $line);
1030 $o_value = trim ($s[0]);
1031 if ($strip_optgroup)
1032 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
1033 $a_value = trim ($s[1]);
1034 if ($which == 'a')
1035 return "<a href='${a_value}'>${o_value}</a>";
1036 if ($which == 'o')
1037 return $o_value;
1038 }
1039
1040 function buildVServiceName ($vsinfo = NULL)
1041 {
1042 if ($vsinfo == NULL)
1043 {
1044 showError ('NULL argument', __FUNCTION__);
1045 return NULL;
1046 }
1047 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
1048 }
1049
1050 function 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
1060 // rackspace usage for a single rack
1061 // (T + W + U) / (height * 3 - A)
1062 function getRSUforRack ($data = NULL)
1063 {
1064 if ($data == NULL)
1065 {
1066 showError ('Invalid argument', __FUNCTION__);
1067 return NULL;
1068 }
1069 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
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']]++;
1073 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
1074 }
1075
1076 // Same for row.
1077 function getRSUforRackRow ($rowData = NULL)
1078 {
1079 if ($rowData === NULL)
1080 {
1081 showError ('Invalid argument', __FUNCTION__);
1082 return NULL;
1083 }
1084 if (!count ($rowData))
1085 return 0;
1086 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
1087 $total_height = 0;
1088 foreach (array_keys ($rowData) as $rack_id)
1089 {
1090 $data = getRackData ($rack_id);
1091 $total_height += $data['height'];
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']]++;
1095 }
1096 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
1097 }
1098
1099 function 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
1113 // Perform substitutions and return resulting string
1114 function 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
1123 function lf_wrap ($str)
1124 {
1125 $ret = trim ($str, "\r\n");
1126 if (!empty ($ret))
1127 $ret .= "\n";
1128 return $ret;
1129 }
1130
1131 // Adopted from Mantis BTS code.
1132 function 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.
1147 function 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
1153 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
1154 // for the requested object_type_id.
1155 function 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
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.
1185 function 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.
1201 function getTagTree ()
1202 {
1203 global $taglist;
1204 $mytaglist = $taglist;
1205 $ret = array();
1206 while (count ($mytaglist) > 0)
1207 {
1208 $picked = FALSE;
1209 foreach ($mytaglist as $tagid => $taginfo)
1210 {
1211 $taginfo['kids'] = array();
1212 if ($taginfo['parent_id'] == NULL)
1213 {
1214 $ret[$tagid] = $taginfo;
1215 $picked = TRUE;
1216 unset ($mytaglist[$tagid]);
1217 }
1218 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
1219 {
1220 $picked = TRUE;
1221 unset ($mytaglist[$tagid]);
1222 }
1223 }
1224 if (!$picked) // Only orphaned items on the list.
1225 break;
1226 }
1227 return $ret;
1228 }
1229
1230 // Build a tree from the tag list and return everything _except_ the tree.
1231 function 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
1260 function serializeTags ($trail, $baseurl = '')
1261 {
1262 $comma = '';
1263 $ret = '';
1264 foreach ($trail as $taginfo)
1265 {
1266 $ret .= $comma .
1267 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
1268 $taginfo['tag'] .
1269 ($baseurl == '' ? '' : '</a>');
1270 $comma = ', ';
1271 }
1272 return $ret;
1273 }
1274
1275 // a helper for getTrailExpansion()
1276 function 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.
1307 function getTrailExpansion ($trail)
1308 {
1309 global $tagtree;
1310 return traceTrail ($tagtree, $trail);
1311 }
1312
1313 // Return the list of missing implicit tags.
1314 function 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;
1329 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
1330 }
1331 return $ret;
1332 }
1333
1334 // Minimize the trail: exclude all implicit tags and return the resulting trail.
1335 function getExplicitTagsOnly ($trail, $tree = NULL)
1336 {
1337 global $tagtree;
1338 if ($tree === NULL)
1339 $tree = $tagtree;
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
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.
1366 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1367 {
1368 global $tagtree;
1369 if ($tree === NULL)
1370 $tree = $tagtree;
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
1391 function loadRackObjectAutoTags ()
1392 {
1393 assertUIntArg ('object_id', __FUNCTION__);
1394 $object_id = $_REQUEST['object_id'];
1395 $oinfo = getObjectInfo ($object_id);
1396 $ret = array();
1397 $ret[] = array ('tag' => '$id_' . $_REQUEST['object_id']);
1398 $ret[] = array ('tag' => '$any_object');
1399 return $ret;
1400 }
1401
1402 // Common code for both prefix and address tag listers.
1403 function getIPv4PrefixTags ($prefix)
1404 {
1405 $ret = array();
1406 $ret[] = array ('tag' => '$ipv4net-' . str_replace ('.', '-', $prefix['ip']) . '-' . $prefix['mask']);
1407 // FIXME: find and list tags for all parent networks
1408 $ret[] = array ('tag' => '$any_ipv4net');
1409 $ret[] = array ('tag' => '$any_net');
1410 return $ret;
1411 }
1412
1413 function loadIPv4PrefixAutoTags ()
1414 {
1415 assertUIntArg ('id', __FUNCTION__);
1416 return array_merge
1417 (
1418 array (array ('tag' => '$id_' . $_REQUEST['id'])),
1419 getIPv4PrefixTags (getIPRange ($_REQUEST['id']))
1420 );
1421 }
1422
1423 function loadIPv4AddressAutoTags ()
1424 {
1425 assertIPv4Arg ('ip', __FUNCTION__);
1426 return array_merge
1427 (
1428 array (array ('tag' => '$ipv4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
1429 getIPv4PrefixTags (getRangeByIP ($_REQUEST['ip']))
1430 );
1431 }
1432
1433 function loadRackAutoTags ()
1434 {
1435 assertUIntArg ('rack_id', __FUNCTION__);
1436 $ret = array();
1437 $ret[] = array ('tag' => '$id_' . $_REQUEST['rack_id']);
1438 $ret[] = array ('tag' => '$any_rack');
1439 return $ret;
1440 }
1441
1442 function loadIPv4VSAutoTags ()
1443 {
1444 assertUIntArg ('id', __FUNCTION__);
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
1452 function loadIPv4RSPoolAutoTags ()
1453 {
1454 assertUIntArg ('pool_id', __FUNCTION__);
1455 $ret = array();
1456 $ret[] = array ('tag' => '$id_' . $_REQUEST['pool_id']);
1457 $ret[] = array ('tag' => '$any_ipv4rspool');
1458 $ret[] = array ('tag' => '$any_rspool');
1459 return $ret;
1460 }
1461
1462 function getGlobalAutoTags ()
1463 {
1464 global $remote_username, $accounts;
1465 $ret = array();
1466 $user_id = 0;
1467 foreach ($accounts as $a)
1468 if ($a['user_name'] == $remote_username)
1469 {
1470 $user_id = $a['user_id'];
1471 break;
1472 }
1473 $ret[] = array ('tag' => '$username_' . $remote_username);
1474 $ret[] = array ('tag' => '$userid_' . $user_id);
1475 return $ret;
1476 }
1477
1478 // Build a tag trail from supplied tag id list and return it.
1479 function buildTrailFromIds ($tagidlist)
1480 {
1481 global $taglist;
1482 $ret = array();
1483 foreach ($tagidlist as $tag_id)
1484 if (isset ($taglist[$tag_id]))
1485 $ret[] = $taglist[$tag_id];
1486 return $ret;
1487 }
1488
1489 // Process a given tag tree and return only meaningful branches. The resulting
1490 // (sub)tree will have refcnt leaves on every last branch.
1491 function getObjectiveTagTree ($tree, $realm)
1492 {
1493 $ret = array();
1494 foreach ($tree as $taginfo)
1495 {
1496 $subsearch = array();
1497 $pick = FALSE;
1498 if (count ($taginfo['kids']))
1499 {
1500 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1501 $pick = count ($subsearch) > 0;
1502 }
1503 if (isset ($taginfo['refcnt'][$realm]))
1504 $pick = TRUE;
1505 if (!$pick)
1506 continue;
1507 $ret[] = array
1508 (
1509 'id' => $taginfo['id'],
1510 'tag' => $taginfo['tag'],
1511 'parent_id' => $taginfo['parent_id'],
1512 'refcnt' => $taginfo['refcnt'],
1513 'kids' => $subsearch
1514 );
1515 }
1516 return $ret;
1517 }
1518
1519 function getTagFilter ()
1520 {
1521 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
1522 }
1523
1524 function getTagFilterStr ($tagfilter = array())
1525 {
1526 $ret = '';
1527 foreach (getExplicitTagsOnly (buildTrailFromIds ($tagfilter)) as $taginfo)
1528 $ret .= "&tagfilter[]=" . $taginfo['id'];
1529 return $ret;
1530 }
1531
1532 ?>