cover comments too in IPv4 search (Mantis#1773)
[racktables] / wwwroot / inc / database.php
1 <?php
2
3 # This file is a part of RackTables, a datacenter and server room management
4 # framework. See accompanying file "COPYING" for the full copyright and
5 # licensing information.
6
7 /*
8 *
9 * This file is a library of database access functions for RackTables.
10 *
11 */
12
13 $SQLSchema = array
14 (
15 'object' => array
16 (
17 'table' => 'RackObject',
18 'columns' => array
19 (
20 'id' => 'id',
21 'name' => 'name',
22 'label' => 'label',
23 'asset_no' => 'asset_no',
24 'objtype_id' => 'objtype_id',
25 'rack_id' => '(SELECT MIN(rack_id) FROM RackSpace WHERE object_id = RackObject.id)',
26 'rack_id_2' => "(SELECT MIN(parent_entity_id) FROM EntityLink WHERE child_entity_type='object' AND child_entity_id = RackObject.id AND parent_entity_type = 'rack')",
27 'container_id' => "(SELECT MIN(parent_entity_id) FROM EntityLink WHERE child_entity_type='object' AND child_entity_id = RackObject.id AND parent_entity_type = 'object')",
28 'container_name' => '(SELECT name FROM RackObject WHERE id = container_id)',
29 'container_objtype_id' => '(SELECT objtype_id FROM RackObject WHERE id = container_id)',
30 'has_problems' => 'has_problems',
31 'comment' => 'comment',
32 'nports' => '(SELECT COUNT(*) FROM Port WHERE object_id = RackObject.id)',
33 '8021q_domain_id' => '(SELECT domain_id FROM VLANSwitch WHERE object_id = id LIMIT 1)',
34 '8021q_template_id' => '(SELECT template_id FROM VLANSwitch WHERE object_id = id LIMIT 1)',
35 ),
36 'keycolumn' => 'id',
37 'ordcolumns' => array ('RackObject.name'),
38 ),
39 'user' => array
40 (
41 'table' => 'UserAccount',
42 'columns' => array
43 (
44 'user_id' => 'user_id',
45 'user_name' => 'user_name',
46 'user_password_hash' => 'user_password_hash',
47 'user_realname' => 'user_realname',
48 ),
49 'keycolumn' => 'user_id',
50 'ordcolumns' => array ('UserAccount.user_name'),
51 ),
52 'ipv4net' => array
53 (
54 'table' => 'IPv4Network',
55 'columns' => array
56 (
57 'id' => 'id',
58 'ip_bin' => 'ip',
59 'mask' => 'mask',
60 'name' => 'name',
61 'comment' => 'comment',
62 '8021q' => '(SELECT GROUP_CONCAT(CONCAT(domain_id, "-", vlan_id) ORDER BY domain_id, vlan_id) FROM VLANIPv4 WHERE ipv4net_id = id)',
63 ),
64 'keycolumn' => 'id',
65 'ordcolumns' => array ('IPv4Network.ip', 'IPv4Network.mask'),
66 ),
67 'ipv6net' => array
68 (
69 'table' => 'IPv6Network',
70 'columns' => array
71 (
72 'id' => 'id',
73 'ip_bin' => 'ip',
74 'mask' => 'mask',
75 'name' => 'name',
76 'comment' => 'comment',
77 '8021q' => '(SELECT GROUP_CONCAT(CONCAT(domain_id, "-", vlan_id) ORDER BY domain_id, vlan_id) FROM VLANIPv6 WHERE ipv6net_id = id)',
78 ),
79 'keycolumn' => 'id',
80 'ordcolumns' => array ('IPv6Network.ip', 'IPv6Network.mask'),
81 ),
82 'file' => array
83 (
84 'table' => 'File',
85 'columns' => array
86 (
87 'id' => 'id',
88 'name' => 'name',
89 'type' => 'type',
90 'size' => 'size',
91 'ctime' => 'ctime',
92 'mtime' => 'mtime',
93 'atime' => 'atime',
94 'comment' => 'comment',
95 ),
96 'keycolumn' => 'id',
97 'ordcolumns' => array ('File.name'),
98 ),
99 'ipv4vs' => array
100 (
101 'table' => 'IPv4VS',
102 'columns' => array
103 (
104 'id' => 'id',
105 'vip_bin' => 'vip',
106 'vport' => 'vport',
107 'proto' => 'proto',
108 'name' => 'name',
109 'vsconfig' => 'vsconfig',
110 'rsconfig' => 'rsconfig',
111 'refcnt' => '(select count(vs_id) from IPv4LB where vs_id = id)',
112 //'vip' =>
113 //'dname' =>
114 ),
115 'keycolumn' => 'id',
116 'ordcolumns' => array ('IPv4VS.vip', 'IPv4VS.proto', 'IPv4VS.vport'),
117 ),
118 'ipvs' => array
119 (
120 'table' => 'VS',
121 'columns' => array
122 (
123 'id' => 'id',
124 'name' => 'name',
125 'vsconfig' => 'vsconfig',
126 'rsconfig' => 'rsconfig',
127 ),
128 'keycolumn' => 'id',
129 ),
130 'ipv4rspool' => array
131 (
132 'table' => 'IPv4RSPool',
133 'columns' => array
134 (
135 'id' => 'id',
136 'name' => 'name',
137 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
138 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
139 'vsconfig' => 'vsconfig',
140 'rsconfig' => 'rsconfig',
141 ),
142 'keycolumn' => 'id',
143 'ordcolumns' => array ('IPv4RSPool.name', 'IPv4RSPool.id'),
144 ),
145 'rack' => array
146 (
147 'table' => 'Rack',
148 'columns' => array
149 (
150 'id' => 'id',
151 'name' => 'name',
152 'height' => 'height',
153 'asset_no' => 'asset_no',
154 'has_problems' => 'has_problems',
155 'comment' => 'comment',
156 'row_id' => 'row_id',
157 'row_name' => 'row_name',
158 'location_id' => 'location_id',
159 'location_name' => 'location_name',
160 ),
161 'keycolumn' => 'id',
162 'ordcolumns' => array ('location_name', 'row_name', 'sort_order', 'Rack.name'),
163 'pidcolumn' => 'row_id',
164 ),
165 'row' => array
166 (
167 'table' => 'Row',
168 'columns' => array
169 (
170 'id' => 'id',
171 'name' => 'name',
172 'location_id' => 'location_id',
173 'location_name' => 'location_name',
174 'rackc' => '(select count(Rack.id) from Rack where row_id = Row.id)',
175 ),
176 'keycolumn' => 'id',
177 'ordcolumns' => array ('location_name', 'name'),
178 ),
179 'location' => array
180 (
181 'table' => 'Location',
182 'columns' => array
183 (
184 'id' => 'id',
185 'name' => 'name',
186 'has_problems' => 'has_problems',
187 'comment' => 'comment',
188 'parent_id' => 'parent_id',
189 'parent_name' => 'parent_name',
190 'refcnt' => "(SELECT COUNT(child_entity_id) FROM EntityLink EL WHERE EL.parent_entity_type = 'location' AND EL.parent_entity_id = Location.id)",
191 ),
192 'keycolumn' => 'id',
193 'ordcolumns' => array ('name'),
194 ),
195 'vst' => array
196 (
197 'table' => 'VLANSwitchTemplate',
198 'columns' => array
199 (
200 'id' => 'id',
201 'description' => 'description',
202 'mutex_rev' => 'mutex_rev',
203 'saved_by' => 'saved_by',
204 'switchc' => '(SELECT COUNT(object_id) FROM VLANSwitch WHERE template_id = id)',
205 'rulec' => '(SELECT COUNT(rule_no) FROM VLANSTRule WHERE vst_id = id)',
206 ),
207 'keycolumn' => 'id',
208 'ordcolumns' => array ('description'),
209 ),
210 );
211
212 $searchfunc = array
213 (
214 'object' => array
215 (
216 'by_port' => 'getPortSearchResults',
217 'by_attr' => 'getObjectAttrsSearchResults',
218 'by_iface' => 'getObjectIfacesSearchResults',
219 'by_nat' => 'getObjectNATSearchResults',
220 'by_cableid' => 'searchCableIDs',
221 ),
222 );
223
224 $tablemap_8021q = array
225 (
226 'desired' => array
227 (
228 'pvm' => 'PortVLANMode',
229 'pav' => 'PortAllowedVLAN',
230 'pnv' => 'PortNativeVLAN',
231 ),
232 'cached' => array
233 (
234 'pvm' => 'CachedPVM',
235 'pav' => 'CachedPAV',
236 'pnv' => 'CachedPNV',
237 ),
238 );
239
240 // VST roles
241 $port_role_options = array
242 (
243 'none' => 'none',
244 'access' => 'user: access only',
245 'trunk' => 'user: trunk only',
246 'anymode' => 'user: any mode',
247 'uplink' => 'system: uplink trunk',
248 'downlink' => 'system: downlink trunk',
249 );
250
251 // flags to pass to scanIPSpace, scanIPv4Space, scanIPv6Space
252 define ('IPSCAN_DO_ADDR', 1 << 0);
253 define ('IPSCAN_DO_ALLOCS', 1 << 1);
254 define ('IPSCAN_DO_VS', 1 << 2);
255 define ('IPSCAN_DO_RS', 1 << 3);
256 define ('IPSCAN_DO_NAT', 1 << 4);
257 define ('IPSCAN_DO_LOG', 1 << 5);
258 define ('IPSCAN_RTR_ONLY', 1 << 6);
259
260 define ('IPSCAN_ANY', -1 ^ IPSCAN_RTR_ONLY);
261 define ('IPSCAN_DO_SLB', IPSCAN_DO_VS | IPSCAN_DO_RS);
262
263 $object_attribute_cache = array();
264
265 // Return list of locations directly under a specified location
266 function getLocations ($location_id)
267 {
268 $result = usePreparedSelectBlade
269 (
270 'SELECT id, name FROM Location WHERE parent_id = ? ORDER BY name',
271 array ($location_id)
272 );
273 return reduceSubarraysToColumn (reindexById ($result->fetchAll (PDO::FETCH_ASSOC)), 'name');
274 }
275
276 // Return detailed information about one rack row.
277 function getRowInfo ($row_id)
278 {
279 $query =
280 "SELECT Row.id AS id, Row.name AS name, COUNT(Rack.id) AS count, " .
281 "IF(ISNULL(SUM(Rack.height)),0,SUM(Rack.height)) AS sum, " .
282 "Location.id AS location_id, Location.name AS location " .
283 "FROM Row LEFT JOIN Rack ON Rack.row_id = Row.id " .
284 "LEFT OUTER JOIN Location ON Row.location_id = Location.id " .
285 "WHERE Row.id = ? " .
286 "GROUP BY Row.id, Location.id";
287 $result = usePreparedSelectBlade ($query, array ($row_id));
288 if ($row = $result->fetch (PDO::FETCH_ASSOC))
289 return $row;
290 throw new EntityNotFoundException ('rackrow', $row_id);
291 }
292
293 // TODO: deprecated function. delete it
294 function getAllRows ()
295 {
296 return listCells ('row');
297 }
298
299 // Return list of rows directly under a specified location
300 function getRows ($location_id)
301 {
302 $result = usePreparedSelectBlade
303 (
304 'SELECT R.id, R.name FROM Row R ' .
305 'INNER JOIN EntityLink EL ON ' .
306 "EL.parent_entity_type = 'location' " .
307 "AND EL.child_entity_type = 'row' " .
308 "AND EL.child_entity_id = R.id " .
309 'WHERE EL.parent_entity_id = ? ' .
310 'ORDER BY R.name',
311 array ($location_id)
312 );
313 return reduceSubarraysToColumn (reindexById ($result->fetchAll (PDO::FETCH_ASSOC)), 'name');
314 }
315
316 function getRacks ($row_id)
317 {
318 $result = usePreparedSelectBlade
319 (
320 'SELECT id, name, asset_no, height, sort_order, comment, row_name FROM Rack WHERE row_id = ? ORDER BY sort_order',
321 array ($row_id)
322 );
323 return reindexById ($result->fetchAll (PDO::FETCH_ASSOC));
324 }
325
326 # Return rack and row details for those objects on the list that have
327 # at least one rackspace atom allocated to them.
328 function getMountInfo ($object_ids)
329 {
330 if (! count ($object_ids))
331 return array();
332 # In theory number of involved racks can be equal or even greater, than the
333 # number of objects, but in practice it will often be tens times less. Hence
334 # the scope of the 1st pass is to tell IDs of all involved racks without
335 # fetching lots of duplicate data.
336 $result = usePreparedSelectBlade
337 (
338 'SELECT object_id, rack_id ' .
339 'FROM RackSpace ' .
340 'WHERE object_id IN(' . questionMarks (count ($object_ids)) . ') ' .
341 'GROUP BY object_id, rack_id ' .
342 'UNION ' .
343 'SELECT child_entity_id AS object_id, parent_entity_id AS rack_id ' .
344 'FROM EntityLink ' .
345 'WHERE child_entity_id IN(' . questionMarks (count ($object_ids)) . ') ' .
346 "AND parent_entity_type = 'rack' AND child_entity_type = 'object' " .
347 'ORDER BY rack_id ASC',
348 array_merge($object_ids, $object_ids)
349 );
350 $rackidlist = $objectlist = array();
351 foreach ($result as $row)
352 {
353 $objectlist[$row['object_id']][] = $row['rack_id'];
354 $rackidlist[] = $row['rack_id'];
355 }
356 unset ($result);
357 # short-cut to exit in case no object had rackspace allocated
358 if (! count ($rackidlist))
359 {
360 $ret = array();
361 foreach ($object_ids as $object_id)
362 $ret[$object_id] = array();
363 return $ret;
364 }
365 # Pass 2. Fetch shorter, but better extra data about the rows and racks,
366 # set displayed names for both.
367 $result = usePreparedSelectBlade
368 (
369 'SELECT Rack_.id as rack_id, Rack_.name AS rack_name, Rack_.label as rack_label, ' .
370 'parent_entity_id AS row_id, Row_.name AS row_name ' .
371 'FROM Object Rack_ ' .
372 "LEFT JOIN EntityLink ON (Rack_.id = child_entity_id AND parent_entity_type = 'row' AND child_entity_type = 'rack') " .
373 'LEFT JOIN Object Row_ ON parent_entity_id = Row_.id ' .
374 'WHERE Rack_.id IN(' . questionMarks (count ($rackidlist)) . ') ',
375 $rackidlist
376 );
377 $rackinfo = array();
378 foreach ($result as $row)
379 {
380 $rackinfo[$row['rack_id']] = array
381 (
382 'rack_id' => $row['rack_id'],
383 'row_id' => $row['row_id'],
384 );
385 if ('' != $row['rack_name'])
386 $rackinfo[$row['rack_id']]['rack_name'] = $row['rack_name'];
387 elseif ('' != $row['rack_label'])
388 $rackinfo[$row['rack_id']]['rack_name'] = $row['rack_label'];
389 else
390 $rackinfo[$row['rack_id']]['rack_name'] = 'rack#' . $row['rack_id'];
391 if ('' != $row['row_name'])
392 $rackinfo[$row['rack_id']]['row_name'] = $row['row_name'];
393 else
394 $rackinfo[$row['rack_id']]['row_name'] = 'row#' . $row['row_id'];
395 }
396 unset ($result);
397 # Pass 3. Combine retrieved data into returned array.
398 $ret = array();
399 foreach ($objectlist as $object_id => $racklist)
400 foreach ($racklist as $rack_id)
401 $ret[$object_id][] = $rackinfo[$rack_id];
402 return $ret;
403 }
404
405 # Return container details for a list of objects
406 function getContainerInfo ($object_ids)
407 {
408 if (! count ($object_ids))
409 return array ();
410 $result = usePreparedSelectBlade
411 (
412 'SELECT EL.child_entity_id, EL.parent_entity_id, RO.name, RO.objtype_id ' .
413 'FROM EntityLink EL ' .
414 'LEFT JOIN RackObject RO ON EL.parent_entity_id = RO.id ' .
415 'WHERE EL.child_entity_id IN (' . questionMarks (count ($object_ids)) . ') ' .
416 "AND EL.parent_entity_type = 'object' " .
417 "AND EL.child_entity_type = 'object' " .
418 'ORDER BY RO.name',
419 $object_ids
420 );
421 $ret = array ();
422 foreach ($result as $row)
423 $ret[$row['child_entity_id']][] = array
424 (
425 'container_id' => $row['parent_entity_id'],
426 'container_dname' => formatObjectDisplayedName ($row['name'], $row['objtype_id'])
427 );
428 unset ($result);
429 return $ret;
430 }
431
432 // For a given realm return a list of entity records, each with
433 // enough information for judgeCell() to execute.
434 function listCells ($realm, $parent_id = 0)
435 {
436 if (!$parent_id)
437 {
438 global $entityCache;
439 if (isset ($entityCache['complete'][$realm]))
440 return $entityCache['complete'][$realm];
441 }
442 global $SQLSchema;
443 if (!isset ($SQLSchema[$realm]))
444 throw new InvalidArgException ('realm', $realm);
445 $SQLinfo = $SQLSchema[$realm];
446 $qparams = array ();
447 $query = 'SELECT ';
448 foreach ($SQLinfo['columns'] as $alias => $expression)
449 // Automatically prepend table name to each single column, but leave all others intact.
450 $query .= ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}") . ', ';
451 $query = trim($query, ', ');
452 $query .= " FROM ${SQLinfo['table']}";
453 if (isset ($SQLinfo['pidcolumn']) && $parent_id)
454 {
455 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ?";
456 $qparams[] = $parent_id;
457 }
458 if (isset ($SQLinfo['ordcolumns']))
459 {
460 $query .= " ORDER BY ";
461 foreach ($SQLinfo['ordcolumns'] as $oc)
462 $query .= "${oc}, ";
463 $query = trim($query, ', ');
464 }
465 $result = usePreparedSelectBlade ($query, $qparams);
466 $ret = array();
467 // Index returned result by the value of key column.
468 while ($row = $result->fetch (PDO::FETCH_ASSOC))
469 {
470 $entity_id = $row[$SQLinfo['keycolumn']];
471 $ret[$entity_id] = array ('realm' => $realm);
472 $ret[$entity_id]['etags'] = array();
473 foreach (array_keys ($SQLinfo['columns']) as $alias)
474 $ret[$entity_id][$alias] = $row[$alias];
475 // use the temporary rack_id_2 key and remove this key from the result array
476 if ($realm == 'object')
477 {
478 if (! isset ($ret[$entity_id]['rack_id']))
479 $ret[$entity_id]['rack_id'] = $ret[$entity_id]['rack_id_2'];
480 unset ($ret[$entity_id]['rack_id_2']);
481 }
482 }
483 unset($result);
484
485 // select tags and link them to previosly fetched entities
486 $query = 'SELECT entity_id, tag_id, user AS tag_user, UNIX_TIMESTAMP(date) AS tag_time FROM TagStorage WHERE entity_realm = ?';
487 $result = usePreparedSelectBlade ($query, array($realm));
488 global $taglist;
489 while ($row = $result->fetch (PDO::FETCH_ASSOC))
490 {
491 $tag_id = $row['tag_id'];
492 if (array_key_exists($row['entity_id'], $ret))
493 $ret[$row['entity_id']]['etags'][$tag_id] = array
494 (
495 'id' => $tag_id,
496 'tag' => $taglist[$tag_id]['tag'],
497 'parent_id' => $taglist[$tag_id]['parent_id'],
498 'user' => $row['tag_user'],
499 'time' => $row['tag_time'],
500 );
501 }
502 unset($result);
503 // Add necessary finish to the list before returning it. Maintain caches.
504 if (!$parent_id)
505 unset ($entityCache['partial'][$realm]);
506 if ($realm == 'object') // cache dict attributes of all objects to speed up autotags calculation
507 cacheDictAttrValues();
508 foreach ($ret as $entity_id => &$entity)
509 {
510 sortEntityTags ($entity); // changes ['etags'] and ['itags']
511 switch ($realm)
512 {
513 case 'object':
514 setDisplayedName ($entity); // set $entity['dname']
515 break;
516 case 'ipv4net':
517 $entity = array_merge ($entity, constructIPRange (ip4_int2bin ($entity['ip_bin']), $entity['mask']));
518 processIPNetVlans ($entity);
519 $entity['spare_ranges'] = array();
520 $entity['kidc'] = 0;
521 break;
522 case 'ipv6net':
523 $entity = array_merge ($entity, constructIPRange ($entity['ip_bin'], $entity['mask']));
524 processIPNetVlans ($entity);
525 $entity['spare_ranges'] = array();
526 $entity['kidc'] = 0;
527 break;
528 case 'ipv4vs':
529 $entity['vip'] = ip_format ($entity['vip_bin']);
530 setDisplayedName ($entity); // set $entity['dname']
531 $entity['vsconfig'] = dos2unix ($entity['vsconfig']);
532 $entity['rsconfig'] = dos2unix ($entity['rsconfig']);
533 break;
534 case 'ipv4rspool':
535 $entity['vsconfig'] = dos2unix ($entity['vsconfig']);
536 $entity['rsconfig'] = dos2unix ($entity['rsconfig']);
537 break;
538 case 'ipvs':
539 $entity['vsconfig'] = dos2unix ($entity['vsconfig']);
540 $entity['rsconfig'] = dos2unix ($entity['rsconfig']);
541 break;
542 default:
543 break;
544 }
545 }
546 if ($realm == 'ipv4net' || $realm == 'ipv6net')
547 fillIPNetsCorrelation ($ret);
548
549 foreach (array_keys ($ret) as $entity_id)
550 {
551 $entity = &$ret[$entity_id];
552 $entity['atags'] = callHook ('generateEntityAutoTags', $entity);
553 if (!$parent_id)
554 $entityCache['complete'][$realm][$entity_id] = $entity;
555 else
556 $entityCache['partial'][$realm][$entity_id] = $entity;
557 }
558
559 return $ret;
560 }
561
562 // Very much like listCells(), but return only one record requested
563 // throws an exception if entity not exists
564 function spotEntity ($realm, $id, $ignore_cache = FALSE)
565 {
566 if (! $ignore_cache)
567 {
568 global $entityCache;
569 if (isset ($entityCache['complete'][$realm]))
570 {
571 if (isset ($entityCache['complete'][$realm][$id]))
572 return $entityCache['complete'][$realm][$id];
573 }
574 elseif (isset ($entityCache['partial'][$realm][$id]))
575 return $entityCache['partial'][$realm][$id];
576 }
577 global $SQLSchema;
578 if (!isset ($SQLSchema[$realm]))
579 throw new InvalidArgException ('realm', $realm);
580 $SQLinfo = $SQLSchema[$realm];
581 $query = 'SELECT tag_id, TagStorage.user as tag_user, UNIX_TIMESTAMP(TagStorage.date) AS tag_time';
582 foreach ($SQLinfo['columns'] as $alias => $expression)
583 // Automatically prepend table name to each single column, but leave all others intact.
584 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
585 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
586 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ?";
587 $result = usePreparedSelectBlade ($query, array ($realm, $id));
588 $ret = array();
589 global $taglist;
590 while ($row = $result->fetch (PDO::FETCH_ASSOC))
591 if (!isset ($ret['realm']))
592 {
593 $ret = array ('realm' => $realm);
594 foreach (array_keys ($SQLinfo['columns']) as $alias)
595 $ret[$alias] = $row[$alias];
596 // use the temporary rack_id_2 key and remove this key from the result array
597 if ($realm == 'object')
598 {
599 if (! isset ($ret['rack_id']))
600 $ret['rack_id'] = $ret['rack_id_2'];
601 unset ($ret['rack_id_2']);
602 }
603 $ret['etags'] = array();
604 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
605 $ret['etags'][$row['tag_id']] = array
606 (
607 'id' => $row['tag_id'],
608 'tag' => $taglist[$row['tag_id']]['tag'],
609 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
610 'user' => $row['tag_user'],
611 'time' => $row['tag_time'],
612 );
613 }
614 elseif (isset ($taglist[$row['tag_id']]))
615 $ret['etags'][$row['tag_id']] = array
616 (
617 'id' => $row['tag_id'],
618 'tag' => $taglist[$row['tag_id']]['tag'],
619 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
620 'user' => $row['tag_user'],
621 'time' => $row['tag_time'],
622 );
623 unset ($result);
624 if (!isset ($ret['realm'])) // no rows were returned
625 throw new EntityNotFoundException ($realm, $id);
626 sortEntityTags ($ret); // changes ['etags'] and ['itags']
627 switch ($realm)
628 {
629 case 'object':
630 setDisplayedName ($ret); // set $ret['dname']
631 break;
632 case 'ipv4net':
633 processIPNetVlans ($ret);
634 $ret = array_merge ($ret, constructIPRange (ip4_int2bin ($ret['ip_bin']), $ret['mask']));
635 if (! fillNetKids ($ret))
636 {
637 $ret['spare_ranges'] = array();
638 $ret['kidc'] = 0;
639 }
640 break;
641 case 'ipv6net':
642 processIPNetVlans ($ret);
643 $ret = array_merge ($ret, constructIPRange ($ret['ip_bin'], $ret['mask']));
644 if (! fillNetKids ($ret))
645 {
646 $ret['spare_ranges'] = array();
647 $ret['kidc'] = 0;
648 }
649 break;
650 case 'ipv4vs':
651 $ret['vip'] = ip_format ($ret['vip_bin']);
652 setDisplayedName ($ret); // set $ret['dname']
653 $ret['vsconfig'] = dos2unix ($ret['vsconfig']);
654 $ret['rsconfig'] = dos2unix ($ret['rsconfig']);
655 break;
656 case 'ipv4rspool':
657 $ret['vsconfig'] = dos2unix ($ret['vsconfig']);
658 $ret['rsconfig'] = dos2unix ($ret['rsconfig']);
659 break;
660 case 'ipvs':
661 $ret['vsconfig'] = dos2unix ($ret['vsconfig']);
662 $ret['rsconfig'] = dos2unix ($ret['rsconfig']);
663 break;
664 default:
665 break;
666 }
667
668 $ret['atags'] = generateEntityAutoTags ($ret);
669 if (! $ignore_cache)
670 $entityCache['partial'][$realm][$id] = $ret;
671 return $ret;
672 }
673
674 function fillNetKids (&$net_cell)
675 {
676 if ($net_cell['realm'] == 'ipv6net')
677 {
678 $table = 'IPv6Network';
679 $ip_first = $net_cell['ip_bin'];
680 $ip_last = ip_last ($net_cell);
681 }
682 else
683 {
684 $table = 'IPv4Network';
685 $ip_first = ip4_bin2db ($net_cell['ip_bin']);
686 $ip_last = ip4_bin2db (ip_last ($net_cell));
687 }
688
689 $result = usePreparedSelectBlade ("
690 SELECT id, ip as ip_bin, mask FROM $table
691 WHERE ip BETWEEN ? AND ? AND mask >= ?
692 ORDER BY ip, mask
693 ", array ($ip_first, $ip_last, $net_cell['mask']));
694 $nets = array();
695 while ($net_row = $result->fetch (PDO::FETCH_ASSOC))
696 {
697 $ip_bin = $net_row['ip_bin'];
698 if ($net_cell['realm'] == 'ipv4net')
699 $ip_bin = ip4_int2bin ($ip_bin);
700 $nets[] = constructIPRange ($ip_bin, $net_row['mask']) +
701 array(
702 'id' => $net_row['id'],
703 'spare_ranges' => array(),
704 'kidc' => 0,
705 );
706 }
707 unset ($result);
708
709 fillIPNetsCorrelation ($nets, 1);
710 if (is_array ($nets[0]) && $nets[0]['id'] == $net_cell['id'])
711 {
712 $net_cell['spare_ranges'] = $nets[0]['spare_ranges'];
713 $net_cell['kidc'] = $nets[0]['kidc'];
714 return TRUE;
715 }
716 return FALSE;
717 }
718
719 // This function can be used with array_walk().
720 function amplifyCell (&$record, $dummy = NULL)
721 {
722 switch ($record['realm'])
723 {
724 case 'object':
725 $record['ports'] = getObjectPortsAndLinks ($record['id']);
726 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
727 $record['ipv6'] = getObjectIPv6Allocations ($record['id']);
728 $record['nat4'] = getNATv4ForObject ($record['id']);
729 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
730 break;
731 case 'file':
732 $record['links'] = getFileLinks ($record['id']);
733 break;
734 case 'location':
735 $record['locations'] = getLocations ($record['id']);
736 $record['rows'] = getRows ($record['id']);
737 break;
738 case 'row':
739 $record['racks'] = getRacks ($record['id']);
740 break;
741 case 'rack':
742 // start with default rackspace
743 for ($i = $record['height']; $i > 0; $i--)
744 for ($locidx = 0; $locidx < 3; $locidx++)
745 $record[$i][$locidx]['state'] = 'F';
746 // load difference
747 $query =
748 "select unit_no, atom, state, object_id, has_problems " .
749 "from RackSpace LEFT JOIN Object ON Object.id = object_id where rack_id = ? and " .
750 "unit_no between 1 and ? order by unit_no";
751 $result = usePreparedSelectBlade ($query, array ($record['id'], $record['height']));
752 global $loclist;
753 $mounted_objects = array();
754 // fetch Zero-U mounted objects
755 foreach (getChildren ($record, 'object') as $child)
756 $mounted_objects[$child['id']] = TRUE;
757
758 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
759 unset ($result);
760 foreach ($rows as $row)
761 {
762 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
763 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
764 $record[$row['unit_no']][$loclist[$row['atom']]]['hl'] = $row['has_problems'] == 'yes' ? 'w' : '';
765 if ($row['state'] == 'T' && $row['object_id'] != NULL)
766 $mounted_objects[$row['object_id']] = TRUE;
767 }
768
769 $record['isDeletable'] = (count ($rows) || count ($mounted_objects)) ? FALSE : TRUE;
770 $record['mountedObjects'] = array_keys ($mounted_objects);
771 break;
772 case 'vst':
773 $record['rules'] = array();
774 $record['switches'] = array();
775 $result = usePreparedSelectBlade
776 (
777 'SELECT rule_no, port_pcre, port_role, wrt_vlans, description ' .
778 'FROM VLANSTRule WHERE vst_id = ? ORDER BY rule_no',
779 array ($record['id'])
780 );
781 while ($row = $result->fetch (PDO::FETCH_ASSOC))
782 $record['rules'][$row['rule_no']] = $row;
783 unset ($result);
784 $result = usePreparedSelectBlade ('SELECT object_id, domain_id FROM VLANSwitch WHERE template_id = ?', array ($record['id']));
785 while ($row = $result->fetch (PDO::FETCH_ASSOC))
786 $record['switches'][$row['object_id']] = $row;
787 break;
788 case 'ipvs':
789 $record['ports'] = array();
790 $record['vips'] = array();
791 $result = usePreparedSelectBlade ("SELECT proto, vport, vsconfig, rsconfig FROM VSPorts WHERE vs_id = ?", array ($record['id']));
792 while ($row = $result->fetch (PDO::FETCH_ASSOC))
793 {
794 $row['vsconfig'] = dos2unix ($row['vsconfig']);
795 $row['rsconfig'] = dos2unix ($row['rsconfig']);
796 $record['ports'][] = $row;
797 }
798 unset ($result);
799 $result = usePreparedSelectBlade ("SELECT vip, vsconfig, rsconfig FROM VSIPs WHERE vs_id = ?", array ($record['id']));
800 while ($row = $result->fetch (PDO::FETCH_ASSOC))
801 {
802 $row['vsconfig'] = dos2unix ($row['vsconfig']);
803 $row['rsconfig'] = dos2unix ($row['rsconfig']);
804 $record['vips'][] = $row;
805 }
806 unset ($result);
807 break;
808 default:
809 }
810 }
811
812 // is called by spotEntity and listCells.
813 // replaces ['8021q'] text value in cell by an array with 'domain_id' and 'vlan_id' subkeys
814 // also sets ['vlanc'] cell key to the binded vlans count.
815 function processIPNetVlans (&$cell)
816 {
817 if (empty ($cell['8021q']))
818 $cell['8021q'] = array();
819 else
820 {
821 $ck_list = explode (',', $cell['8021q']);
822 $cell['8021q'] = array();
823 foreach ($ck_list as $vlan_ck)
824 {
825 list ($domain_id, $vlan_id) = decodeVLANCK ($vlan_ck);
826 $cell['8021q'][] = array ('domain_id' => $domain_id, 'vlan_id' => $vlan_id);
827 }
828 }
829 $cell['vlanc'] = count ($cell['8021q']);
830 }
831
832 function fetchPortList ($sql_where_clause, $query_params = array())
833 {
834 $query = <<<END
835 SELECT
836 Port.id,
837 Port.name,
838 Port.object_id,
839 Object.name AS object_name,
840 Port.l2address,
841 Port.label,
842 Port.reservation_comment,
843 Port.iif_id,
844 Port.type AS oif_id,
845 (SELECT PortInnerInterface.iif_name FROM PortInnerInterface WHERE PortInnerInterface.id = Port.iif_id) AS iif_name,
846 (SELECT PortOuterInterface.oif_name FROM PortOuterInterface WHERE PortOuterInterface.id = Port.type) AS oif_name,
847 IF(la.porta, la.cable, lb.cable) AS cableid,
848 IF(la.porta, pa.id, pb.id) AS remote_id,
849 IF(la.porta, pa.name, pb.name) AS remote_name,
850 IF(la.porta, pa.object_id, pb.object_id) AS remote_object_id,
851 IF(la.porta, oa.name, ob.name) AS remote_object_name,
852 IF(la.porta, oa.objtype_id, ob.objtype_id) AS remote_object_tid,
853 (SELECT COUNT(*) FROM PortLog WHERE PortLog.port_id = Port.id) AS log_count,
854 PortLog.user,
855 UNIX_TIMESTAMP(PortLog.date) as time
856 FROM
857 Port
858 INNER JOIN Object ON Port.object_id = Object.id
859 LEFT JOIN Link AS la ON la.porta = Port.id
860 LEFT JOIN Port AS pa ON pa.id = la.portb
861 LEFT JOIN Object AS oa ON pa.object_id = oa.id
862 LEFT JOIN Link AS lb on lb.portb = Port.id
863 LEFT JOIN Port AS pb ON pb.id = lb.porta
864 LEFT JOIN Object AS ob ON pb.object_id = ob.id
865 LEFT JOIN PortLog ON PortLog.id = (SELECT id FROM PortLog WHERE PortLog.port_id = Port.id ORDER BY date DESC LIMIT 1)
866 WHERE
867 $sql_where_clause
868 END;
869
870 $result = usePreparedSelectBlade ($query, $query_params);
871 $ret = array();
872 while ($row = $result->fetch (PDO::FETCH_ASSOC))
873 {
874 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
875 $row['linked'] = isset ($row['remote_id']) ? 1 : 0;
876
877 // last changed log
878 $row['last_log'] = array();
879 if ($row['log_count'])
880 {
881 $row['last_log']['user'] = $row['user'];
882 $row['last_log']['time'] = $row['time'];
883 }
884 unset ($row['user']);
885 unset ($row['time']);
886
887 $ret[] = $row;
888 }
889 return $ret;
890 }
891
892 function getObjectPortsAndLinks ($object_id, $sorted = TRUE)
893 {
894 $ret = fetchPortList ("Port.object_id = ?", array ($object_id));
895 if ($sorted)
896 $ret = sortPortList ($ret, TRUE);
897 return $ret;
898 }
899
900 // This function provides data for syncObjectPorts() and requires only two tables locked.
901 function getObjectPortsAndLinksTerse ($object_id)
902 {
903 $result = usePreparedSelectBlade
904 (
905 'SELECT id, name, iif_id, type AS oif_id, label, l2address, reservation_comment, ' .
906 '(SELECT COUNT(*) FROM Link WHERE porta = Port.id OR portb = Port.id) AS link_count ' .
907 'FROM Port WHERE object_id = ?',
908 array ($object_id)
909 );
910 return $result->fetchAll (PDO::FETCH_ASSOC);
911 }
912
913 // Fetch the object type via SQL.
914 // spotEntity cannot be used because it references RackObject, which doesn't suit Racks, Rows, or Locations.
915 function getObjectType ($object_id)
916 {
917 $result = usePreparedSelectBlade ('SELECT objtype_id from Object WHERE id = ?', array ($object_id));
918 return $result->fetchColumn ();
919 }
920
921 // If the given name is used by any object other than the current object,
922 // raise an exception. Validation is bypassed for certain object types
923 // where duplicates are acceptable.
924 // NOTE: This could be enforced more strictly at the database level using triggers.
925 function checkObjectNameUniqueness ($name, $type_id, $object_id = 0)
926 {
927 // Some object types do not need unique names
928 // 1560 - Rack
929 // 1561 - Row
930 $dupes_allowed = array (1560, 1561);
931 if (in_array ($type_id, $dupes_allowed))
932 return;
933
934 $result = usePreparedSelectBlade
935 (
936 'SELECT COUNT(*) FROM Object WHERE name = ? AND id != ?',
937 array ($name, $object_id)
938 );
939 $row = $result->fetch (PDO::FETCH_NUM);
940 if ($row[0] != 0)
941 throw new InvalidRequestArgException ('name', $name, 'An object with that name already exists');
942 }
943
944 function commitAddObject ($new_name, $new_label, $new_type_id, $new_asset_no, $taglist = array())
945 {
946 checkObjectNameUniqueness ($new_name, $new_type_id);
947 usePreparedInsertBlade
948 (
949 'Object',
950 array
951 (
952 'name' => nullIfEmptyStr ($new_name),
953 'label' => nullIfEmptyStr ($new_label),
954 'objtype_id' => $new_type_id,
955 'asset_no' => nullIfEmptyStr ($new_asset_no),
956 )
957 );
958 $object_id = lastInsertID();
959 switch ($new_type_id)
960 {
961 case 1560:
962 $realm = 'rack';
963 break;
964 case 1561:
965 $realm = 'row';
966 break;
967 case 1562:
968 $realm = 'location';
969 break;
970 default:
971 $realm = 'object';
972 }
973 lastCreated ($realm, $object_id);
974
975 // Do AutoPorts magic
976 if ($realm == 'object')
977 executeAutoPorts ($object_id);
978 // Now tags...
979 produceTagsForNewRecord ($realm, $taglist, $object_id);
980 recordObjectHistory ($object_id);
981 return $object_id;
982 }
983
984 function commitRenameObject ($object_id, $new_name)
985 {
986 $type_id = getObjectType ($object_id);
987 checkObjectNameUniqueness ($new_name, $type_id, $object_id);
988 usePreparedUpdateBlade
989 (
990 'Object',
991 array
992 (
993 'name' => nullIfEmptyStr ($new_name),
994 ),
995 array
996 (
997 'id' => $object_id
998 )
999 );
1000 recordObjectHistory ($object_id);
1001 }
1002
1003 function commitUpdateObject ($object_id, $new_name, $new_label, $new_has_problems, $new_asset_no, $new_comment)
1004 {
1005 $type_id = getObjectType ($object_id);
1006 checkObjectNameUniqueness ($new_name, $type_id, $object_id);
1007 usePreparedUpdateBlade
1008 (
1009 'Object',
1010 array
1011 (
1012 'name' => nullIfEmptyStr ($new_name),
1013 'label' => nullIfEmptyStr ($new_label),
1014 'has_problems' => $new_has_problems == '' ? 'no' : $new_has_problems,
1015 'asset_no' => nullIfEmptyStr ($new_asset_no),
1016 'comment' => nullIfEmptyStr ($new_comment),
1017 ),
1018 array
1019 (
1020 'id' => $object_id
1021 )
1022 );
1023 recordObjectHistory ($object_id);
1024 }
1025
1026 function compare_name ($a, $b)
1027 {
1028 return strnatcmp($a['name'], $b['name']);
1029 }
1030
1031 // find either parents or children of a record
1032 function getEntityRelatives ($type, $entity_type, $entity_id)
1033 {
1034 $ret = array();
1035
1036 if ($type == 'parents')
1037 {
1038 // searching for parents
1039 $sql =
1040 'SELECT id, parent_entity_type AS entity_type, parent_entity_id AS entity_id FROM EntityLink ' .
1041 'WHERE child_entity_type = ? AND child_entity_id = ?';
1042 }
1043 else
1044 {
1045 // searching for children
1046 $sql =
1047 'SELECT id, child_entity_type AS entity_type, child_entity_id AS entity_id FROM EntityLink ' .
1048 'WHERE parent_entity_type = ? AND parent_entity_id = ?';
1049 }
1050
1051 $result = usePreparedSelectBlade ($sql, array ($entity_type, $entity_id));
1052 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1053 $ret[$row['id']] = array(
1054 'entity_type' => $row['entity_type'],
1055 'entity_id' => $row['entity_id'],
1056 );
1057
1058 return $ret;
1059 }
1060
1061 function getParents ($entity, $result_realm = NULL)
1062 {
1063 return getRelatives ($entity, 'parents', $result_realm);
1064 }
1065
1066 function getChildren ($entity, $result_realm = NULL)
1067 {
1068 return getRelatives ($entity, 'children', $result_realm);
1069 }
1070
1071 function getRelatives ($entity, $type, $result_realm = NULL)
1072 {
1073 $ret = array();
1074 foreach (getEntityRelatives ($type, $entity['realm'], $entity['id']) as $link_id => $struct)
1075 if (! isset ($result_realm) || $result_realm == $struct['entity_type'])
1076 $ret[$link_id] = spotEntity ($struct['entity_type'], $struct['entity_id']);
1077 return $ret;
1078 }
1079
1080 // This function is recursive and returns only object IDs.
1081 function getObjectContentsList ($object_id, $children = array ())
1082 {
1083 $self = __FUNCTION__;
1084 $result = usePreparedSelectBlade
1085 (
1086 'SELECT child_entity_id FROM EntityLink ' .
1087 'WHERE parent_entity_type = "object" AND child_entity_type = "object" AND parent_entity_id = ?',
1088 array ($object_id)
1089 );
1090 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1091 unset ($result);
1092 foreach ($rows as $row)
1093 {
1094 if (in_array ($row['child_entity_id'], $children))
1095 throw new RackTablesError ("Circular reference for object ${object_id}", RackTablesError::INTERNAL);
1096 $children[] = $row['child_entity_id'];
1097 $children = array_unique (array_merge ($children, $self ($row['child_entity_id'], $children)));
1098 }
1099 return $children;
1100 }
1101
1102 // This function is recursive and returns only location IDs.
1103 function getLocationChildrenList ($location_id, $children = array ())
1104 {
1105 $self = __FUNCTION__;
1106 $result = usePreparedSelectBlade ('SELECT id FROM Location WHERE parent_id = ?', array ($location_id));
1107 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1108 unset ($result);
1109 foreach ($rows as $row)
1110 {
1111 if (in_array ($row['id'], $children))
1112 throw new RackTablesError ("Circular reference for location ${location_id}", RackTablesError::INTERNAL);
1113 $children[] = $row['id'];
1114 $children = array_unique (array_merge ($children, $self ($row['id'], $children)));
1115 }
1116 return $children;
1117 }
1118
1119 // DEPRECATED: use getTagDescendents() instead
1120 // This function is recursive and returns only tag IDs.
1121 function getTagChildrenList ($tag_id, $children = array ())
1122 {
1123 $self = __FUNCTION__;
1124 $result = usePreparedSelectBlade ('SELECT id FROM TagTree WHERE parent_id = ?', array ($tag_id));
1125 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1126 unset ($result);
1127 foreach ($rows as $row)
1128 {
1129 if (in_array ($row['id'], $children))
1130 throw new RackTablesError ("Circular reference for tag ${tag_id}", RackTablesError::INTERNAL);
1131 $children[] = $row['id'];
1132 $children = array_unique (array_merge ($children, $self ($row['id'], $children)));
1133 }
1134 return $children;
1135 }
1136
1137 function commitLinkEntities ($parent_entity_type, $parent_entity_id, $child_entity_type, $child_entity_id)
1138 {
1139 // a location's parent may not be one of its children
1140 if
1141 (
1142 $parent_entity_type == 'location' &&
1143 $child_entity_type == 'location' &&
1144 in_array ($parent_entity_id, getLocationChildrenList ($child_entity_id))
1145 )
1146 throw new RackTablesError ("Circular reference for location ${parent_entity_id}", RackTablesError::INTERNAL);
1147
1148 // an object's container may not be one of its contained objects
1149 if
1150 (
1151 $parent_entity_type == 'object' &&
1152 $child_entity_type == 'object' &&
1153 in_array ($parent_entity_id, getObjectContentsList ($child_entity_id))
1154 )
1155 throw new RackTablesError ("Circular reference for object ${parent_entity_id}", RackTablesError::INTERNAL);
1156
1157 usePreparedInsertBlade
1158 (
1159 'EntityLink',
1160 array
1161 (
1162 'parent_entity_type' => $parent_entity_type,
1163 'parent_entity_id' => $parent_entity_id,
1164 'child_entity_type' => $child_entity_type,
1165 'child_entity_id' => $child_entity_id,
1166 )
1167 );
1168 }
1169
1170 function commitUpdateEntityLink
1171 (
1172 $old_parent_entity_type, $old_parent_entity_id, $old_child_entity_type, $old_child_entity_id,
1173 $new_parent_entity_type, $new_parent_entity_id, $new_child_entity_type, $new_child_entity_id
1174 )
1175 {
1176 // a location's parent may not be one of its children
1177 if
1178 (
1179 $new_parent_entity_type == 'location' &&
1180 $new_child_entity_type == 'location' &&
1181 in_array ($new_parent_entity_id, getLocationChildrenList ($new_child_entity_id))
1182 )
1183 throw new RackTablesError ("Circular reference for location ${new_parent_entity_id}", RackTablesError::INTERNAL);
1184
1185 // an object's container may not be one of its contained objects
1186 if
1187 (
1188 $new_parent_entity_type == 'object' &&
1189 $new_child_entity_type == 'object' &&
1190 in_array ($new_parent_entity_id, getObjectContentsList ($new_child_entity_id))
1191 )
1192 throw new RackTablesError ("Circular reference for object ${new_parent_entity_id}", RackTablesError::INTERNAL);
1193
1194 usePreparedUpdateBlade
1195 (
1196 'EntityLink',
1197 array
1198 (
1199 'parent_entity_type' => $new_parent_entity_type,
1200 'parent_entity_id' => $new_parent_entity_id,
1201 'child_entity_type' => $new_child_entity_type,
1202 'child_entity_id' => $new_child_entity_id
1203 ),
1204 array
1205 (
1206 'parent_entity_type' => $old_parent_entity_type,
1207 'parent_entity_id' => $old_parent_entity_id,
1208 'child_entity_type' => $old_child_entity_type,
1209 'child_entity_id' => $old_child_entity_id
1210 )
1211 );
1212 }
1213
1214 function commitUnlinkEntities ($parent_entity_type, $parent_entity_id, $child_entity_type, $child_entity_id)
1215 {
1216 usePreparedDeleteBlade
1217 (
1218 'EntityLink',
1219 array
1220 (
1221 'parent_entity_type' => $parent_entity_type,
1222 'parent_entity_id' => $parent_entity_id,
1223 'child_entity_type' => $child_entity_type,
1224 'child_entity_id' => $child_entity_id
1225 )
1226 );
1227 }
1228
1229 function commitUnlinkEntitiesByLinkID ($link_id)
1230 {
1231 usePreparedDeleteBlade ('EntityLink', array ('id' => $link_id));
1232 }
1233
1234 // return VM clusters and corresponding stats
1235 // - number of hypervisors
1236 // - number of resource pools
1237 // - number of VMs whose parent is the cluster itself
1238 // - number of VMs whose parent is one of the resource pools in the cluster
1239 function getVMClusterSummary ()
1240 {
1241 $query = <<<END
1242 SELECT
1243 O.id,
1244 O.name,
1245 (SELECT COUNT(*) FROM EntityLink EL
1246 LEFT JOIN Object O_H ON EL.child_entity_id = O_H.id
1247 LEFT JOIN AttributeValue AV ON O_H.id = AV.object_id
1248 WHERE EL.parent_entity_type = 'object'
1249 AND EL.child_entity_type = 'object'
1250 AND EL.parent_entity_id = O.id
1251 AND O_H.objtype_id = 4
1252 AND AV.attr_id = 26
1253 AND AV.uint_value = 1501) AS hypervisors,
1254 (SELECT COUNT(*) FROM EntityLink EL
1255 LEFT JOIN Object O_RP ON EL.child_entity_id = O_RP.id
1256 WHERE EL.parent_entity_type = 'object'
1257 AND EL.child_entity_type = 'object'
1258 AND EL.parent_entity_id = O.id
1259 AND O_RP.objtype_id = 1506) AS resource_pools,
1260 (SELECT COUNT(*) FROM EntityLink EL
1261 LEFT JOIN Object O_C_VM ON EL.child_entity_id = O_C_VM.id
1262 WHERE EL.parent_entity_type = 'object'
1263 AND EL.child_entity_type = 'object'
1264 AND EL.parent_entity_id = O.id
1265 AND O_C_VM.objtype_id = 1504) AS cluster_vms,
1266 (SELECT COUNT(*) FROM EntityLink EL
1267 LEFT JOIN Object O_RP_VM ON EL.child_entity_id = O_RP_VM.id
1268 WHERE EL.parent_entity_type = 'object'
1269 AND EL.child_entity_type = 'object'
1270 AND EL.parent_entity_id IN
1271 (SELECT child_entity_id FROM EntityLink EL
1272 LEFT JOIN Object O_RP ON EL.child_entity_id = O_RP.id
1273 WHERE EL.parent_entity_type = 'object'
1274 AND EL.child_entity_type = 'object'
1275 AND EL.parent_entity_id = O.id
1276 AND O_RP.objtype_id = 1506)
1277 AND O_RP_VM.objtype_id = 1504) AS resource_pool_vms
1278 FROM Object O
1279 WHERE O.objtype_id = 1505
1280 ORDER BY O.name
1281 END;
1282 $result = usePreparedSelectBlade ($query);
1283 return $result->fetchAll (PDO::FETCH_ASSOC);
1284 }
1285
1286 function getVMResourcePoolSummary ()
1287 {
1288 $result = usePreparedSelectBlade
1289 (
1290 "SELECT O.id, O.name, " .
1291 "(SELECT O_C.id " .
1292 "FROM EntityLink EL " .
1293 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1294 "WHERE EL.child_entity_id = O.id " .
1295 "AND EL.parent_entity_type = 'object' " .
1296 "AND EL.child_entity_type = 'object' " .
1297 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_id, " .
1298 "(SELECT O_C.name " .
1299 "FROM EntityLink EL " .
1300 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1301 "WHERE EL.child_entity_id = O.id " .
1302 "AND EL.parent_entity_type = 'object' " .
1303 "AND EL.child_entity_type = 'object' " .
1304 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_name, " .
1305 "(SELECT COUNT(*) FROM EntityLink EL " .
1306 "LEFT JOIN Object O_VM ON EL.child_entity_id = O_VM.id " .
1307 "WHERE EL.parent_entity_type = 'object' " .
1308 "AND EL.child_entity_type = 'object' " .
1309 "AND EL.parent_entity_id = O.id " .
1310 "AND O_VM.objtype_id = 1504) AS VMs " .
1311 "FROM Object O " .
1312 "WHERE O.objtype_id = 1506 " .
1313 "ORDER BY O.name"
1314 );
1315 return $result->fetchAll (PDO::FETCH_ASSOC);
1316 }
1317
1318 function getVMHypervisorSummary ()
1319 {
1320 $result = usePreparedSelectBlade
1321 (
1322 "SELECT O.id, O.name, " .
1323 "(SELECT O_C.id " .
1324 "FROM EntityLink EL " .
1325 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1326 "WHERE EL.child_entity_id = O.id " .
1327 "AND EL.parent_entity_type = 'object' " .
1328 "AND EL.child_entity_type = 'object' " .
1329 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_id, " .
1330 "(SELECT O_C.name " .
1331 "FROM EntityLink EL " .
1332 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1333 "WHERE EL.child_entity_id = O.id " .
1334 "AND EL.parent_entity_type = 'object' " .
1335 "AND EL.child_entity_type = 'object' " .
1336 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_name, " .
1337 "(SELECT COUNT(*) FROM EntityLink EL " .
1338 "LEFT JOIN Object O_VM ON EL.child_entity_id = O_VM.id " .
1339 "WHERE EL.parent_entity_type = 'object' " .
1340 "AND EL.child_entity_type = 'object' " .
1341 "AND EL.parent_entity_id = O.id " .
1342 "AND O_VM.objtype_id = 1504) AS VMs " .
1343 "FROM Object O " .
1344 "LEFT JOIN AttributeValue AV ON O.id = AV.object_id " .
1345 "WHERE O.objtype_id = 4 " .
1346 "AND AV.attr_id = 26 " .
1347 "AND AV.uint_value = 1501 " .
1348 "ORDER BY O.name"
1349 );
1350 return $result->fetchAll (PDO::FETCH_ASSOC);
1351 }
1352
1353 function getVMSwitchSummary ()
1354 {
1355 $result = usePreparedSelectBlade
1356 (
1357 "SELECT O.id, O.name " .
1358 "FROM Object O " .
1359 "WHERE O.objtype_id = 1507 " .
1360 "ORDER BY O.name"
1361 );
1362 return $result->fetchAll (PDO::FETCH_ASSOC);
1363 }
1364
1365 // Remove file links related to the entity, but leave the entity and file(s) intact.
1366 function releaseFiles ($entity_realm, $entity_id)
1367 {
1368 usePreparedDeleteBlade ('FileLink', array ('entity_type' => $entity_realm, 'entity_id' => $entity_id));
1369 }
1370
1371 // There are times when you want to delete all traces of an object
1372 function commitDeleteObject ($object_id)
1373 {
1374 // Reset most of stuff
1375 commitResetObject ($object_id);
1376 // Object itself
1377 usePreparedDeleteBlade ('Object', array ('id' => $object_id));
1378 // Dangling links
1379 usePreparedExecuteBlade
1380 (
1381 'DELETE FROM EntityLink WHERE ' .
1382 "(parent_entity_type IN ('rack', 'row', 'location') AND parent_entity_id = ?) OR " .
1383 "(child_entity_type IN ('rack', 'row', 'location') AND child_entity_id = ?)",
1384 array ($object_id, $object_id)
1385 );
1386 }
1387
1388 function commitResetObject ($object_id)
1389 {
1390 releaseFiles ('object', $object_id);
1391 destroyTagsForEntity ('object', $object_id);
1392 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
1393 usePreparedDeleteBlade ('IPv4Allocation', array ('object_id' => $object_id));
1394 usePreparedDeleteBlade ('IPv6Allocation', array ('object_id' => $object_id));
1395 usePreparedDeleteBlade ('IPv4NAT', array ('object_id' => $object_id));
1396 // Parent-child relationships
1397 usePreparedExecuteBlade
1398 (
1399 'DELETE FROM EntityLink WHERE ' .
1400 "(parent_entity_type = 'object' AND parent_entity_id = ?) OR (child_entity_type = 'object' AND child_entity_id = ?)",
1401 array ($object_id, $object_id)
1402 );
1403 // Rack space
1404 usePreparedExecuteBlade ('DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
1405 usePreparedExecuteBlade ('DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
1406 usePreparedDeleteBlade ('MountOperation', array ('object_id' => $object_id));
1407 usePreparedDeleteBlade ('RackSpace', array ('object_id' => $object_id));
1408 // 802.1Q
1409 usePreparedDeleteBlade ('PortVLANMode', array ('object_id' => $object_id));
1410 usePreparedDeleteBlade ('PortNativeVLAN', array ('object_id' => $object_id));
1411 usePreparedDeleteBlade ('PortAllowedVLAN', array ('object_id' => $object_id));
1412 usePreparedDeleteBlade ('CachedPVM', array ('object_id' => $object_id));
1413 usePreparedDeleteBlade ('VLANSwitch', array ('object_id' => $object_id));
1414 // SLB
1415 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
1416 usePreparedDeleteBlade ('VSEnabledIPs', array ('object_id' => $object_id));
1417 usePreparedDeleteBlade ('VSEnabledPorts', array ('object_id' => $object_id));
1418 // Ports & links
1419 usePreparedDeleteBlade ('Port', array ('object_id' => $object_id));
1420 // CN
1421 usePreparedUpdateBlade ('Object', array ('name' => NULL, 'label' => ''), array ('id' => $object_id));
1422 // FQDN
1423 commitUpdateAttrValue ($object_id, 3, "");
1424 // log history
1425 recordObjectHistory ($object_id);
1426 # Cacti graphs
1427 usePreparedDeleteBlade ('CactiGraph', array ('object_id' => $object_id));
1428 # Munin graphs
1429 usePreparedDeleteBlade ('MuninGraph', array ('object_id' => $object_id));
1430 # Do an additional reset if needed
1431 callHook ('resetObject_hook', $object_id);
1432 }
1433
1434 function commitUpdateRack ($rack_id, $new_row_id, $new_name, $new_height, $new_has_problems, $new_asset_no, $new_comment)
1435 {
1436 // Can't shrink a rack if rows being deleted contain mounted objects
1437 $check_result = usePreparedSelectBlade ('SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = ? AND unit_no > ?', array ($rack_id, $new_height));
1438 $check_row = $check_result->fetch (PDO::FETCH_ASSOC);
1439 unset ($check_result);
1440 if ($check_row['count'] > 0)
1441 throw new InvalidArgException ('new_height', $new_height, 'Cannot shrink rack, objects are still mounted there');
1442
1443 // Determine if the row changed
1444 $old_rack = spotEntity ('rack', $rack_id);
1445 $old_row_id = $old_rack['row_id'];
1446 if ($old_row_id != $new_row_id)
1447 {
1448 // Move it to the specified row
1449 usePreparedUpdateBlade
1450 (
1451 'EntityLink',
1452 array ('parent_entity_id' => $new_row_id),
1453 array ('child_entity_type' => 'rack', 'child_entity_id' => $rack_id)
1454 );
1455
1456 // Set the sort_order attribute so it's placed at the end of the new row
1457 $rowInfo = getRowInfo ($new_row_id);
1458 usePreparedUpdateBlade
1459 (
1460 'AttributeValue',
1461 array ('uint_value' => $rowInfo['count']),
1462 array ('object_id' => $rack_id, 'attr_id' => 29)
1463 );
1464
1465 // Reset the sort order of the old row
1466 resetRackSortOrder ($old_row_id);
1467 }
1468
1469 // Update the height
1470 commitUpdateAttrValue ($rack_id, 27, $new_height);
1471
1472 // Update the rack
1473 commitUpdateObject ($rack_id, $new_name, NULL, $new_has_problems, $new_asset_no, $new_comment);
1474 }
1475
1476 // Unmount all objects from the rack
1477 function commitCleanRack ($rack_id)
1478 {
1479 $rack = spotEntity ('rack', $rack_id);
1480 foreach (getChildren ($rack, 'object') as $child)
1481 commitUnlinkEntities ('rack', $rack_id, 'object', $child['id']);
1482 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
1483 usePreparedDeleteBlade ('RackThumbnail', array ('rack_id' => $rack_id));
1484 }
1485
1486 // Drop the rack
1487 function commitDeleteRack ($rack_id)
1488 {
1489 $rack = spotEntity ('rack', $rack_id);
1490 releaseFiles ('rack', $rack_id);
1491 destroyTagsForEntity ('rack', $rack_id);
1492 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
1493 commitDeleteObject ($rack_id);
1494 resetRackSortOrder ($rack['row_id']);
1495 }
1496
1497 // Drop the row with all racks inside
1498 function commitDeleteRow ($row_id)
1499 {
1500 $racks = getRacks ($row_id);
1501 foreach ($racks as $rack)
1502 commitDeleteRack ($rack['id']);
1503 commitDeleteObject ($row_id);
1504 }
1505
1506 // Returns mounted devices count in all racks inside the specified row
1507 function getRowMountsCount ($row_id)
1508 {
1509 $query =<<<END
1510 SELECT COUNT(*) FROM (
1511 SELECT object_id FROM RackSpace rs LEFT JOIN EntityLink el ON (rs.rack_id = el.child_entity_id)
1512 WHERE
1513 rs.object_id IS NOT NULL AND
1514 el.parent_entity_id = ? AND el.parent_entity_type = "row" AND el.child_entity_type = "rack"
1515 UNION
1516 SELECT el1.child_entity_id object_id FROM EntityLink el1 LEFT JOIN EntityLink el2 ON (el1.parent_entity_id = el2.child_entity_id)
1517 WHERE
1518 el1.parent_entity_type = "rack" AND el1.child_entity_type = "object" AND
1519 el2.parent_entity_id = ? AND el2.parent_entity_type = "row" AND el2.child_entity_type = "rack"
1520 ) x
1521 END;
1522 $result = usePreparedSelectBlade ($query, array ($row_id, $row_id));
1523 return $result->fetchColumn();
1524 }
1525
1526 // Returns mounted devices count in specified rack
1527 function getRackMountsCount ($rack_id)
1528 {
1529 $query =<<<END
1530 SELECT COUNT(*) FROM (
1531 SELECT object_id FROM RackSpace WHERE object_id IS NOT NULL AND rack_id = ?
1532 UNION
1533 SELECT child_entity_id object_id FROM EntityLink WHERE
1534 parent_entity_id = ? AND parent_entity_type = "rack" AND child_entity_type = "object"
1535 ) x
1536 END;
1537 $result = usePreparedSelectBlade ($query, array ($rack_id, $rack_id));
1538 return $result->fetchColumn();
1539 }
1540
1541 // Used when sort order is manually changed, and when a rack is moved or deleted
1542 // Input is expected to be a pre-sorted array of rack IDs
1543 function updateRackSortOrder ($racks)
1544 {
1545 for ($i = 0; $i<count($racks); $i++)
1546 {
1547 usePreparedUpdateBlade
1548 (
1549 'AttributeValue',
1550 array ('uint_value' => $i+1),
1551 array ('object_id' => $racks[$i], 'attr_id' => 29)
1552 );
1553 }
1554 }
1555
1556 function resetRackSortOrder ($row_id)
1557 {
1558 // Re-order the row's racks
1559 $racks = getRacks($row_id);
1560 $rack_ids = array ();
1561 foreach ($racks as $rack_id => $rackDetails)
1562 $rack_ids[] = $rack_id;
1563 updateRackSortOrder ($rack_ids);
1564 }
1565
1566 // This function builds a list of rack-unit-atom records assigned to
1567 // the requested object.
1568 function getMoleculeForObject ($object_id)
1569 {
1570 $result = usePreparedSelectBlade
1571 (
1572 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
1573 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
1574 array ($object_id)
1575 );
1576 return $result->fetchAll (PDO::FETCH_ASSOC);
1577 }
1578
1579 // This function builds a list of rack-unit-atom records for requested molecule.
1580 function getMolecule ($mid)
1581 {
1582 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
1583 return $result->fetchAll (PDO::FETCH_ASSOC);
1584 }
1585
1586 // returns exactly what is's named after
1587 function lastInsertID ()
1588 {
1589 $result = usePreparedSelectBlade ('select last_insert_id()');
1590 return $result->fetchColumn();
1591 }
1592
1593 // This function creates a new record in Molecule and number of linked
1594 // R-U-A records in Atom.
1595 function createMolecule ($molData)
1596 {
1597 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
1598 $molecule_id = lastInsertID();
1599 foreach ($molData as $rua)
1600 usePreparedInsertBlade
1601 (
1602 'Atom',
1603 array
1604 (
1605 'molecule_id' => $molecule_id,
1606 'rack_id' => $rua['rack_id'],
1607 'unit_no' => $rua['unit_no'],
1608 'atom' => $rua['atom'],
1609 )
1610 );
1611 return $molecule_id;
1612 }
1613
1614 // History logger. This function assumes certain table naming convention and
1615 // column design:
1616 // - History table must have the same row set (w/o keys) plus one row named
1617 // 'ctime' of type 'timestamp'.
1618 function recordObjectHistory ($object_id)
1619 {
1620 global $remote_username;
1621 usePreparedExecuteBlade
1622 (
1623 'INSERT INTO ObjectHistory ' .
1624 'SELECT id, name, label, objtype_id, asset_no, has_problems, comment, ' .
1625 'CURRENT_TIMESTAMP(), ? FROM Object WHERE id=?',
1626 array ($remote_username, $object_id)
1627 );
1628 }
1629
1630 function getRackspaceHistory ()
1631 {
1632 $result = usePreparedSelectBlade
1633 (
1634 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
1635 "MountOperation ORDER BY ctime DESC"
1636 );
1637 return $result->fetchAll (PDO::FETCH_ASSOC);
1638 }
1639
1640 // This function is used in renderRackspaceHistory()
1641 function getOperationMolecules ($op_id)
1642 {
1643 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
1644 // We expect one row.
1645 $row = $result->fetch (PDO::FETCH_ASSOC);
1646 return array ($row['old_molecule_id'], $row['new_molecule_id']);
1647 }
1648
1649 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
1650 {
1651 $result = usePreparedSelectBlade
1652 (
1653 // Include racks that the object is directly mounted in
1654 "SELECT rack_id FROM RackSpace WHERE object_id = ? " .
1655 "UNION " .
1656 // Include racks that it's parent is mounted in
1657 "SELECT RS.rack_id FROM RackSpace RS INNER JOIN EntityLink EL ON RS.object_id = EL.parent_entity_id AND EL.parent_entity_type = 'object' WHERE EL.child_entity_id = ? AND EL.child_entity_type = 'object' " .
1658 "UNION " .
1659 // and racks that it is 'Zero-U' mounted in
1660 "SELECT parent_entity_id AS rack_id FROM EntityLink WHERE parent_entity_type = 'rack' AND child_entity_type = 'object' AND child_entity_id = ? " .
1661 'ORDER BY rack_id', array ($object_id, $object_id, $object_id)
1662 );
1663 $rows = $result->fetchAll (PDO::FETCH_NUM);
1664 unset ($result);
1665
1666 $ret = array();
1667 foreach ($rows as $row)
1668 if (! isset ($ret[$row[0]]))
1669 {
1670 if (!$fetch_rackdata)
1671 $rackData = $row[0];
1672 else
1673 {
1674 $rackData = spotEntity ('rack', $row[0]);
1675 amplifyCell ($rackData);
1676 }
1677 $ret[$row[0]] = $rackData;
1678 }
1679 return $ret;
1680 }
1681
1682 function commitAddPort ($object_id, $port_name, $port_type_id, $port_label, $port_l2address)
1683 {
1684 global $dbxlink;
1685 $db_l2address = l2addressForDatabase ($port_l2address);
1686 list ($iif_id, $oif_id) = parsePortIIFOIF ($port_type_id);
1687 // The conditional table locking is less relevant now due to syncObjectPorts().
1688 if ($db_l2address != '')
1689 $dbxlink->exec ('LOCK TABLES Port WRITE');
1690 try
1691 {
1692 assertUniqueL2Addresses (array ($db_l2address), $object_id);
1693 $ret = commitAddPortReal ($object_id, $port_name, $iif_id, $oif_id, $port_label, $db_l2address);
1694 }
1695 catch (Exception $e)
1696 {
1697 if ($db_l2address != '')
1698 $dbxlink->exec ('UNLOCK TABLES');
1699 throw $e;
1700 }
1701 if ($db_l2address != '')
1702 $dbxlink->exec ('UNLOCK TABLES');
1703 return $ret;
1704 }
1705
1706 // Having the call to assertUniqueL2Addresses() in this function would break things because
1707 // if the constraint check fails for any port the whole "transaction" needs to be rolled
1708 // back. Thus the calling function must call assertUniqueL2Addresses() for all involved ports
1709 // first and only then start making any calls to this function.
1710 function commitAddPortReal ($object_id, $port_name, $iif_id, $oif_id, $port_label, $db_l2address)
1711 {
1712 usePreparedInsertBlade
1713 (
1714 'Port',
1715 array
1716 (
1717 'name' => $port_name,
1718 'object_id' => $object_id,
1719 'label' => nullIfEmptyStr ($port_label),
1720 'iif_id' => $iif_id,
1721 'type' => $oif_id,
1722 'l2address' => nullIfEmptyStr ($db_l2address),
1723 )
1724 );
1725 lastCreated ('port', lastInsertID());
1726 return lastInsertID();
1727 }
1728
1729 function getPortReservationComment ($port_id, $extrasql = '')
1730 {
1731 $result = usePreparedSelectBlade ("SELECT reservation_comment FROM Port WHERE id = ? $extrasql", array ($port_id));
1732 return $result->fetchColumn();
1733 }
1734
1735 function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment)
1736 {
1737 global $dbxlink;
1738 $db_l2address = l2addressForDatabase ($port_l2address);
1739 list ($iif_id, $oif_id) = parsePortIIFOIF ($port_type_id);
1740 if ($db_l2address != '')
1741 $dbxlink->exec ('LOCK TABLES Port WRITE, PortLog WRITE');
1742 try
1743 {
1744 assertUniqueL2Addresses (array ($db_l2address), $object_id);
1745 commitUpdatePortReal ($object_id, $port_id, $port_name, $iif_id, $oif_id, $port_label, $db_l2address, $port_reservation_comment);
1746 }
1747 catch (Exception $e)
1748 {
1749 if ($db_l2address != '')
1750 $dbxlink->exec ('UNLOCK TABLES');
1751 throw $e;
1752 }
1753 if ($db_l2address != '')
1754 $dbxlink->exec ('UNLOCK TABLES');
1755 }
1756
1757 // The comment about commitAddPortReal() also applies here.
1758 function commitUpdatePortReal ($object_id, $port_id, $port_name, $iif_id, $oif_id, $port_label, $db_l2address, $port_reservation_comment)
1759 {
1760 $old_reservation_comment = getPortReservationComment ($port_id);
1761 $port_reservation_comment = nullIfEmptyStr ($port_reservation_comment);
1762 usePreparedUpdateBlade
1763 (
1764 'Port',
1765 array
1766 (
1767 'name' => $port_name,
1768 'iif_id' => $iif_id,
1769 'type' => $oif_id,
1770 'label' => nullIfEmptyStr ($port_label),
1771 'reservation_comment' => $port_reservation_comment,
1772 'l2address' => nullIfEmptyStr ($db_l2address),
1773 ),
1774 array
1775 (
1776 'id' => $port_id,
1777 'object_id' => $object_id
1778 )
1779 );
1780 if ($old_reservation_comment !== $port_reservation_comment)
1781 addPortLogEntry ($port_id, sprintf ("Reservation changed from '%s' to '%s'", $old_reservation_comment, $port_reservation_comment));
1782 }
1783
1784 function commitUpdatePortComment ($port_id, $port_reservation_comment)
1785 {
1786 global $dbxlink;
1787 $dbxlink->beginTransaction();
1788 $prev_comment = getPortReservationComment ($port_id, 'FOR UPDATE');
1789 $reservation_comment = nullIfEmptyStr ($port_reservation_comment);
1790 usePreparedUpdateBlade
1791 (
1792 'Port',
1793 array
1794 (
1795 'reservation_comment' => $reservation_comment,
1796 ),
1797 array
1798 (
1799 'id' => $port_id,
1800 )
1801 );
1802 if ($prev_comment !== $reservation_comment)
1803 addPortLogEntry ($port_id, sprintf ("Reservation changed from '%s' to '%s'", $prev_comment, $reservation_comment));
1804 $dbxlink->commit();
1805 }
1806
1807 function commitUpdatePortOIF ($port_id, $port_type_id)
1808 {
1809 usePreparedUpdateBlade
1810 (
1811 'Port',
1812 array ('type' => $port_type_id),
1813 array ('id' => $port_id)
1814 );
1815 }
1816
1817 function getAllIPv4Allocations ()
1818 {
1819 $result = usePreparedSelectBlade
1820 (
1821 "select object_id as object_id, ".
1822 "Object.name as object_name, ".
1823 "IPv4Allocation.name as name, ".
1824 "IPv4Allocation.type as type, ".
1825 "INET_NTOA(ip) as ip ".
1826 "from IPv4Allocation join Object on id=object_id "
1827 );
1828 return $result->fetchAll (PDO::FETCH_ASSOC);
1829 }
1830
1831 function linkPorts ($porta, $portb, $cable = NULL)
1832 {
1833 if ($porta == $portb)
1834 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
1835
1836 $result = usePreparedSelectBlade
1837 (
1838 'SELECT COUNT(*) FROM Link WHERE porta IN (?,?) OR portb IN (?,?)',
1839 array ($porta, $portb, $porta, $portb)
1840 );
1841 if ($result->fetchColumn () != 0)
1842 throw new RTDatabaseError ("Port ${porta} or ${portb} is already linked");
1843 unset ($result);
1844
1845 $ret = usePreparedInsertBlade
1846 (
1847 'Link',
1848 array
1849 (
1850 'porta' => $porta,
1851 'portb' => $portb,
1852 'cable' => nullIfEmptyStr ($cable),
1853 )
1854 );
1855 usePreparedUpdateBlade ('Port', array ('reservation_comment' => NULL), array ('id' => array ($porta, $portb)));
1856
1857 // log new links
1858 $result = usePreparedSelectBlade
1859 (
1860 "SELECT Port.id, Port.name as port_name, Object.name as obj_name FROM Port " .
1861 "INNER JOIN Object ON Port.object_id = Object.id WHERE Port.id IN (?, ?)",
1862 array ($porta, $portb)
1863 );
1864 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1865 unset ($result);
1866 foreach ($rows as $row)
1867 {
1868 $pair_id = ($row['id'] == $porta ? $portb : $porta);
1869 addPortLogEntry ($pair_id, sprintf ("linked to %s %s", $row['obj_name'], $row['port_name']));
1870 }
1871 return $ret;
1872 }
1873
1874 function commitUpdatePortLink ($port_id, $cable = NULL)
1875 {
1876 return usePreparedUpdateBlade
1877 (
1878 'Link',
1879 array ('cable' => nullIfEmptyStr ($cable)),
1880 array ('porta' => $port_id, 'portb' => $port_id),
1881 'OR'
1882 );
1883 }
1884
1885 function commitUnlinkPort ($port_id)
1886 {
1887 // fetch and log existing link
1888 $result = usePreparedSelectBlade
1889 (
1890 "SELECT pa.id AS id_a, pa.name AS port_name_a, oa.name AS obj_name_a, " .
1891 "pb.id AS id_b, pb.name AS port_name_b, ob.name AS obj_name_b " .
1892 "FROM " .
1893 "Link INNER JOIN Port pa ON pa.id = Link.porta " .
1894 "INNER JOIN Port pb ON pb.id = Link.portb " .
1895 "INNER JOIN RackObject oa ON pa.object_id = oa.id " .
1896 "INNER JOIN RackObject ob ON pb.object_id = ob.id " .
1897 "WHERE " .
1898 "Link.porta = ? OR Link.portb = ?",
1899 array ($port_id, $port_id)
1900 );
1901 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1902 unset ($result);
1903 foreach ($rows as $row)
1904 {
1905 addPortLogEntry ($row['id_a'], sprintf ("unlinked from %s %s", $row['obj_name_b'], $row['port_name_b']));
1906 addPortLogEntry ($row['id_b'], sprintf ("unlinked from %s %s", $row['obj_name_a'], $row['port_name_a']));
1907 }
1908
1909 // remove existing link
1910 return usePreparedDeleteBlade ('Link', array ('porta' => $port_id, 'portb' => $port_id), 'OR');
1911 }
1912
1913 function addPortLogEntry ($port_id, $message)
1914 {
1915 global $disable_logging;
1916 if (isset ($disable_logging) && $disable_logging)
1917 return;
1918 global $remote_username;
1919 usePreparedExecuteBlade
1920 (
1921 "INSERT INTO PortLog (port_id, user, date, message) VALUES (?, ?, NOW(), ?)",
1922 array ($port_id, $remote_username, $message)
1923 );
1924 }
1925
1926 function addIPLogEntry ($ip_bin, $message)
1927 {
1928 switch (strlen ($ip_bin))
1929 {
1930 case 4: return addIPv4LogEntry ($ip_bin, $message);
1931 case 16: return addIPv6LogEntry ($ip_bin, $message);
1932 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
1933 }
1934 }
1935
1936 function addIPv4LogEntry ($ip_bin, $message)
1937 {
1938 global $disable_logging;
1939 if (isset ($disable_logging) && $disable_logging)
1940 return;
1941 global $remote_username;
1942 usePreparedExecuteBlade
1943 (
1944 "INSERT INTO IPv4Log (ip, date, user, message) VALUES (?, NOW(), ?, ?)",
1945 array (ip4_bin2db ($ip_bin), $remote_username, $message)
1946 );
1947 }
1948
1949 function addIPv6LogEntry ($ip_bin, $message)
1950 {
1951 global $disable_logging;
1952 if (isset ($disable_logging) && $disable_logging)
1953 return;
1954 global $remote_username;
1955 usePreparedExecuteBlade
1956 (
1957 "INSERT INTO IPv6Log (ip, date, user, message) VALUES (?, NOW(), ?, ?)",
1958 array ($ip_bin, $remote_username, $message)
1959 );
1960 }
1961
1962 function fetchIPLogEntry ($ip_bin)
1963 {
1964 switch (strlen ($ip_bin))
1965 {
1966 case 4: return fetchIPv4LogEntry ($ip_bin);
1967 case 16: return fetchIPv6LogEntry ($ip_bin);
1968 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
1969 }
1970 }
1971
1972 function fetchIPv4LogEntry ($ip_bin)
1973 {
1974 $result = usePreparedSelectBlade
1975 (
1976 "SELECT date, user, message FROM IPv4Log WHERE ip = ? ORDER BY date ASC",
1977 array (ip4_bin2db ($ip_bin))
1978 );
1979 return $result->fetchAll (PDO::FETCH_ASSOC);
1980 }
1981
1982 function fetchIPv6LogEntry ($ip_bin)
1983 {
1984 $result = usePreparedSelectBlade
1985 (
1986 "SELECT date, user, message FROM IPv6Log WHERE ip = ? ORDER BY date ASC",
1987 array ($ip_bin)
1988 );
1989 return $result->fetchAll (PDO::FETCH_ASSOC);
1990 }
1991
1992 // wrapper around getObjectIPv4AllocationList and getObjectIPv6AllocationList
1993 function getObjectIPAllocationList ($object_id)
1994 {
1995 return
1996 getObjectIPv4AllocationList ($object_id) +
1997 getObjectIPv6AllocationList ($object_id);
1998 }
1999
2000 // Returns all IPv4 addresses allocated to object, but does not attach detailed info about address
2001 // Used instead of getObjectIPv4Allocations if you need perfomance but 'addrinfo' value
2002 function getObjectIPv4AllocationList ($object_id)
2003 {
2004 $ret = array();
2005 $result = usePreparedSelectBlade
2006 (
2007 'SELECT name AS osif, type, ip FROM IPv4Allocation ' .
2008 'WHERE object_id = ?',
2009 array ($object_id)
2010 );
2011 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2012 $ret[ip4_int2bin ($row['ip'])] = array ('osif' => $row['osif'], 'type' => $row['type']);
2013 return $ret;
2014 }
2015
2016 // Returns all IPv6 addresses allocated to object, but does not attach detailed info about address
2017 // Used instead of getObjectIPv6Allocations if you need perfomance but 'addrinfo' value
2018 function getObjectIPv6AllocationList ($object_id)
2019 {
2020 $ret = array();
2021 $result = usePreparedSelectBlade
2022 (
2023 'SELECT name AS osif, type, ip AS ip FROM IPv6Allocation ' .
2024 'WHERE object_id = ?',
2025 array ($object_id)
2026 );
2027 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2028 $ret[$row['ip']] = array ('osif' => $row['osif'], 'type' => $row['type']);
2029 return $ret;
2030 }
2031
2032 // Return all IP addresses allocated to the object sorted by allocation name.
2033 // Attach detailed info about address to each alocation records.
2034 // Index result by binary ip
2035 function getObjectIPAllocations ($object_id)
2036 {
2037 return amplifyAllocationList (getObjectIPAllocationList ($object_id));
2038 }
2039 function getObjectIPv4Allocations ($object_id)
2040 {
2041 return amplifyAllocationList (getObjectIPv4AllocationList ($object_id));
2042 }
2043 function getObjectIPv6Allocations ($object_id)
2044 {
2045 return amplifyAllocationList (getObjectIPv6AllocationList ($object_id));
2046 }
2047
2048 function amplifyAllocationList ($alloc_list)
2049 {
2050 $ret = array();
2051 $sorted = array();
2052 foreach ($alloc_list as $ip_bin => $alloc)
2053 $sorted[$alloc['osif']][$ip_bin] = $alloc;
2054 foreach (sortPortList ($sorted) as $osif => $subarray)
2055 foreach ($subarray as $ip_bin => $alloc)
2056 {
2057 $alloc['addrinfo'] = getIPAddress ($ip_bin);
2058 $ret[$ip_bin] = $alloc;
2059 }
2060 return $ret;
2061 }
2062
2063 function scanIPNet ($net_info, $filter_flags = IPSCAN_ANY)
2064 {
2065 $pairlist = array(
2066 array('first' => $net_info['ip_bin'], 'last' => ip_last ($net_info))
2067 );
2068 return scanIPSpace ($pairlist, $filter_flags);
2069 }
2070
2071 function scanIPSpace ($pairlist, $filter_flags = IPSCAN_ANY)
2072 {
2073 $v4_pairs = array();
2074 $v6_pairs = array();
2075 foreach ($pairlist as $pair)
2076 {
2077 if (strlen ($pair['first']) == 4)
2078 $v4_pairs[] = $pair;
2079 elseif (strlen ($pair['first']) == 16)
2080 $v6_pairs[] = $pair;
2081 }
2082 return
2083 scanIPv4Space ($v4_pairs, $filter_flags) +
2084 scanIPv6Space ($v6_pairs, $filter_flags);
2085 }
2086
2087 // Check the range requested for meaningful IPv4 records, build them
2088 // into a list and return. Return an empty list if nothing matched.
2089 // Both arguments are expected in 4-byte binary string form. The resulting list
2090 // is keyed by 4-byte binary IPs, items aren't sorted.
2091 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
2092 function scanIPv4Space ($pairlist, $filter_flags = IPSCAN_ANY)
2093 {
2094 $ret = array();
2095 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
2096 return $ret;
2097 $pairlist = reduceIPPairList ($pairlist);
2098 // FIXME: this is a copy-and-paste prototype
2099 $or = '';
2100 $whereexpr1 = '(';
2101 $whereexpr2 = '(';
2102 $whereexpr3a = '(';
2103 $whereexpr3b = '(';
2104 $whereexpr4 = '(';
2105 $whereexpr5a = '(';
2106 $whereexpr5b = '(';
2107 $whereexpr6 = '(';
2108 $qparams = array();
2109 $qparams_bin = array();
2110 foreach ($pairlist as $tmp)
2111 {
2112 $whereexpr1 .= $or . "ip between ? and ?";
2113 $whereexpr2 .= $or . "ip between ? and ?";
2114 $whereexpr3a .= $or . "vip between ? and ?";
2115 $whereexpr3b .= $or . "vip between ? and ?";
2116 $whereexpr4 .= $or . "rsip between ? and ?";
2117 $whereexpr5a .= $or . "remoteip between ? and ?";
2118 $whereexpr5b .= $or . "localip between ? and ?";
2119 $whereexpr6 .= $or . "l.ip between ? and ?";
2120 $or = ' or ';
2121 $qparams[] = ip4_bin2db ($tmp['first']);
2122 $qparams[] = ip4_bin2db ($tmp['last']);
2123 $qparams_bin[] = $tmp['first'];
2124 $qparams_bin[] = $tmp['last'];
2125 }
2126 $whereexpr1 .= ')';
2127 $whereexpr2 .= ')';
2128 $whereexpr3a .= ')';
2129 $whereexpr3b .= ')';
2130 $whereexpr4 .= ')';
2131 $whereexpr5a .= ')';
2132 $whereexpr5b .= ')';
2133 $whereexpr6 .= ')';
2134
2135 // 1. collect labels and reservations
2136 if ($filter_flags & IPSCAN_DO_ADDR)
2137 {
2138 $query = "select ip, name, comment, reserved from IPv4Address ".
2139 "where ${whereexpr1} and (reserved = 'yes' or name != '' or comment != '')";
2140 $result = usePreparedSelectBlade ($query, $qparams);
2141 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2142 {
2143 $ip_bin = ip4_int2bin ($row['ip']);
2144 if (!isset ($ret[$ip_bin]))
2145 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2146 $ret[$ip_bin]['name'] = $row['name'];
2147 $ret[$ip_bin]['comment'] = $row['comment'];
2148 $ret[$ip_bin]['reserved'] = $row['reserved'];
2149 }
2150 unset ($result);
2151 }
2152
2153 // 2. check for allocations
2154 if ($filter_flags & IPSCAN_DO_ALLOCS)
2155 {
2156 if ($filter_flags & IPSCAN_RTR_ONLY)
2157 $whereexpr2 .= " AND ia.type = 'router'";
2158 $query =
2159 "select ia.ip, ia.object_id, ia.name, ia.type, Object.name as object_name " .
2160 "from IPv4Allocation AS ia INNER JOIN Object ON ia.object_id = Object.id where ${whereexpr2} order by ia.type";
2161 $result = usePreparedSelectBlade ($query, $qparams);
2162 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2163 {
2164 $ip_bin = ip4_int2bin ($row['ip']);
2165 if (!isset ($ret[$ip_bin]))
2166 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2167 $ret[$ip_bin]['allocs'][] = array
2168 (
2169 'type' => $row['type'],
2170 'name' => $row['name'],
2171 'object_id' => $row['object_id'],
2172 'object_name' => $row['object_name'],
2173 );
2174 }
2175 unset ($result);
2176 }
2177
2178 // 3a. look for virtual services
2179 if ($filter_flags & IPSCAN_DO_VS)
2180 {
2181 $query = "select id, vip from IPv4VS where ${whereexpr3a}";
2182 $result = usePreparedSelectBlade ($query, $qparams_bin);
2183 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2184 unset ($result);
2185 foreach ($allRows as $row)
2186 {
2187 $ip_bin = $row['vip'];
2188 if (!isset ($ret[$ip_bin]))
2189 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2190 $ret[$ip_bin]['vslist'][] = $row['id'];
2191 }
2192
2193 // 3b. look for virtual service groups
2194 $query = "select vs_id, vip from VSIPs where ${whereexpr3b}";
2195 $result = usePreparedSelectBlade ($query, $qparams_bin);
2196 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2197 unset ($result);
2198 foreach ($allRows as $row)
2199 {
2200 $ip_bin = $row['vip'];
2201 if (!isset ($ret[$ip_bin]))
2202 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2203 $ret[$ip_bin]['vsglist'][] = $row['vs_id'];
2204 }
2205 }
2206
2207 // 4. don't forget about real servers along with pools
2208 if ($filter_flags & IPSCAN_DO_RS)
2209 {
2210 $query = "select rsip, rspool_id from IPv4RS where ${whereexpr4}";
2211 $result = usePreparedSelectBlade ($query, $qparams_bin);
2212 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2213 {
2214 $ip_bin = $row['rsip'];
2215 if (!isset ($ret[$ip_bin]))
2216 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2217 $ret[$ip_bin]['rsplist'][] = $row['rspool_id'];
2218 }
2219 unset ($result);
2220 }
2221
2222 // 5. add NAT rules, remote ip
2223 if ($filter_flags & IPSCAN_DO_NAT)
2224 {
2225 $query =
2226 "select " .
2227 "proto, " .
2228 "localip, " .
2229 "localport, " .
2230 "remoteip, " .
2231 "remoteport, " .
2232 "description " .
2233 "from IPv4NAT " .
2234 "where ${whereexpr5a} " .
2235 "order by localip, localport, remoteip, remoteport, proto";
2236 $result = usePreparedSelectBlade ($query, $qparams);
2237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2238 {
2239 $ip_bin_local = ip4_int2bin ($row['localip']);
2240 $ip_bin_remote = ip4_int2bin ($row['remoteip']);
2241 $row['localip_bin'] = $ip_bin_local;
2242 $row['remoteip_bin'] = $ip_bin_remote;
2243 $row['localip'] = ip_format ($ip_bin_local);
2244 $row['remoteip'] = ip_format ($ip_bin_remote);
2245 if (!isset ($ret[$ip_bin_remote]))
2246 $ret[$ip_bin_remote] = constructIPAddress ($ip_bin_remote);
2247 $ret[$ip_bin_remote]['inpf'][] = $row;
2248 }
2249 unset ($result);
2250 // 5. add NAT rules, local ip
2251 $query =
2252 "select " .
2253 "proto, " .
2254 "localip, " .
2255 "localport, " .
2256 "remoteip, " .
2257 "remoteport, " .
2258 "description " .
2259 "from IPv4NAT " .
2260 "where ${whereexpr5b} " .
2261 "order by localip, localport, remoteip, remoteport, proto";
2262 $result = usePreparedSelectBlade ($query, $qparams);
2263 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2264 {
2265 $ip_bin_local = ip4_int2bin ($row['localip']);
2266 $ip_bin_remote = ip4_int2bin ($row['remoteip']);
2267 $row['localip_bin'] = $ip_bin_local;
2268 $row['remoteip_bin'] = $ip_bin_remote;
2269 $row['localip'] = ip_format ($ip_bin_local);
2270 $row['remoteip'] = ip_format ($ip_bin_remote);
2271 if (!isset ($ret[$ip_bin_local]))
2272 $ret[$ip_bin_local] = constructIPAddress ($ip_bin_local);
2273 $ret[$ip_bin_local]['outpf'][] = $row;
2274 }
2275 unset ($result);
2276 }
2277
2278 // 6. collect last log message
2279 if ($filter_flags & IPSCAN_DO_LOG)
2280 {
2281 $query = "select l.ip, l.user, UNIX_TIMESTAMP(l.date) AS time from IPv4Log l INNER JOIN " .
2282 " (SELECT MAX(id) as id FROM IPv4Log GROUP BY ip) v USING (id) WHERE ${whereexpr6}";
2283 $result = usePreparedSelectBlade ($query, $qparams);
2284 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2285 {
2286 $ip_bin = ip4_int2bin ($row['ip']);
2287 if (isset ($ret[$ip_bin]))
2288 $ret[$ip_bin]['last_log'] = array
2289 (
2290 'user' => $row['user'],
2291 'time' => $row['time'],
2292 );
2293 }
2294 unset ($result);
2295 }
2296
2297 $override = callHook ('scanIPSpace_hook', $ret, $pairlist, $filter_flags);
2298 if (isset ($override))
2299 $ret = $override;
2300
2301 return $ret;
2302 }
2303
2304 // Check the range requested for meaningful IPv6 records, build them
2305 // into a list and return. Return an empty list if nothing matched.
2306 // Both arguments are expected as 16-byte binary IPs. The resulting list
2307 // is keyed by 16-byte bynary IPs, items aren't sorted.
2308 function scanIPv6Space ($pairlist, $filter_flags = IPSCAN_ANY)
2309 {
2310 $ret = array();
2311 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
2312 return $ret;
2313 $pairlist = reduceIPPairList ($pairlist);
2314
2315 $or = '';
2316 $whereexpr1 = '(';
2317 $whereexpr2 = '(';
2318 $whereexpr3a = '(';
2319 $whereexpr3b = '(';
2320 $whereexpr4 = '(';
2321 $whereexpr6 = '(';
2322 $qparams = array();
2323 foreach ($pairlist as $tmp)
2324 {
2325 $whereexpr1 .= $or . "ip between ? and ?";
2326 $whereexpr2 .= $or . "ip between ? and ?";
2327 $whereexpr3a .= $or . "vip between ? and ?";
2328 $whereexpr3b .= $or . "vip between ? and ?";
2329 $whereexpr4 .= $or . "rsip between ? and ?";
2330 $whereexpr6 .= $or . "l.ip between ? and ?";
2331 $or = ' or ';
2332 $qparams[] = $tmp['first'];
2333 $qparams[] = $tmp['last'];
2334 }
2335 $whereexpr1 .= ')';
2336 $whereexpr2 .= ')';
2337 $whereexpr3a .= ')';
2338 $whereexpr3b .= ')';
2339 $whereexpr4 .= ')';
2340 $whereexpr6 .= ')';
2341
2342 // 1. collect labels and reservations
2343 if ($filter_flags & IPSCAN_DO_ADDR)
2344 {
2345 $query = "select ip, name, comment, reserved from IPv6Address ".
2346 "where ${whereexpr1} and (reserved = 'yes' or name != '' or comment != '')";
2347 $result = usePreparedSelectBlade ($query, $qparams);
2348 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2349 {
2350 $ip_bin = $row['ip'];
2351 if (!isset ($ret[$ip_bin]))
2352 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2353 $ret[$ip_bin]['name'] = $row['name'];
2354 $ret[$ip_bin]['comment'] = $row['comment'];
2355 $ret[$ip_bin]['reserved'] = $row['reserved'];
2356 }
2357 unset ($result);
2358 }
2359
2360 // 2. check for allocations
2361 if ($filter_flags & IPSCAN_DO_ALLOCS)
2362 {
2363 if ($filter_flags & IPSCAN_RTR_ONLY)
2364 $whereexpr2 .= " AND ia.type = 'router'";
2365 $query =
2366 "select ia.ip, ia.object_id, ia.name, ia.type, Object.name as object_name " .
2367 "from IPv6Allocation AS ia INNER JOIN Object ON ia.object_id = Object.id where ${whereexpr2} order by ia.type";
2368 $result = usePreparedSelectBlade ($query, $qparams);
2369 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2370 {
2371 $ip_bin = $row['ip'];
2372 if (!isset ($ret[$ip_bin]))
2373 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2374 $ret[$ip_bin]['allocs'][] = array
2375 (
2376 'type' => $row['type'],
2377 'name' => $row['name'],
2378 'object_id' => $row['object_id'],
2379 'object_name' => $row['object_name'],
2380 );
2381 }
2382 unset ($result);
2383 }
2384
2385 // 3a. look for virtual services
2386 if ($filter_flags & IPSCAN_DO_VS)
2387 {
2388 $query = "select id, vip from IPv4VS where ${whereexpr3a}";
2389 $result = usePreparedSelectBlade ($query, $qparams);
2390 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2391 unset ($result);
2392 foreach ($allRows as $row)
2393 {
2394 $ip_bin = $row['vip'];
2395 if (!isset ($ret[$ip_bin]))
2396 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2397 $ret[$ip_bin]['vslist'][] = $row['id'];
2398 }
2399
2400 // 3b. look for virtual service groups
2401 $query = "select vs_id, vip from VSIPs where ${whereexpr3b}";
2402 $result = usePreparedSelectBlade ($query, $qparams);
2403 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2404 unset ($result);
2405 foreach ($allRows as $row)
2406 {
2407 $ip_bin = $row['vip'];
2408 if (!isset ($ret[$ip_bin]))
2409 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2410 $ret[$ip_bin]['vsglist'][] = $row['vs_id'];
2411 }
2412 }
2413
2414 // 4. don't forget about real servers along with pools
2415 if ($filter_flags & IPSCAN_DO_RS)
2416 {
2417 $query = "select rsip, rspool_id from IPv4RS where ${whereexpr4}";
2418 $result = usePreparedSelectBlade ($query, $qparams);
2419 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2420 {
2421 $ip_bin = $row['rsip'];
2422 if (!isset ($ret[$ip_bin]))
2423 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2424 $ret[$ip_bin]['rsplist'][] = $row['rspool_id'];
2425 }
2426 unset ($result);
2427 }
2428
2429 // 6. collect last log message
2430 if ($filter_flags & IPSCAN_DO_LOG)
2431 {
2432 $query = "select l.ip, l.user, UNIX_TIMESTAMP(l.date) AS time from IPv6Log l INNER JOIN " .
2433 " (SELECT MAX(id) as id FROM IPv6Log GROUP BY ip) v USING (id) WHERE ${whereexpr6}";
2434 $result = usePreparedSelectBlade ($query, $qparams);
2435 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2436 {
2437 $ip_bin = $row['ip'];
2438 if (isset ($ret[$ip_bin]))
2439 $ret[$ip_bin]['last_log'] = array
2440 (
2441 'user' => $row['user'],
2442 'time' => $row['time'],
2443 );
2444 }
2445 unset ($result);
2446 }
2447
2448 $override = callHook ('scanIPSpace_hook', $ret, $pairlist, $filter_flags);
2449 if (isset ($override))
2450 $ret = $override;
2451
2452 return $ret;
2453 }
2454
2455 function bindIPToObject ($ip_bin, $object_id = 0, $name = '', $type = '')
2456 {
2457 switch (strlen ($ip_bin))
2458 {
2459 case 4:
2460 $db_ip = ip4_bin2db ($ip_bin);
2461 $table = 'IPv4Allocation';
2462 $table2 = 'IPv4Address';
2463 break;
2464 case 16:
2465 $db_ip = $ip_bin;
2466 $table = 'IPv6Allocation';
2467 $table2 = 'IPv6Address';
2468 break;
2469 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2470 }
2471
2472 // release IP reservation and/or comment if configured
2473 $release = getConfigVar ('IPV4_AUTO_RELEASE');
2474 if ($release >= 2)
2475 usePreparedExecuteBlade ("DELETE FROM $table2 WHERE ip = ?", array ($db_ip));
2476 elseif ($release >= 1)
2477 usePreparedExecuteBlade ("UPDATE $table2 SET reserved = 'no' WHERE ip = ?", array ($db_ip));
2478
2479 usePreparedInsertBlade
2480 (
2481 $table,
2482 array ('ip' => $db_ip, 'object_id' => $object_id, 'name' => $name, 'type' => $type)
2483 );
2484 // store history line
2485 $cell = spotEntity ('object', $object_id);
2486 setDisplayedName ($cell);
2487 addIPLogEntry ($ip_bin, "Binded with ${cell['dname']}, ifname=$name");
2488 }
2489
2490 function bindIPv4ToObject ($ip_bin, $object_id = 0, $name = '', $type = '')
2491 {
2492 if (strlen ($ip_bin) != 4)
2493 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2494 return bindIPToObject ($ip_bin, $object_id, $name, $type);
2495 }
2496
2497 function bindIPv6ToObject ($ip_bin, $object_id = 0, $name = '', $type = '')
2498 {
2499 if (strlen ($ip_bin) != 16)
2500 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2501 return bindIPToObject ($ip_bin, $object_id, $name, $type);
2502 }
2503
2504 // Universal v4/v6 wrapper around getIPv4AddressNetworkId and getIPv6AddressNetworkId.
2505 // Return the id of the smallest IP network containing the given IP address
2506 // or NULL, if nothing was found. When finding the covering network for
2507 // another network, it is important to filter out matched records with longer
2508 // masks (they aren't going to be the right pick).
2509 function getIPAddressNetworkId ($ip_bin, $masklen = NULL)
2510 {
2511 switch (strlen ($ip_bin))
2512 {
2513 case 4: return getIPv4AddressNetworkId ($ip_bin, isset ($masklen) ? $masklen : 32);
2514 case 16: return getIPv6AddressNetworkId ($ip_bin, isset ($masklen) ? $masklen : 128);
2515 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2516 }
2517 }
2518
2519 // Returns ipv4net or ipv6net entity, or NULL if no spanning network found.
2520 // Throws an exception if $ip_bin is not valid binary address;
2521 function spotNetworkByIP ($ip_bin, $masklen = NULL)
2522 {
2523 $net_id = getIPAddressNetworkId ($ip_bin, $masklen);
2524 if (! $net_id)
2525 return NULL;
2526 switch (strlen ($ip_bin))
2527 {
2528 case 4: return spotEntity ('ipv4net', $net_id);
2529 case 16: return spotEntity ('ipv6net', $net_id);
2530 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2531 }
2532 }
2533
2534 // Return the id of the smallest IPv4 network containing the given IPv4 address
2535 // or NULL, if nothing was found. When finding the covering network for
2536 // another network, it is important to filter out matched records with longer
2537 // masks (they aren't going to be the right pick).
2538 function getIPv4AddressNetworkId ($ip_bin, $masklen = 32)
2539 {
2540 $row = callHook ('fetchIPv4AddressNetworkRow', $ip_bin, $masklen);
2541 return $row === NULL ? NULL : $row['id'];
2542 }
2543
2544 function fetchIPAddressNetworkRow ($ip_bin, $masklen = NULL)
2545 {
2546 switch (strlen ($ip_bin))
2547 {
2548 case 4:
2549 return callHook ('fetchIPv4AddressNetworkRow', $ip_bin, isset ($masklen) ? $masklen : 32);
2550 case 16:
2551 return callHook ('fetchIPv6AddressNetworkRow', $ip_bin, isset ($masklen) ? $masklen : 128);
2552 default:
2553 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary address");
2554 }
2555 }
2556
2557 function fetchIPv4AddressNetworkRow ($ip_bin, $masklen = 32)
2558 {
2559 $ip_db = ip4_bin2db ($ip_bin);
2560 $result = usePreparedSelectBlade
2561 (
2562 'SELECT id, ip, mask, name, comment FROM IPv4Network ' .
2563 'WHERE ? & (4294967295 >> (32 - mask)) << (32 - mask) = ip AND ip <= ? AND mask < ? ' .
2564 'ORDER BY mask DESC LIMIT 1',
2565 array ($ip_db, $ip_db, $masklen)
2566 );
2567 return nullIfFalse ($result->fetch (PDO::FETCH_ASSOC));
2568 }
2569
2570 // Return the id of the smallest IPv6 network containing the given IPv6 address
2571 // ($ip is an instance of IPv4Address class) or NULL, if nothing was found.
2572 function getIPv6AddressNetworkId ($ip_bin, $masklen = 128)
2573 {
2574 $row = callHook ('fetchIPv6AddressNetworkRow', $ip_bin, $masklen);
2575 return $row === NULL ? NULL : $row['id'];
2576 }
2577
2578 function fetchIPv6AddressNetworkRow ($ip_bin, $masklen = 128)
2579 {
2580 $result = usePreparedSelectBlade
2581 (
2582 'SELECT id, ip, mask, last_ip, name, comment FROM IPv6Network ' .
2583 'WHERE ip <= ? AND last_ip >= ? AND mask < ? ' .
2584 'ORDER BY mask DESC LIMIT 1',
2585 array ($ip_bin, $ip_bin, $masklen)
2586 );
2587 return nullIfFalse ($result->fetch (PDO::FETCH_ASSOC));
2588 }
2589
2590 // This function is actually used not only to update, but also to create records,
2591 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
2592 // (MySQL 4.0 workaround).
2593 function updateAddress ($ip_bin, $name = '', $reserved = 'no', $comment)
2594 {
2595 switch (strlen ($ip_bin))
2596 {
2597 case 4:
2598 $table = 'IPv4Address';
2599 $db_ip = ip4_bin2db ($ip_bin);
2600 break;
2601 case 16:
2602 $table = 'IPv6Address';
2603 $db_ip = $ip_bin;
2604 break;
2605 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2606 }
2607
2608 // compute update log message
2609 $result = usePreparedSelectBlade ("SELECT name, comment, reserved FROM $table WHERE ip = ?", array ($db_ip));
2610 $old_name = '';
2611 $old_comment = '';
2612 if ($row = $result->fetch (PDO::FETCH_ASSOC))
2613 {
2614 $old_name = $row['name'];
2615 $old_comment = $row['comment'];
2616 }
2617
2618 // If the 'comment' argument was specified when this function was called, use it.
2619 // If not, retain the old value.
2620 $comment = (func_num_args () == 4 ) ? $comment : $old_comment;
2621 $new_row = array ('name' => $name, 'comment' => $comment, 'reserved' => $reserved);
2622 $new_row_empty = $name == '' && $comment == '' && $reserved == 'no';
2623
2624 unset ($result);
2625 $messages = array ();
2626 if ($name != $old_name)
2627 {
2628 if ($name == '')
2629 $messages[] = "name '$old_name' removed";
2630 elseif ($old_name == '')
2631 $messages[] = "name set to '$name'";
2632 else
2633 $messages[] = "name changed from '$old_name' to '$name'";
2634 }
2635 if ($comment != $old_comment)
2636 {
2637 if ($comment == '')
2638 $messages[] = "comment '$old_comment' removed";
2639 elseif ($old_name == '')
2640 $messages[] = "comment set to '$comment'";
2641 else
2642 $messages[] = "comment changed from '$old_comment' to '$comment'";
2643 }
2644
2645 if ($row && ! $new_row_empty && $row == $new_row)
2646 return;
2647 if ($row)
2648 usePreparedDeleteBlade ($table, array ('ip' => $db_ip));
2649 // INSERT may appear not necessary.
2650 if (! $new_row_empty)
2651 usePreparedInsertBlade
2652 (
2653 $table,
2654 array ('name' => $name, 'comment' => $comment, 'reserved' => $reserved, 'ip' => $db_ip)
2655 );
2656 // store history line
2657 if ($messages)
2658 addIPLogEntry ($ip_bin, ucfirst (implode (', ', $messages)));
2659 }
2660
2661 function updateV4Address ($ip_bin, $name = '', $reserved = 'no', $comment = '')
2662 {
2663 if (strlen ($ip_bin) != 4)
2664 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2665 return updateAddress ($ip_bin, $name, $reserved, $comment);
2666 }
2667
2668 function updateV6Address ($ip_bin, $name = '', $reserved = 'no', $comment = '')
2669 {
2670 if (strlen ($ip_bin) != 16)
2671 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2672 return updateAddress ($ip_bin, $name, $reserved, $comment);
2673 }
2674
2675 function updateIPBond ($ip_bin, $object_id=0, $name='', $type='')
2676 {
2677 switch (strlen ($ip_bin))
2678 {
2679 case 4: return updateIPv4Bond ($ip_bin, $object_id, $name, $type);
2680 case 16: return updateIPv6Bond ($ip_bin, $object_id, $name, $type);
2681 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2682 }
2683 }
2684
2685 function updateIPv4Bond ($ip_bin, $object_id=0, $name='', $type='')
2686 {
2687 usePreparedUpdateBlade
2688 (
2689 'IPv4Allocation',
2690 array
2691 (
2692 'name' => $name,
2693 'type' => $type,
2694 ),
2695 array
2696 (
2697 'ip' => ip4_bin2db ($ip_bin),
2698 'object_id' => $object_id,
2699 )
2700 );
2701 }
2702
2703 function updateIPv6Bond ($ip_bin, $object_id=0, $name='', $type='')
2704 {
2705 usePreparedUpdateBlade
2706 (
2707 'IPv6Allocation',
2708 array
2709 (
2710 'name' => $name,
2711 'type' => $type,
2712 ),
2713 array
2714 (
2715 'ip' => $ip_bin,
2716 'object_id' => $object_id,
2717 )
2718 );
2719 }
2720
2721
2722 function unbindIPFromObject ($ip_bin, $object_id)
2723 {
2724 switch (strlen ($ip_bin))
2725 {
2726 case 4:
2727 $table = 'IPv4Allocation';
2728 $db_ip = ip4_bin2db ($ip_bin);
2729 break;
2730 case 16:
2731 $table = 'IPv6Allocation';
2732 $db_ip = $ip_bin;
2733 break;
2734 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2735 }
2736
2737 $n_deleted = usePreparedDeleteBlade
2738 (
2739 $table,
2740 array ('ip' => $db_ip, 'object_id' => $object_id)
2741 );
2742 if ($n_deleted)
2743 {
2744 // store history line
2745 $cell = spotEntity ('object', $object_id);
2746 setDisplayedName ($cell);
2747 addIPLogEntry ($ip_bin, "Removed from ${cell['dname']}");
2748 }
2749 }
2750
2751 function unbindIPv4FromObject ($ip_bin, $object_id)
2752 {
2753 if (strlen ($ip_bin) != 4)
2754 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2755 return unbindIPFromObject ($ip_bin, $object_id);
2756 }
2757
2758 function unbindIPv6FromObject ($ip_bin, $object_id)
2759 {
2760 if (strlen ($ip_bin) != 16)
2761 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2762 return unbindIPFromObject ($ip_bin, $object_id);
2763 }
2764
2765 function getIPv4PrefixSearchResult ($terms)
2766 {
2767 $ret = array();
2768 foreach (array ('name', 'comment') as $column)
2769 {
2770 $tmp = getSearchResultByField
2771 (
2772 'IPv4Network',
2773 array ('id'),
2774 $column,
2775 $terms,
2776 'ip'
2777 );
2778 foreach ($tmp as $row)
2779 {
2780 $ret[$row['id']] = spotEntity ('ipv4net', $row['id']);
2781 }
2782 }
2783 return $ret;
2784 }
2785
2786 function getIPv6PrefixSearchResult ($terms)
2787 {
2788 $byname = getSearchResultByField
2789 (
2790 'IPv6Network',
2791 array ('id'),
2792 'name',
2793 $terms,
2794 'ip'
2795 );
2796 $ret = array();
2797 foreach ($byname as $row)
2798 $ret[$row['id']] = spotEntity ('ipv6net', $row['id']);
2799 return $ret;
2800 }
2801
2802 function getIPv4AddressSearchResult ($terms)
2803 {
2804 $query = "select ip, name, comment from IPv4Address where ";
2805 $or = '';
2806 $qparams = array();
2807 foreach (explode (' ', $terms) as $term)
2808 {
2809 $query .= $or . "name like ? or comment like ?";
2810 $or = ' or ';
2811 $qparams[] = "%${term}%";
2812 $qparams[] = "%${term}%";
2813 }
2814 $result = usePreparedSelectBlade ($query, $qparams);
2815 $ret = array();
2816 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2817 {
2818 $ip_bin = ip4_int2bin ($row['ip']);
2819 $row['ip'] = $ip_bin;
2820 $ret[$ip_bin] = $row;
2821 }
2822 return $ret;
2823 }
2824
2825 function getIPv6AddressSearchResult ($terms)
2826 {
2827 $query = "select ip, name, comment from IPv6Address where ";
2828 $or = '';
2829 $qparams = array();
2830 foreach (explode (' ', $terms) as $term)
2831 {
2832 $query .= $or . "name like ? or comment like ?";
2833 $or = ' or ';
2834 $qparams[] = "%${term}%";
2835 $qparams[] = "%${term}%";
2836 }
2837 $result = usePreparedSelectBlade ($query, $qparams);
2838 return reindexById ($result->fetchAll (PDO::FETCH_ASSOC), 'ip');
2839 }
2840
2841 function getIPv4RSPoolSearchResult ($terms)
2842 {
2843 $byname = getSearchResultByField
2844 (
2845 'IPv4RSPool',
2846 array ('id'),
2847 'name',
2848 $terms,
2849 'name'
2850 );
2851 $ret = array();
2852 foreach ($byname as $row)
2853 $ret[$row['id']] = spotEntity ('ipv4rspool', $row['id']);
2854 return $ret;
2855 }
2856
2857 function getIPv4VServiceSearchResult ($terms)
2858 {
2859 $byname = getSearchResultByField
2860 (
2861 'IPv4VS',
2862 array ('id'),
2863 'name',
2864 $terms,
2865 'vip'
2866 );
2867 $ret = array();
2868 foreach ($byname as $row)
2869 $ret[$row['id']] = spotEntity ('ipv4vs', $row['id']);
2870 return $ret;
2871 }
2872
2873 function getVServiceSearchResult ($terms)
2874 {
2875 $byname = getSearchResultByField
2876 (
2877 'VS',
2878 array ('id'),
2879 'name',
2880 $terms,
2881 'name'
2882 );
2883 $ret = array();
2884 foreach ($byname as $row)
2885 $ret[$row['id']] = spotEntity ('ipvs', $row['id']);
2886 return $ret;
2887 }
2888
2889 function getAccountSearchResult ($terms)
2890 {
2891 $byUsername = getSearchResultByField
2892 (
2893 'UserAccount',
2894 array ('user_id', 'user_name', 'user_realname'),
2895 'user_name',
2896 $terms,
2897 'user_name'
2898 );
2899 $byRealname = getSearchResultByField
2900 (
2901 'UserAccount',
2902 array ('user_id', 'user_name', 'user_realname'),
2903 'user_realname',
2904 $terms,
2905 'user_name'
2906 );
2907 // Merge it together, if duplicates persist, byUsername wins
2908 $ret = array();
2909 foreach (array ($byRealname, $byUsername) as $array)
2910 foreach ($array as $user)
2911 {
2912 $user['realm'] = 'user';
2913 $user['id'] = $user['user_id'];
2914 $ret[$user['user_id']] = $user;
2915 }
2916 return $ret;
2917 }
2918
2919 function getFileSearchResult ($terms)
2920 {
2921 $byName = getSearchResultByField
2922 (
2923 'File',
2924 array ('id'),
2925 'name',
2926 $terms,
2927 'name'
2928 );
2929 $byComment = getSearchResultByField
2930 (
2931 'File',
2932 array ('id'),
2933 'comment',
2934 $terms,
2935 'name'
2936 );
2937 // Filter out dupes.
2938 foreach ($byName as $res1)
2939 foreach (array_keys ($byComment) as $key2)
2940 if ($res1['id'] == $byComment[$key2]['id'])
2941 {
2942 unset ($byComment[$key2]);
2943 continue 2;
2944 }
2945 $ret = array();
2946 foreach (array_merge ($byName, $byComment) as $row)
2947 $ret[$row['id']] = spotEntity ('file', $row['id']);
2948 return $ret;
2949 }
2950
2951 function getRackSearchResult ($terms)
2952 {
2953 $byName = getSearchResultByField
2954 (
2955 'Rack',
2956 array ('id'),
2957 'name',
2958 $terms,
2959 'name'
2960 );
2961 $byComment = getSearchResultByField
2962 (
2963 'Rack',
2964 array ('id'),
2965 'comment',
2966 $terms,
2967 'name'
2968 );
2969 $byAssetNo = getSearchResultByField
2970 (
2971 'Rack',
2972 array ('id'),
2973 'asset_no',
2974 $terms,
2975 'name'
2976 );
2977 $bySticker = getStickerSearchResults ('Rack', $terms);
2978 // Filter out dupes.
2979 foreach ($byName as $res1)
2980 {
2981 foreach (array_keys ($byComment) as $key2)
2982 if ($res1['id'] == $byComment[$key2]['id'])
2983 unset ($byComment[$key2]);
2984 foreach (array_keys ($byAssetNo) as $key3)
2985 if ($res1['id'] == $byAssetNo[$key3]['id'])
2986 unset ($byAssetNo[$key3]);
2987 foreach (array_keys ($bySticker) as $key4)
2988 if ($res1['id'] == $bySticker[$key4]['id'])
2989 unset ($bySticker[$key4]);
2990 }
2991 $ret = array();
2992 foreach (array_merge ($byName, $byComment, $byAssetNo, $bySticker) as $row)
2993 $ret[$row['id']] = spotEntity ('rack', $row['id']);
2994 return $ret;
2995 }
2996
2997 function getRowSearchResult ($terms)
2998 {
2999 $byName = getSearchResultByField
3000 (
3001 'Row',
3002 array ('id'),
3003 'name',
3004 $terms,
3005 'name'
3006 );
3007
3008 $ret = array();
3009 foreach ($byName as $row)
3010 $ret[$row['id']] = spotEntity ('row', $row['id']);
3011 return $ret;
3012 }
3013
3014 function getLocationSearchResult ($terms)
3015 {
3016 $byName = getSearchResultByField
3017 (
3018 'Location',
3019 array ('id'),
3020 'name',
3021 $terms,
3022 'name'
3023 );
3024 $byComment = getSearchResultByField
3025 (
3026 'Location',
3027 array ('id'),
3028 'comment',
3029 $terms,
3030 'name'
3031 );
3032 $bySticker = getStickerSearchResults ('Location', $terms);
3033 // Filter out dupes.
3034 foreach ($byName as $res1)
3035 {
3036 foreach (array_keys ($byComment) as $key2)
3037 if ($res1['id'] == $byComment[$key2]['id'])
3038 unset ($byComment[$key2]);
3039 foreach (array_keys ($bySticker) as $key3)
3040 if ($res1['id'] == $bySticker[$key3]['id'])
3041 unset ($bySticker[$key3]);
3042 }
3043 $ret = array();
3044 foreach (array_merge ($byName, $byComment, $bySticker) as $location)
3045 $ret[$location['id']] = spotEntity ('location', $location['id']);
3046 return $ret;
3047 }
3048
3049 function getVLANSearchResult ($terms)
3050 {
3051 $ret = array();
3052 $byDescr = getSearchResultByField
3053 (
3054 'VLANDescription',
3055 array ('domain_id', 'vlan_id'),
3056 'vlan_descr',
3057 $terms
3058 );
3059 foreach ($byDescr as $row)
3060 {
3061 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
3062 $row['id'] = $vlan_ck;
3063 $ret[$vlan_ck] = $row;
3064 }
3065 return $ret;
3066 }
3067
3068 function getSearchResultByField ($tablename, $retcolumns, $scancolumn, $terms, $ordercolumn = '', $exactness = 0)
3069 {
3070 $query = 'SELECT ' . implode (', ', $retcolumns) . " FROM ${tablename} WHERE ";
3071 $qparams = array();
3072 $pfx = '';
3073 $pterms = $exactness == 3 ? explode (' ', $terms) : parseSearchTerms ($terms);
3074 foreach ($pterms as $term)
3075 {
3076 switch ($exactness)
3077 {
3078 case 3:
3079 $query .= $pfx . "${scancolumn} REGEXP ?";
3080 $qparams[] = $term;
3081 break;
3082 case 2: // does this work as expected?
3083 $query .= $pfx . "BINARY ${scancolumn} = ?";
3084 $qparams[] = $term;
3085 break;
3086 case 1:
3087 $query .= $pfx . "${scancolumn} = ?";
3088 $qparams[] = $term;
3089 break;
3090 default:
3091 $query .= $pfx . "${scancolumn} LIKE ?";
3092 $qparams[] = "%${term}%";
3093 break;
3094 }
3095 $pfx = ' OR ';
3096 }
3097 if ($ordercolumn != '')
3098 $query .= " ORDER BY ${ordercolumn}";
3099 $result = usePreparedSelectBlade ($query, $qparams);
3100 return $result->fetchAll (PDO::FETCH_ASSOC);
3101 }
3102
3103 function getObjectSearchResults ($what)
3104 {
3105 $ret = array();
3106 global $searchfunc;
3107 foreach ($searchfunc['object'] as $method => $func)
3108 foreach ($func ($what) as $objRecord)
3109 {
3110 $ret[$objRecord['id']]['id'] = $objRecord['id'];
3111 $ret[$objRecord['id']][$method] = $objRecord[$method];
3112 }
3113 foreach (getStickerSearchResults ('RackObject', $what) as $objRecord)
3114 {
3115 $ret[$objRecord['id']]['id'] = $objRecord['id'];
3116 $ret[$objRecord['id']]['by_sticker'] = $objRecord['by_sticker'];
3117 }
3118 return $ret;
3119 }
3120
3121 function getObjectAttrsSearchResults ($what)
3122 {
3123 $ret = array();
3124 foreach (array ('name', 'label', 'asset_no', 'comment') as $column)
3125 {
3126 $tmp = getSearchResultByField
3127 (
3128 'RackObject',
3129 array ('id'),
3130 $column,
3131 $what,
3132 $column
3133 );
3134 foreach ($tmp as $row)
3135 {
3136 $ret[$row['id']]['id'] = $row['id'];
3137 $ret[$row['id']]['by_attr'][] = $column;
3138 }
3139 }
3140 return $ret;
3141 }
3142
3143 // Search stickers and return a list of pairs "object_id-attribute_id"
3144 // that matched. A partilar object_id could be returned more than once, if it has
3145 // multiple matching stickers. Search is only performed on "string" or "dict" attributes.
3146 function getStickerSearchResults ($tablename, $what)
3147 {
3148 $attr_types = array();
3149 $result = usePreparedSelectBlade
3150 (
3151 'SELECT AV.object_id, AV.attr_id FROM AttributeValue AV ' .
3152 "INNER JOIN ${tablename} O ON AV.object_id = O.id " .
3153 'INNER JOIN Attribute A ON AV.attr_id = A.id ' .
3154 'LEFT JOIN AttributeMap AM ON A.type = "dict" AND AV.object_tid = AM.objtype_id AND AV.attr_id = AM.attr_id ' .
3155 'LEFT JOIN Dictionary D ON AM.chapter_id = D.chapter_id AND AV.uint_value = D.dict_key ' .
3156 'WHERE string_value LIKE ? ' .
3157 'OR (A.type = "dict" AND dict_value LIKE ?) ORDER BY object_id',
3158 array ("%${what}%", "%${what}%")
3159 );
3160 $ret = array ();
3161 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3162 {
3163 if (! array_key_exists ($row['attr_id'], $attr_types))
3164 $attr_types[$row['attr_id']] = getAttrType ($row['attr_id']);
3165 if (in_array ($attr_types[$row['attr_id']], array ('string', 'dict')))
3166 {
3167 $ret[$row['object_id']]['id'] = $row['object_id'];
3168 $ret[$row['object_id']]['by_sticker'][] = $row['attr_id'];
3169 }
3170 }
3171 return $ret;
3172 }
3173
3174 // search in port "reservation comment", "label" and "L2 address" columns
3175 function getPortSearchResults ($what)
3176 {
3177 $ret = array();
3178 $ports = getSearchResultByField
3179 (
3180 'Port',
3181 array ('object_id', 'id', 'reservation_comment'),
3182 'reservation_comment',
3183 $what,
3184 'object_id',
3185 0
3186 );
3187 foreach ($ports as $port)
3188 {
3189 $ret[$port['object_id']]['id'] = $port['object_id'];
3190 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
3191 }
3192 $ports = getSearchResultByField
3193 (
3194 'Port',
3195 array ('object_id', 'id', 'label'),
3196 'label',
3197 $what,
3198 'object_id',
3199 0
3200 );
3201 foreach ($ports as $port)
3202 {
3203 $ret[$port['object_id']]['id'] = $port['object_id'];
3204 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
3205 }
3206 try
3207 {
3208 $db_l2address = l2addressForDatabase ($what);
3209 }
3210 catch (InvalidArgException $e)
3211 {
3212 return $ret;
3213 }
3214 $ports = getSearchResultByField
3215 (
3216 'Port',
3217 array ('object_id', 'id', 'l2address'),
3218 'l2address',
3219 $db_l2address,
3220 'object_id',
3221 2
3222 );
3223 foreach ($ports as $port)
3224 {
3225 $ret[$port['object_id']]['id'] = $port['object_id'];
3226 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
3227 }
3228 return $ret;
3229 }
3230
3231 // search in IPv4 allocations
3232 function getObjectIfacesSearchResults ($what)
3233 {
3234 $ret = array();
3235 $ifaces4 = getSearchResultByField
3236 (
3237 'IPv4Allocation',
3238 array ('object_id', 'name'),
3239 'name',
3240 $what,
3241 'object_id'
3242 );
3243 $ifaces6 = getSearchResultByField
3244 (
3245 'IPv6Allocation',
3246 array ('object_id', 'name'),
3247 'name',
3248 $what,
3249 'object_id'
3250 );
3251 foreach (array_merge ($ifaces4, $ifaces6) as $row)
3252 {
3253 $ret[$row['object_id']]['id'] = $row['object_id'];
3254 $ret[$row['object_id']]['by_iface'][] = $row['name'];
3255 }
3256 return $ret;
3257 }
3258
3259 function getObjectNATSearchResults ($what)
3260 {
3261 $ret = array();
3262 $ifaces = getSearchResultByField
3263 (
3264 'IPv4NAT',
3265 array ('object_id', 'description'),
3266 'description',
3267 $what,
3268 'object_id'
3269 );
3270 foreach ($ifaces as $row)
3271 {
3272 $ret[$row['object_id']]['id'] = $row['object_id'];
3273 $ret[$row['object_id']]['by_nat'][] = $row['description'];
3274 }
3275 return $ret;
3276 }
3277
3278 function searchCableIDs ($what)
3279 {
3280 $ret = array();
3281 $result = usePreparedSelectBlade
3282 (
3283 'SELECT object_id, cable ' .
3284 'FROM Link INNER JOIN Port ON porta = Port.id OR portb = Port.id ' .
3285 'WHERE cable LIKE ? ORDER BY object_id',
3286 array ("%${what}%")
3287 );
3288 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3289 {
3290 $ret[$row['object_id']]['id'] = $row['object_id'];
3291 $ret[$row['object_id']]['by_cableid'][] = $row['cable'];
3292 }
3293 return $ret;
3294 }
3295
3296 // This function returns either port ID or NULL for specified arguments.
3297 function getPortIDs ($object_id, $port_name)
3298 {
3299 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
3300 return reduceSubarraysToColumn ($result->fetchAll (PDO::FETCH_ASSOC), 'id');
3301 }
3302
3303 // Search in "FQDN" attribute only, and return object ID, when there is exactly
3304 // one result found (and NULL in any other case).
3305 function searchByMgmtHostname ($string)
3306 {
3307 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
3308 $rows = $result->fetchAll (PDO::FETCH_NUM);
3309 if (count ($rows) == 1)
3310 return $rows[0][0];
3311 unset ($result);
3312
3313 // second attempt: search for FQDN part, separated by dot.
3314 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value LIKE ? LIMIT 2', array ("$string.%"));
3315 $rows = $result->fetchAll (PDO::FETCH_NUM);
3316 return count ($rows) == 1 ? $rows[0][0] : NULL;
3317 }
3318
3319 // returns an array of object ids
3320 function searchByAttrValue ($attr_id, $value)
3321 {
3322 $type = getAttrType ($attr_id);
3323 if (! isset ($type))
3324 throw new InvalidArgException ('attr_id', $attr_id, "No such attribute");
3325
3326 switch ($type)
3327 {
3328 case 'string':
3329 $field = 'string_value';
3330 break;
3331 case 'float':
3332 $field = 'float_value';
3333 break;
3334 case 'uint':
3335 case 'dict':
3336 case 'date':
3337 $field = 'uint_value';
3338 break;
3339 default:
3340 throw new InvalidArgException ('type', $type);
3341 }
3342
3343 $result = usePreparedSelectBlade ("
3344 SELECT object_id FROM AttributeValue
3345 WHERE
3346 attr_id = ?
3347 AND $field = ?
3348 ", array ($attr_id, $value)
3349 );
3350 return $result->fetchAll (PDO::FETCH_COLUMN, 0);
3351 }
3352
3353
3354 // returns user_id
3355 // throws an exception if error occured
3356 function commitCreateUserAccount ($username, $realname, $password)
3357 {
3358 usePreparedInsertBlade
3359 (
3360 'UserAccount',
3361 array
3362 (
3363 'user_name' => $username,
3364 'user_realname' => $realname == '' ? NULL : $realname,
3365 'user_password_hash' => $password,
3366 )
3367 );
3368 $user_id = lastInsertID();
3369 lastCreated ('user', $user_id);
3370 return $user_id;
3371 }
3372
3373 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
3374 {
3375 usePreparedUpdateBlade
3376 (
3377 'UserAccount',
3378 array
3379 (
3380 'user_name' => $new_username,
3381 'user_realname' => $new_realname == '' ? NULL : $new_realname,
3382 'user_password_hash' => $new_password,
3383 ),
3384 array ('user_id' => $id)
3385 );
3386 }
3387
3388 // This function returns an array of all port type pairs from PortCompat table.
3389 function getPortOIFCompat ($ignore_cache = FALSE)
3390 {
3391 static $cache = NULL;
3392 if (! $ignore_cache && isset ($cache))
3393 return $cache;
3394
3395 $query =
3396 "SELECT type1, type2, POI1.oif_name AS type1name, POI2.oif_name AS type2name FROM " .
3397 "PortCompat AS pc INNER JOIN PortOuterInterface AS POI1 ON pc.t