r2072 + more changes to make compact URLs work
[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 $query .= " order by ${fieldname}";
630 $result = useSelectBlade ($query, __FUNCTION__);
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');
634 while ($row = $result->fetch (PDO::FETCH_ASSOC))
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
653 function getObjectSearchResults ($terms)
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.
666 function 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
684 function 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().
702 function getPrevIDforRack ($row_id = 0, $rack_id = 0)
703 {
704 if ($row_id <= 0 or $rack_id <= 0)
705 {
706 showError ('Invalid arguments passed', __FUNCTION__);
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
716 function getNextIDforRack ($row_id = 0, $rack_id = 0)
717 {
718 if ($row_id <= 0 or $rack_id <= 0)
719 {
720 showError ('Invalid arguments passed', __FUNCTION__);
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.
732 function 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.
748 function restoreRackIDs ($racks)
749 {
750 $ret = array();
751 foreach ($racks as $rack)
752 $ret[$rack['id']] = $rack;
753 return $ret;
754 }
755
756 function 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
797 function sortByName ($a, $b)
798 {
799 return sortTokenize($a['name'], $b['name']);
800 }
801
802 function sortRacks ($a, $b)
803 {
804 return sortTokenize($a['row_name'] . ': ' . $a['name'], $b['row_name'] . ': ' . $b['name']);
805 }
806
807 function eq ($a, $b)
808 {
809 return $a==$b;
810 }
811
812 function neq ($a, $b)
813 {
814 return $a!=$b;
815 }
816
817 function 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
828 function 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
838 function sortObjectAddressesAndNames ($a, $b)
839 {
840 $objname_cmp = sortTokenize($a['object_name'], $b['object_name']);
841 if ($objname_cmp == 0)
842 {
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);
846 if ($objname_cmp == 0)
847 sortTokenize($a['ip'], $b['ip']);
848 return $objname_cmp;
849 }
850 return $objname_cmp;
851 }
852
853
854
855 function 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.
866 function 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
878 function 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
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.';
914 }
915
916 function 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
926 function 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
936 function getNATv4ForObject ($object_id)
937 {
938 $ret = array();
939 $ret['out'] = array();
940 $ret['in'] = array();
941 $query =
942 "select ".
943 "proto, ".
944 "INET_NTOA(localip) as localip, ".
945 "localport, ".
946 "INET_NTOA(remoteip) as remoteip, ".
947 "remoteport, ".
948 "ipa1.name as local_addr_name, " .
949 "ipa2.name as remote_addr_name, " .
950 "description ".
951 "from PortForwarding ".
952 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
953 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
954 "where object_id='$object_id' ".
955 "order by localip, localport, proto, remoteip, remoteport";
956 $result = useSelectBlade ($query, __FUNCTION__);
957 $count=0;
958 while ($row = $result->fetch (PDO::FETCH_ASSOC))
959 {
960 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
961 $ret['out'][$count][$cname] = $row[$cname];
962 $count++;
963 }
964 $result->closeCursor();
965 unset ($result);
966
967 $query =
968 "select ".
969 "proto, ".
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 ".
977 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
978 "where IPBonds.object_id='$object_id' ".
979 "order by remoteip, remoteport, proto, localip, localport";
980 $result = useSelectBlade ($query, __FUNCTION__);
981 $count=0;
982 while ($row = $result->fetch (PDO::FETCH_ASSOC))
983 {
984 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
985 $ret['in'][$count][$cname] = $row[$cname];
986 $count++;
987 }
988 $result->closeCursor();
989
990 return $ret;
991 }
992
993 // This function returns an array of single element of object's FQDN attribute,
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
996 // object is returned (which may appear 0 and more elements long).
997 function findAllEndpoints ($object_id, $fallback = '')
998 {
999 $values = getAttrValues ($object_id);
1000 foreach ($values as $record)
1001 if ($record['name'] == 'FQDN' && !empty ($record['value']))
1002 return array ($record['value']);
1003 $addresses = getObjectAddresses ($object_id);
1004 $regular = array();
1005 foreach ($addresses as $idx => $address)
1006 if ($address['type'] == 'regular')
1007 $regular[] = $address['ip'];
1008 if (!count ($regular) && !empty ($fallback))
1009 return array ($fallback);
1010 return $regular;
1011 }
1012
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>).
1020 function parseWikiLink ($line, $which, $strip_optgroup = FALSE)
1021 {
1022 if (preg_match ('/^\[\[.+\]\]$/', $line) == 0)
1023 {
1024 if ($strip_optgroup)
1025 return ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $line));
1026 else
1027 return $line;
1028 }
1029 $line = preg_replace ('/^\[\[(.+)\]\]$/', '$1', $line);
1030 $s = explode ('|', $line);
1031 $o_value = trim ($s[0]);
1032 if ($strip_optgroup)
1033 $o_value = ereg_replace ('^.+%GSKIP%', '', ereg_replace ('^(.+)%GPASS%', '\\1 ', $o_value));
1034 $a_value = trim ($s[1]);
1035 if ($which == 'a')
1036 return "<a href='${a_value}'>${o_value}</a>";
1037 if ($which == 'o')
1038 return $o_value;
1039 }
1040
1041 function buildVServiceName ($vsinfo = NULL)
1042 {
1043 if ($vsinfo == NULL)
1044 {
1045 showError ('NULL argument', __FUNCTION__);
1046 return NULL;
1047 }
1048 return $vsinfo['vip'] . ':' . $vsinfo['vport'] . '/' . $vsinfo['proto'];
1049 }
1050
1051 function 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
1061 // rackspace usage for a single rack
1062 // (T + W + U) / (height * 3 - A)
1063 function getRSUforRack ($data = NULL)
1064 {
1065 if ($data == NULL)
1066 {
1067 showError ('Invalid argument', __FUNCTION__);
1068 return NULL;
1069 }
1070 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
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']]++;
1074 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
1075 }
1076
1077 // Same for row.
1078 function getRSUforRackRow ($rowData = NULL)
1079 {
1080 if ($rowData === NULL)
1081 {
1082 showError ('Invalid argument', __FUNCTION__);
1083 return NULL;
1084 }
1085 if (!count ($rowData))
1086 return 0;
1087 $counter = array ('A' => 0, 'U' => 0, 'T' => 0, 'W' => 0, 'F' => 0);
1088 $total_height = 0;
1089 foreach (array_keys ($rowData) as $rack_id)
1090 {
1091 $data = getRackData ($rack_id);
1092 $total_height += $data['height'];
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']]++;
1096 }
1097 return ($counter['T'] + $counter['W'] + $counter['U']) / ($counter['T'] + $counter['W'] + $counter['U'] + $counter['F']);
1098 }
1099
1100 function 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
1114 // Perform substitutions and return resulting string
1115 function 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
1124 function lf_wrap ($str)
1125 {
1126 $ret = trim ($str, "\r\n");
1127 if (!empty ($ret))
1128 $ret .= "\n";
1129 return $ret;
1130 }
1131
1132 // Adopted from Mantis BTS code.
1133 function 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.
1148 function 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
1154 // Parse AUTOPORTS_CONFIG and return a list of generated pairs (port_type, port_name)
1155 // for the requested object_type_id.
1156 function 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
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.
1186 function 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.
1202 function getTagTree ()
1203 {
1204 global $taglist;
1205 $mytaglist = $taglist;
1206 $ret = array();
1207 while (count ($mytaglist) > 0)
1208 {
1209 $picked = FALSE;
1210 foreach ($mytaglist as $tagid => $taginfo)
1211 {
1212 $taginfo['kids'] = array();
1213 if ($taginfo['parent_id'] == NULL)
1214 {
1215 $ret[$tagid] = $taginfo;
1216 $picked = TRUE;
1217 unset ($mytaglist[$tagid]);
1218 }
1219 elseif (attachChildTag ($ret, $taginfo['parent_id'], $tagid, $taginfo))
1220 {
1221 $picked = TRUE;
1222 unset ($mytaglist[$tagid]);
1223 }
1224 }
1225 if (!$picked) // Only orphaned items on the list.
1226 break;
1227 }
1228 return $ret;
1229 }
1230
1231 // Build a tree from the tag list and return everything _except_ the tree.
1232 function 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
1261 function serializeTags ($chain, $baseurl = '')
1262 {
1263 $comma = '';
1264 $ret = '';
1265 foreach ($chain as $taginfo)
1266 {
1267 $ret .= $comma .
1268 ($baseurl == '' ? '' : "<a href='${baseurl}tagfilter[]=${taginfo['id']}'>") .
1269 $taginfo['tag'] .
1270 ($baseurl == '' ? '' : '</a>');
1271 $comma = ', ';
1272 }
1273 return $ret;
1274 }
1275
1276 // a helper for getTagChainExpansion()
1277 function traceTagChain ($tree, $chain)
1278 {
1279 // For each tag find its path from the root, then combine items
1280 // of all paths and add them to the chain, if they aren't there yet.
1281 $ret = array();
1282 foreach ($tree as $taginfo1)
1283 {
1284 $hit = FALSE;
1285 foreach ($chain as $taginfo2)
1286 if ($taginfo1['id'] == $taginfo2['id'])
1287 {
1288 $hit = TRUE;
1289 break;
1290 }
1291 if (count ($taginfo1['kids']) > 0)
1292 {
1293 $subsearch = traceTagChain ($taginfo1['kids'], $chain);
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
1307 // except user's tags on the chain.
1308 function getTagChainExpansion ($chain)
1309 {
1310 global $tagtree;
1311 return traceTagChain ($tagtree, $chain);
1312 }
1313
1314 // Return the list of missing implicit tags.
1315 function getImplicitTags ($oldtags)
1316 {
1317 $ret = array();
1318 $newtags = getTagChainExpansion ($oldtags);
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;
1330 $ret[] = array ('id' => $newtag['id'], 'tag' => $newtag['tag'], 'parent_id' => $newtag['parent_id']);
1331 }
1332 return $ret;
1333 }
1334
1335 // Minimize the chain: exclude all implicit tags and return the result.
1336 function getExplicitTagsOnly ($chain, $tree = NULL)
1337 {
1338 global $tagtree;
1339 if ($tree === NULL)
1340 $tree = $tagtree;
1341 $ret = array();
1342 foreach ($tree as $taginfo)
1343 {
1344 if (isset ($taginfo['kids']))
1345 {
1346 $harvest = getExplicitTagsOnly ($chain, $taginfo['kids']);
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.
1354 foreach ($chain as $testtag)
1355 if ($taginfo['id'] == $testtag['id'])
1356 {
1357 $ret[] = $testtag;
1358 break;
1359 }
1360 }
1361 return $ret;
1362 }
1363
1364 // Maximize the chain: for each tag add all tags, for which it is direct or indirect parent.
1365 // Unlike other functions, this one accepts and returns a list of integer tag IDs, not
1366 // a list of tag structures.
1367 function complementByKids ($idlist, $tree = NULL, $getall = FALSE)
1368 {
1369 global $tagtree;
1370 if ($tree === NULL)
1371 $tree = $tagtree;
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
1392 function getUserAutoTags ($username = NULL)
1393 {
1394 global $remote_username, $accounts;
1395 if ($username == NULL)
1396 $username = $remote_username;
1397 $ret = array();
1398 $ret[] = array ('tag' => '$username_' . $username);
1399 if (isset ($accounts[$username]['user_id']))
1400 $ret[] = array ('tag' => '$userid_' . $accounts[$username]['user_id']);
1401 return $ret;
1402 }
1403
1404 function loadRackObjectAutoTags ()
1405 {
1406 assertUIntArg ('object_id', __FUNCTION__);
1407 $object_id = $_REQUEST['object_id'];
1408 $oinfo = getObjectInfo ($object_id);
1409 $ret = array();
1410 $ret[] = array ('tag' => '$id_' . $object_id);
1411 $ret[] = array ('tag' => '$any_object');
1412 if (validTagName ($oinfo['name']))
1413 $ret[] = array ('tag' => '$cn_' . $oinfo['name']);
1414 return $ret;
1415 }
1416
1417 // Common code for both prefix and address tag listers.
1418 function getIPv4PrefixTags ($prefix)
1419 {
1420 $ret = array();
1421 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $prefix['ip']) . '-' . $prefix['mask']);
1422 // FIXME: find and list tags for all parent networks?
1423 $ret[] = array ('tag' => '$any_ip4net');
1424 $ret[] = array ('tag' => '$any_net');
1425 return $ret;
1426 }
1427
1428 function loadIPv4PrefixAutoTags ()
1429 {
1430 assertUIntArg ('id', __FUNCTION__);
1431 return array_merge
1432 (
1433 array (array ('tag' => '$ip4netid_' . $_REQUEST['id'])),
1434 getIPv4PrefixTags (getIPRange ($_REQUEST['id']))
1435 );
1436 }
1437
1438 function loadIPv4AddressAutoTags ()
1439 {
1440 assertIPv4Arg ('ip', __FUNCTION__);
1441 return array_merge
1442 (
1443 array (array ('tag' => '$ip4net-' . str_replace ('.', '-', $_REQUEST['ip']) . '-32')),
1444 getIPv4PrefixTags (getRangeByIP ($_REQUEST['ip']))
1445 );
1446 }
1447
1448 function loadRackAutoTags ()
1449 {
1450 assertUIntArg ('rack_id', __FUNCTION__);
1451 $ret = array();
1452 $ret[] = array ('tag' => '$rackid_' . $_REQUEST['rack_id']);
1453 $ret[] = array ('tag' => '$any_rack');
1454 return $ret;
1455 }
1456
1457 function loadIPv4VSAutoTags ()
1458 {
1459 assertUIntArg ('vs_id', __FUNCTION__);
1460 $ret = array();
1461 $ret[] = array ('tag' => '$ipv4vsid_' . $_REQUEST['vs_id']);
1462 $ret[] = array ('tag' => '$any_ipv4vs');
1463 $ret[] = array ('tag' => '$any_vs');
1464 return $ret;
1465 }
1466
1467 function loadIPv4RSPoolAutoTags ()
1468 {
1469 assertUIntArg ('pool_id', __FUNCTION__);
1470 $ret = array();
1471 $ret[] = array ('tag' => '$ipv4rspid_' . $_REQUEST['pool_id']);
1472 $ret[] = array ('tag' => '$any_ipv4rsp');
1473 $ret[] = array ('tag' => '$any_rsp');
1474 return $ret;
1475 }
1476
1477 // If the page-tab-op triplet is final, make $expl_tags and $impl_tags
1478 // hold all appropriate (explicit and implicit) tags respectively.
1479 // Otherwise some limited redirection is necessary (only page and tab
1480 // names are preserved, ophandler name change isn't handled).
1481 function fixContext ()
1482 {
1483 global $pageno, $tabno, $auto_tags, $expl_tags, $impl_tags, $page;
1484
1485 $pmap = array
1486 (
1487 'accounts' => 'userlist',
1488 'rspools' => 'ipv4rsplist',
1489 'rspool' => 'ipv4rsp',
1490 'vservices' => 'ipv4vslist',
1491 'vservice' => 'ipv4vs',
1492 );
1493 $tmap = array();
1494 $tmap['objects']['newmulti'] = 'addmore';
1495 $tmap['objects']['newobj'] = 'addmore';
1496 $tmap['object']['switchvlans'] = 'livevlans';
1497 $tmap['object']['slb'] = 'editrspvs';
1498 $tmap['object']['portfwrd'] = 'nat4';
1499 $tmap['object']['network'] = 'ipv4';
1500 if (isset ($pmap[$pageno]))
1501 redirectUser ($pmap[$pageno], $tabno);
1502 if (isset ($tmap[$pageno][$tabno]))
1503 redirectUser ($pageno, $tmap[$pageno][$tabno]);
1504
1505 if (isset ($page[$pageno]['autotagloader']))
1506 $auto_tags = $page[$pageno]['autotagloader'] ();
1507 if
1508 (
1509 isset ($page[$pageno]['tagloader']) and
1510 isset ($page[$pageno]['bypass']) and
1511 isset ($_REQUEST[$page[$pageno]['bypass']])
1512 )
1513 {
1514 $expl_tags = $page[$pageno]['tagloader'] ($_REQUEST[$page[$pageno]['bypass']]);
1515 $impl_tags = getImplicitTags ($expl_tags);
1516 }
1517 }
1518
1519 // Build a tag chain from supplied tag id list and return it.
1520 function buildTagChainFromIds ($tagidlist)
1521 {
1522 global $taglist;
1523 $ret = array();
1524 foreach ($tagidlist as $tag_id)
1525 if (isset ($taglist[$tag_id]))
1526 $ret[] = $taglist[$tag_id];
1527 return $ret;
1528 }
1529
1530 // Process a given tag tree and return only meaningful branches. The resulting
1531 // (sub)tree will have refcnt leaves on every last branch.
1532 function getObjectiveTagTree ($tree, $realm)
1533 {
1534 $ret = array();
1535 foreach ($tree as $taginfo)
1536 {
1537 $subsearch = array();
1538 $pick = FALSE;
1539 if (count ($taginfo['kids']))
1540 {
1541 $subsearch = getObjectiveTagTree ($taginfo['kids'], $realm);
1542 $pick = count ($subsearch) > 0;
1543 }
1544 if (isset ($taginfo['refcnt'][$realm]))
1545 $pick = TRUE;
1546 if (!$pick)
1547 continue;
1548 $ret[] = array
1549 (
1550 'id' => $taginfo['id'],
1551 'tag' => $taginfo['tag'],
1552 'parent_id' => $taginfo['parent_id'],
1553 'refcnt' => $taginfo['refcnt'],
1554 'kids' => $subsearch
1555 );
1556 }
1557 return $ret;
1558 }
1559
1560 function getTagFilter ()
1561 {
1562 return isset ($_REQUEST['tagfilter']) ? complementByKids ($_REQUEST['tagfilter']) : array();
1563 }
1564
1565 function getTagFilterStr ($tagfilter = array())
1566 {
1567 $ret = '';
1568 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagfilter)) as $taginfo)
1569 $ret .= "&tagfilter[]=" . $taginfo['id'];
1570 return $ret;
1571 }
1572
1573 function buildWideRedirectURL ($log, $nextpage = NULL, $nexttab = NULL)
1574 {
1575 global $root, $page, $pageno, $tabno;
1576 if ($nextpage === NULL)
1577 $nextpage = $pageno;
1578 if ($nexttab === NULL)
1579 $nexttab = $tabno;
1580 $url = "${root}?page=${nextpage}&tab=${nexttab}";
1581 if (isset ($page[$nextpage]['bypass']))
1582 $url .= '&' . $page[$nextpage]['bypass'] . '=' . $_REQUEST[$page[$nextpage]['bypass']];
1583 $url .= "&log=" . urlencode (base64_encode (serialize ($log)));
1584 return $url;
1585 }
1586
1587 function buildRedirectURL ($status, $args = array(), $nextpage = NULL, $nexttab = NULL)
1588 {
1589 global $msgcode, $pageno, $tabno, $op;
1590 if ($nextpage === NULL)
1591 $nextpage = $pageno;
1592 if ($nexttab === NULL)
1593 $nexttab = $tabno;
1594 $code = $msgcode[$pageno][$tabno][$op][$status];
1595 $log = array ('v' => 2);
1596 $log['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
1597 return buildWideRedirectURL ($log, $nextpage, $nexttab);
1598 }
1599
1600 function validTagName ($s, $allow_autotag = FALSE)
1601 {
1602 if (1 == mb_ereg (TAGNAME_REGEXP, $s))
1603 return TRUE;
1604 if ($allow_autotag and 1 == mb_ereg (AUTOTAGNAME_REGEXP, $s))
1605 return TRUE;
1606 return FALSE;
1607 }
1608
1609 function redirectUser ($p, $t)
1610 {
1611 global $page, $root;
1612 $l = "{$root}?page=${p}&tab=${t}";
1613 if (isset ($page[$p]['bypass']) and isset ($_REQUEST[$page[$p]['bypass']]))
1614 $l .= '&' . $page[$p]['bypass'] . '=' . $_REQUEST[$page[$p]['bypass']];
1615 header ("Location: " . $l);
1616 die;
1617 }
1618
1619 function getRackCodeStats ()
1620 {
1621 global $rackCode;
1622 $defc = $grantc = 0;
1623 foreach ($rackCode as $s)
1624 switch ($s['type'])
1625 {
1626 case 'SYNT_DEFINITION':
1627 $defc++;
1628 break;
1629 case 'SYNT_GRANT':
1630 $grantc++;
1631 break;
1632 default:
1633 break;
1634 }
1635 $ret = array ('Definition sentences' => $defc, 'Grant sentences' => $grantc);
1636 return $ret;
1637 }
1638
1639 function getRackImageWidth ()
1640 {
1641 return 3 + getConfigVar ('rtwidth_0') + getConfigVar ('rtwidth_1') + getConfigVar ('rtwidth_2') + 3;
1642 }
1643
1644 function getRackImageHeight ($units)
1645 {
1646 return 3 + 3 + $units * 2;
1647 }
1648
1649 ?>