add support for double quotes in the search string
[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 (SELECT COUNT(*) FROM PortLog WHERE PortLog.port_id = Port.id) AS log_count,
853 PortLog.user,
854 UNIX_TIMESTAMP(PortLog.date) as time
855 FROM
856 Port
857 INNER JOIN Object ON Port.object_id = Object.id
858 LEFT JOIN Link AS la ON la.porta = Port.id
859 LEFT JOIN Port AS pa ON pa.id = la.portb
860 LEFT JOIN Object AS oa ON pa.object_id = oa.id
861 LEFT JOIN Link AS lb on lb.portb = Port.id
862 LEFT JOIN Port AS pb ON pb.id = lb.porta
863 LEFT JOIN Object AS ob ON pb.object_id = ob.id
864 LEFT JOIN PortLog ON PortLog.id = (SELECT id FROM PortLog WHERE PortLog.port_id = Port.id ORDER BY date DESC LIMIT 1)
865 WHERE
866 $sql_where_clause
867 END;
868
869 $result = usePreparedSelectBlade ($query, $query_params);
870 $ret = array();
871 while ($row = $result->fetch (PDO::FETCH_ASSOC))
872 {
873 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
874 $row['linked'] = isset ($row['remote_id']) ? 1 : 0;
875
876 // last changed log
877 $row['last_log'] = array();
878 if ($row['log_count'])
879 {
880 $row['last_log']['user'] = $row['user'];
881 $row['last_log']['time'] = $row['time'];
882 }
883 unset ($row['user']);
884 unset ($row['time']);
885
886 $ret[] = $row;
887 }
888 return $ret;
889 }
890
891 function getObjectPortsAndLinks ($object_id, $sorted = TRUE)
892 {
893 $ret = fetchPortList ("Port.object_id = ?", array ($object_id));
894 if ($sorted)
895 $ret = sortPortList ($ret, TRUE);
896 return $ret;
897 }
898
899 // Fetch the object type via SQL.
900 // spotEntity cannot be used because it references RackObject, which doesn't suit Racks, Rows, or Locations.
901 function getObjectType ($object_id)
902 {
903 $result = usePreparedSelectBlade ('SELECT objtype_id from Object WHERE id = ?', array ($object_id));
904 return $result->fetchColumn ();
905 }
906
907 // If the given name is used by any object other than the current object,
908 // raise an exception. Validation is bypassed for certain object types
909 // where duplicates are acceptable.
910 // NOTE: This could be enforced more strictly at the database level using triggers.
911 function checkObjectNameUniqueness ($name, $type_id, $object_id = 0)
912 {
913 // Some object types do not need unique names
914 // 1560 - Rack
915 // 1561 - Row
916 $dupes_allowed = array (1560, 1561);
917 if (in_array ($type_id, $dupes_allowed))
918 return;
919
920 $result = usePreparedSelectBlade
921 (
922 'SELECT COUNT(*) FROM Object WHERE name = ? AND id != ?',
923 array ($name, $object_id)
924 );
925 $row = $result->fetch (PDO::FETCH_NUM);
926 if ($row[0] != 0)
927 throw new InvalidRequestArgException ('name', $name, 'An object with that name already exists');
928 }
929
930 function commitAddObject ($new_name, $new_label, $new_type_id, $new_asset_no, $taglist = array())
931 {
932 checkObjectNameUniqueness ($new_name, $new_type_id);
933 usePreparedInsertBlade
934 (
935 'Object',
936 array
937 (
938 'name' => nullIfEmptyStr ($new_name),
939 'label' => nullIfEmptyStr ($new_label),
940 'objtype_id' => $new_type_id,
941 'asset_no' => nullIfEmptyStr ($new_asset_no),
942 )
943 );
944 $object_id = lastInsertID();
945 switch ($new_type_id)
946 {
947 case 1560:
948 $realm = 'rack';
949 break;
950 case 1561:
951 $realm = 'row';
952 break;
953 case 1562:
954 $realm = 'location';
955 break;
956 default:
957 $realm = 'object';
958 }
959 lastCreated ($realm, $object_id);
960
961 // Do AutoPorts magic
962 if ($realm == 'object')
963 executeAutoPorts ($object_id);
964 // Now tags...
965 produceTagsForNewRecord ($realm, $taglist, $object_id);
966 recordObjectHistory ($object_id);
967 return $object_id;
968 }
969
970 function commitRenameObject ($object_id, $new_name)
971 {
972 $type_id = getObjectType ($object_id);
973 checkObjectNameUniqueness ($new_name, $type_id, $object_id);
974 usePreparedUpdateBlade
975 (
976 'Object',
977 array
978 (
979 'name' => nullIfEmptyStr ($new_name),
980 ),
981 array
982 (
983 'id' => $object_id
984 )
985 );
986 recordObjectHistory ($object_id);
987 }
988
989 function commitUpdateObject ($object_id, $new_name, $new_label, $new_has_problems, $new_asset_no, $new_comment)
990 {
991 $type_id = getObjectType ($object_id);
992 checkObjectNameUniqueness ($new_name, $type_id, $object_id);
993 usePreparedUpdateBlade
994 (
995 'Object',
996 array
997 (
998 'name' => nullIfEmptyStr ($new_name),
999 'label' => nullIfEmptyStr ($new_label),
1000 'has_problems' => $new_has_problems == '' ? 'no' : $new_has_problems,
1001 'asset_no' => nullIfEmptyStr ($new_asset_no),
1002 'comment' => nullIfEmptyStr ($new_comment),
1003 ),
1004 array
1005 (
1006 'id' => $object_id
1007 )
1008 );
1009 recordObjectHistory ($object_id);
1010 }
1011
1012 function compare_name ($a, $b)
1013 {
1014 return strnatcmp($a['name'], $b['name']);
1015 }
1016
1017 // find either parents or children of a record
1018 function getEntityRelatives ($type, $entity_type, $entity_id)
1019 {
1020 $ret = array();
1021
1022 if ($type == 'parents')
1023 {
1024 // searching for parents
1025 $sql =
1026 'SELECT id, parent_entity_type AS entity_type, parent_entity_id AS entity_id FROM EntityLink ' .
1027 'WHERE child_entity_type = ? AND child_entity_id = ?';
1028 }
1029 else
1030 {
1031 // searching for children
1032 $sql =
1033 'SELECT id, child_entity_type AS entity_type, child_entity_id AS entity_id FROM EntityLink ' .
1034 'WHERE parent_entity_type = ? AND parent_entity_id = ?';
1035 }
1036
1037 $result = usePreparedSelectBlade ($sql, array ($entity_type, $entity_id));
1038 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1039 $ret[$row['id']] = array(
1040 'entity_type' => $row['entity_type'],
1041 'entity_id' => $row['entity_id'],
1042 );
1043
1044 return $ret;
1045 }
1046
1047 function getParents ($entity, $result_realm = NULL)
1048 {
1049 return getRelatives ($entity, 'parents', $result_realm);
1050 }
1051
1052 function getChildren ($entity, $result_realm = NULL)
1053 {
1054 return getRelatives ($entity, 'children', $result_realm);
1055 }
1056
1057 function getRelatives ($entity, $type, $result_realm = NULL)
1058 {
1059 $ret = array();
1060 foreach (getEntityRelatives ($type, $entity['realm'], $entity['id']) as $link_id => $struct)
1061 if (! isset ($result_realm) || $result_realm == $struct['entity_type'])
1062 $ret[$link_id] = spotEntity ($struct['entity_type'], $struct['entity_id']);
1063 return $ret;
1064 }
1065
1066 // This function is recursive and returns only object IDs.
1067 function getObjectContentsList ($object_id, $children = array ())
1068 {
1069 $self = __FUNCTION__;
1070 $result = usePreparedSelectBlade
1071 (
1072 'SELECT child_entity_id FROM EntityLink ' .
1073 'WHERE parent_entity_type = "object" AND child_entity_type = "object" AND parent_entity_id = ?',
1074 array ($object_id)
1075 );
1076 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1077 unset ($result);
1078 foreach ($rows as $row)
1079 {
1080 if (in_array ($row['child_entity_id'], $children))
1081 throw new RackTablesError ("Circular reference for object ${object_id}", RackTablesError::INTERNAL);
1082 $children[] = $row['child_entity_id'];
1083 $children = array_unique (array_merge ($children, $self ($row['child_entity_id'], $children)));
1084 }
1085 return $children;
1086 }
1087
1088 // This function is recursive and returns only location IDs.
1089 function getLocationChildrenList ($location_id, $children = array ())
1090 {
1091 $self = __FUNCTION__;
1092 $result = usePreparedSelectBlade ('SELECT id FROM Location WHERE parent_id = ?', array ($location_id));
1093 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1094 unset ($result);
1095 foreach ($rows as $row)
1096 {
1097 if (in_array ($row['id'], $children))
1098 throw new RackTablesError ("Circular reference for location ${location_id}", RackTablesError::INTERNAL);
1099 $children[] = $row['id'];
1100 $children = array_unique (array_merge ($children, $self ($row['id'], $children)));
1101 }
1102 return $children;
1103 }
1104
1105 // DEPRECATED: use getTagDescendents() instead
1106 // This function is recursive and returns only tag IDs.
1107 function getTagChildrenList ($tag_id, $children = array ())
1108 {
1109 $self = __FUNCTION__;
1110 $result = usePreparedSelectBlade ('SELECT id FROM TagTree WHERE parent_id = ?', array ($tag_id));
1111 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1112 unset ($result);
1113 foreach ($rows as $row)
1114 {
1115 if (in_array ($row['id'], $children))
1116 throw new RackTablesError ("Circular reference for tag ${tag_id}", RackTablesError::INTERNAL);
1117 $children[] = $row['id'];
1118 $children = array_unique (array_merge ($children, $self ($row['id'], $children)));
1119 }
1120 return $children;
1121 }
1122
1123 function commitLinkEntities ($parent_entity_type, $parent_entity_id, $child_entity_type, $child_entity_id)
1124 {
1125 // a location's parent may not be one of its children
1126 if
1127 (
1128 $parent_entity_type == 'location' &&
1129 $child_entity_type == 'location' &&
1130 in_array ($parent_entity_id, getLocationChildrenList ($child_entity_id))
1131 )
1132 throw new RackTablesError ("Circular reference for location ${parent_entity_id}", RackTablesError::INTERNAL);
1133
1134 // an object's container may not be one of its contained objects
1135 if
1136 (
1137 $parent_entity_type == 'object' &&
1138 $child_entity_type == 'object' &&
1139 in_array ($parent_entity_id, getObjectContentsList ($child_entity_id))
1140 )
1141 throw new RackTablesError ("Circular reference for object ${parent_entity_id}", RackTablesError::INTERNAL);
1142
1143 usePreparedInsertBlade
1144 (
1145 'EntityLink',
1146 array
1147 (
1148 'parent_entity_type' => $parent_entity_type,
1149 'parent_entity_id' => $parent_entity_id,
1150 'child_entity_type' => $child_entity_type,
1151 'child_entity_id' => $child_entity_id,
1152 )
1153 );
1154 }
1155
1156 function commitUpdateEntityLink
1157 (
1158 $old_parent_entity_type, $old_parent_entity_id, $old_child_entity_type, $old_child_entity_id,
1159 $new_parent_entity_type, $new_parent_entity_id, $new_child_entity_type, $new_child_entity_id
1160 )
1161 {
1162 // a location's parent may not be one of its children
1163 if
1164 (
1165 $new_parent_entity_type == 'location' &&
1166 $new_child_entity_type == 'location' &&
1167 in_array ($new_parent_entity_id, getLocationChildrenList ($new_child_entity_id))
1168 )
1169 throw new RackTablesError ("Circular reference for location ${new_parent_entity_id}", RackTablesError::INTERNAL);
1170
1171 // an object's container may not be one of its contained objects
1172 if
1173 (
1174 $new_parent_entity_type == 'object' &&
1175 $new_child_entity_type == 'object' &&
1176 in_array ($new_parent_entity_id, getObjectContentsList ($new_child_entity_id))
1177 )
1178 throw new RackTablesError ("Circular reference for object ${new_parent_entity_id}", RackTablesError::INTERNAL);
1179
1180 usePreparedUpdateBlade
1181 (
1182 'EntityLink',
1183 array
1184 (
1185 'parent_entity_type' => $new_parent_entity_type,
1186 'parent_entity_id' => $new_parent_entity_id,
1187 'child_entity_type' => $new_child_entity_type,
1188 'child_entity_id' => $new_child_entity_id
1189 ),
1190 array
1191 (
1192 'parent_entity_type' => $old_parent_entity_type,
1193 'parent_entity_id' => $old_parent_entity_id,
1194 'child_entity_type' => $old_child_entity_type,
1195 'child_entity_id' => $old_child_entity_id
1196 )
1197 );
1198 }
1199
1200 function commitUnlinkEntities ($parent_entity_type, $parent_entity_id, $child_entity_type, $child_entity_id)
1201 {
1202 usePreparedDeleteBlade
1203 (
1204 'EntityLink',
1205 array
1206 (
1207 'parent_entity_type' => $parent_entity_type,
1208 'parent_entity_id' => $parent_entity_id,
1209 'child_entity_type' => $child_entity_type,
1210 'child_entity_id' => $child_entity_id
1211 )
1212 );
1213 }
1214
1215 function commitUnlinkEntitiesByLinkID ($link_id)
1216 {
1217 usePreparedDeleteBlade ('EntityLink', array ('id' => $link_id));
1218 }
1219
1220 // return VM clusters and corresponding stats
1221 // - number of hypervisors
1222 // - number of resource pools
1223 // - number of VMs whose parent is the cluster itself
1224 // - number of VMs whose parent is one of the resource pools in the cluster
1225 function getVMClusterSummary ()
1226 {
1227 $query = <<<END
1228 SELECT
1229 O.id,
1230 O.name,
1231 (SELECT COUNT(*) FROM EntityLink EL
1232 LEFT JOIN Object O_H ON EL.child_entity_id = O_H.id
1233 LEFT JOIN AttributeValue AV ON O_H.id = AV.object_id
1234 WHERE EL.parent_entity_type = 'object'
1235 AND EL.child_entity_type = 'object'
1236 AND EL.parent_entity_id = O.id
1237 AND O_H.objtype_id = 4
1238 AND AV.attr_id = 26
1239 AND AV.uint_value = 1501) AS hypervisors,
1240 (SELECT COUNT(*) FROM EntityLink EL
1241 LEFT JOIN Object O_RP ON EL.child_entity_id = O_RP.id
1242 WHERE EL.parent_entity_type = 'object'
1243 AND EL.child_entity_type = 'object'
1244 AND EL.parent_entity_id = O.id
1245 AND O_RP.objtype_id = 1506) AS resource_pools,
1246 (SELECT COUNT(*) FROM EntityLink EL
1247 LEFT JOIN Object O_C_VM ON EL.child_entity_id = O_C_VM.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_C_VM.objtype_id = 1504) AS cluster_vms,
1252 (SELECT COUNT(*) FROM EntityLink EL
1253 LEFT JOIN Object O_RP_VM ON EL.child_entity_id = O_RP_VM.id
1254 WHERE EL.parent_entity_type = 'object'
1255 AND EL.child_entity_type = 'object'
1256 AND EL.parent_entity_id IN
1257 (SELECT child_entity_id FROM EntityLink EL
1258 LEFT JOIN Object O_RP ON EL.child_entity_id = O_RP.id
1259 WHERE EL.parent_entity_type = 'object'
1260 AND EL.child_entity_type = 'object'
1261 AND EL.parent_entity_id = O.id
1262 AND O_RP.objtype_id = 1506)
1263 AND O_RP_VM.objtype_id = 1504) AS resource_pool_vms
1264 FROM Object O
1265 WHERE O.objtype_id = 1505
1266 ORDER BY O.name
1267 END;
1268 $result = usePreparedSelectBlade ($query);
1269 return $result->fetchAll (PDO::FETCH_ASSOC);
1270 }
1271
1272 function getVMResourcePoolSummary ()
1273 {
1274 $result = usePreparedSelectBlade
1275 (
1276 "SELECT O.id, O.name, " .
1277 "(SELECT O_C.id " .
1278 "FROM EntityLink EL " .
1279 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1280 "WHERE EL.child_entity_id = O.id " .
1281 "AND EL.parent_entity_type = 'object' " .
1282 "AND EL.child_entity_type = 'object' " .
1283 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_id, " .
1284 "(SELECT O_C.name " .
1285 "FROM EntityLink EL " .
1286 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1287 "WHERE EL.child_entity_id = O.id " .
1288 "AND EL.parent_entity_type = 'object' " .
1289 "AND EL.child_entity_type = 'object' " .
1290 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_name, " .
1291 "(SELECT COUNT(*) FROM EntityLink EL " .
1292 "LEFT JOIN Object O_VM ON EL.child_entity_id = O_VM.id " .
1293 "WHERE EL.parent_entity_type = 'object' " .
1294 "AND EL.child_entity_type = 'object' " .
1295 "AND EL.parent_entity_id = O.id " .
1296 "AND O_VM.objtype_id = 1504) AS VMs " .
1297 "FROM Object O " .
1298 "WHERE O.objtype_id = 1506 " .
1299 "ORDER BY O.name"
1300 );
1301 return $result->fetchAll (PDO::FETCH_ASSOC);
1302 }
1303
1304 function getVMHypervisorSummary ()
1305 {
1306 $result = usePreparedSelectBlade
1307 (
1308 "SELECT O.id, O.name, " .
1309 "(SELECT O_C.id " .
1310 "FROM EntityLink EL " .
1311 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1312 "WHERE EL.child_entity_id = O.id " .
1313 "AND EL.parent_entity_type = 'object' " .
1314 "AND EL.child_entity_type = 'object' " .
1315 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_id, " .
1316 "(SELECT O_C.name " .
1317 "FROM EntityLink EL " .
1318 "LEFT JOIN Object O_C ON EL.parent_entity_id = O_C.id " .
1319 "WHERE EL.child_entity_id = O.id " .
1320 "AND EL.parent_entity_type = 'object' " .
1321 "AND EL.child_entity_type = 'object' " .
1322 "AND O_C.objtype_id = 1505 LIMIT 1) AS cluster_name, " .
1323 "(SELECT COUNT(*) FROM EntityLink EL " .
1324 "LEFT JOIN Object O_VM ON EL.child_entity_id = O_VM.id " .
1325 "WHERE EL.parent_entity_type = 'object' " .
1326 "AND EL.child_entity_type = 'object' " .
1327 "AND EL.parent_entity_id = O.id " .
1328 "AND O_VM.objtype_id = 1504) AS VMs " .
1329 "FROM Object O " .
1330 "LEFT JOIN AttributeValue AV ON O.id = AV.object_id " .
1331 "WHERE O.objtype_id = 4 " .
1332 "AND AV.attr_id = 26 " .
1333 "AND AV.uint_value = 1501 " .
1334 "ORDER BY O.name"
1335 );
1336 return $result->fetchAll (PDO::FETCH_ASSOC);
1337 }
1338
1339 function getVMSwitchSummary ()
1340 {
1341 $result = usePreparedSelectBlade
1342 (
1343 "SELECT O.id, O.name " .
1344 "FROM Object O " .
1345 "WHERE O.objtype_id = 1507 " .
1346 "ORDER BY O.name"
1347 );
1348 return $result->fetchAll (PDO::FETCH_ASSOC);
1349 }
1350
1351 // Remove file links related to the entity, but leave the entity and file(s) intact.
1352 function releaseFiles ($entity_realm, $entity_id)
1353 {
1354 usePreparedDeleteBlade ('FileLink', array ('entity_type' => $entity_realm, 'entity_id' => $entity_id));
1355 }
1356
1357 // There are times when you want to delete all traces of an object
1358 function commitDeleteObject ($object_id)
1359 {
1360 // Reset most of stuff
1361 commitResetObject ($object_id);
1362 // Object itself
1363 usePreparedDeleteBlade ('Object', array ('id' => $object_id));
1364 // Dangling links
1365 usePreparedExecuteBlade
1366 (
1367 'DELETE FROM EntityLink WHERE ' .
1368 "(parent_entity_type IN ('rack', 'row', 'location') AND parent_entity_id = ?) OR " .
1369 "(child_entity_type IN ('rack', 'row', 'location') AND child_entity_id = ?)",
1370 array ($object_id, $object_id)
1371 );
1372 }
1373
1374 function commitResetObject ($object_id)
1375 {
1376 releaseFiles ('object', $object_id);
1377 destroyTagsForEntity ('object', $object_id);
1378 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
1379 usePreparedDeleteBlade ('IPv4Allocation', array ('object_id' => $object_id));
1380 usePreparedDeleteBlade ('IPv6Allocation', array ('object_id' => $object_id));
1381 usePreparedDeleteBlade ('IPv4NAT', array ('object_id' => $object_id));
1382 // Parent-child relationships
1383 usePreparedExecuteBlade
1384 (
1385 'DELETE FROM EntityLink WHERE ' .
1386 "(parent_entity_type = 'object' AND parent_entity_id = ?) OR (child_entity_type = 'object' AND child_entity_id = ?)",
1387 array ($object_id, $object_id)
1388 );
1389 // Rack space
1390 usePreparedExecuteBlade ('DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
1391 usePreparedExecuteBlade ('DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
1392 usePreparedDeleteBlade ('MountOperation', array ('object_id' => $object_id));
1393 usePreparedDeleteBlade ('RackSpace', array ('object_id' => $object_id));
1394 // 802.1Q
1395 usePreparedDeleteBlade ('PortVLANMode', array ('object_id' => $object_id));
1396 usePreparedDeleteBlade ('PortNativeVLAN', array ('object_id' => $object_id));
1397 usePreparedDeleteBlade ('PortAllowedVLAN', array ('object_id' => $object_id));
1398 usePreparedDeleteBlade ('CachedPVM', array ('object_id' => $object_id));
1399 usePreparedDeleteBlade ('VLANSwitch', array ('object_id' => $object_id));
1400 // SLB
1401 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
1402 usePreparedDeleteBlade ('VSEnabledIPs', array ('object_id' => $object_id));
1403 usePreparedDeleteBlade ('VSEnabledPorts', array ('object_id' => $object_id));
1404 // Ports & links
1405 usePreparedDeleteBlade ('Port', array ('object_id' => $object_id));
1406 // CN
1407 usePreparedUpdateBlade ('Object', array ('name' => NULL, 'label' => ''), array ('id' => $object_id));
1408 // FQDN
1409 commitUpdateAttrValue ($object_id, 3, "");
1410 // log history
1411 recordObjectHistory ($object_id);
1412 # Cacti graphs
1413 usePreparedDeleteBlade ('CactiGraph', array ('object_id' => $object_id));
1414 # Munin graphs
1415 usePreparedDeleteBlade ('MuninGraph', array ('object_id' => $object_id));
1416 # Do an additional reset if needed
1417 callHook ('resetObject_hook', $object_id);
1418 }
1419
1420 function commitUpdateRack ($rack_id, $new_row_id, $new_name, $new_height, $new_has_problems, $new_asset_no, $new_comment)
1421 {
1422 // Can't shrink a rack if rows being deleted contain mounted objects
1423 $check_result = usePreparedSelectBlade ('SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = ? AND unit_no > ?', array ($rack_id, $new_height));
1424 $check_row = $check_result->fetch (PDO::FETCH_ASSOC);
1425 unset ($check_result);
1426 if ($check_row['count'] > 0)
1427 throw new InvalidArgException ('new_height', $new_height, 'Cannot shrink rack, objects are still mounted there');
1428
1429 // Determine if the row changed
1430 $old_rack = spotEntity ('rack', $rack_id);
1431 $old_row_id = $old_rack['row_id'];
1432 if ($old_row_id != $new_row_id)
1433 {
1434 // Move it to the specified row
1435 usePreparedUpdateBlade
1436 (
1437 'EntityLink',
1438 array ('parent_entity_id' => $new_row_id),
1439 array ('child_entity_type' => 'rack', 'child_entity_id' => $rack_id)
1440 );
1441
1442 // Set the sort_order attribute so it's placed at the end of the new row
1443 $rowInfo = getRowInfo ($new_row_id);
1444 usePreparedUpdateBlade
1445 (
1446 'AttributeValue',
1447 array ('uint_value' => $rowInfo['count']),
1448 array ('object_id' => $rack_id, 'attr_id' => 29)
1449 );
1450
1451 // Reset the sort order of the old row
1452 resetRackSortOrder ($old_row_id);
1453 }
1454
1455 // Update the height
1456 commitUpdateAttrValue ($rack_id, 27, $new_height);
1457
1458 // Update the rack
1459 commitUpdateObject ($rack_id, $new_name, NULL, $new_has_problems, $new_asset_no, $new_comment);
1460 }
1461
1462 // Unmount all objects from the rack
1463 function commitCleanRack ($rack_id)
1464 {
1465 $rack = spotEntity ('rack', $rack_id);
1466 foreach (getChildren ($rack, 'object') as $child)
1467 commitUnlinkEntities ('rack', $rack_id, 'object', $child['id']);
1468 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
1469 usePreparedDeleteBlade ('RackThumbnail', array ('rack_id' => $rack_id));
1470 }
1471
1472 // Drop the rack
1473 function commitDeleteRack ($rack_id)
1474 {
1475 $rack = spotEntity ('rack', $rack_id);
1476 releaseFiles ('rack', $rack_id);
1477 destroyTagsForEntity ('rack', $rack_id);
1478 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
1479 commitDeleteObject ($rack_id);
1480 resetRackSortOrder ($rack['row_id']);
1481 }
1482
1483 // Drop the row with all racks inside
1484 function commitDeleteRow ($row_id)
1485 {
1486 $racks = getRacks ($row_id);
1487 foreach ($racks as $rack)
1488 commitDeleteRack ($rack['id']);
1489 commitDeleteObject ($row_id);
1490 }
1491
1492 // Returns mounted devices count in all racks inside the specified row
1493 function getRowMountsCount ($row_id)
1494 {
1495 $query =<<<END
1496 SELECT COUNT(*) FROM (
1497 SELECT object_id FROM RackSpace rs LEFT JOIN EntityLink el ON (rs.rack_id = el.child_entity_id)
1498 WHERE
1499 rs.object_id IS NOT NULL AND
1500 el.parent_entity_id = ? AND el.parent_entity_type = "row" AND el.child_entity_type = "rack"
1501 UNION
1502 SELECT el1.child_entity_id object_id FROM EntityLink el1 LEFT JOIN EntityLink el2 ON (el1.parent_entity_id = el2.child_entity_id)
1503 WHERE
1504 el1.parent_entity_type = "rack" AND el1.child_entity_type = "object" AND
1505 el2.parent_entity_id = ? AND el2.parent_entity_type = "row" AND el2.child_entity_type = "rack"
1506 ) x
1507 END;
1508 $result = usePreparedSelectBlade ($query, array ($row_id, $row_id));
1509 return $result->fetchColumn();
1510 }
1511
1512 // Returns mounted devices count in specified rack
1513 function getRackMountsCount ($rack_id)
1514 {
1515 $query =<<<END
1516 SELECT COUNT(*) FROM (
1517 SELECT object_id FROM RackSpace WHERE object_id IS NOT NULL AND rack_id = ?
1518 UNION
1519 SELECT child_entity_id object_id FROM EntityLink WHERE
1520 parent_entity_id = ? AND parent_entity_type = "rack" AND child_entity_type = "object"
1521 ) x
1522 END;
1523 $result = usePreparedSelectBlade ($query, array ($rack_id, $rack_id));
1524 return $result->fetchColumn();
1525 }
1526
1527 // Used when sort order is manually changed, and when a rack is moved or deleted
1528 // Input is expected to be a pre-sorted array of rack IDs
1529 function updateRackSortOrder ($racks)
1530 {
1531 for ($i = 0; $i<count($racks); $i++)
1532 {
1533 usePreparedUpdateBlade
1534 (
1535 'AttributeValue',
1536 array ('uint_value' => $i+1),
1537 array ('object_id' => $racks[$i], 'attr_id' => 29)
1538 );
1539 }
1540 }
1541
1542 function resetRackSortOrder ($row_id)
1543 {
1544 // Re-order the row's racks
1545 $racks = getRacks($row_id);
1546 $rack_ids = array ();
1547 foreach ($racks as $rack_id => $rackDetails)
1548 $rack_ids[] = $rack_id;
1549 updateRackSortOrder ($rack_ids);
1550 }
1551
1552 // This function builds a list of rack-unit-atom records assigned to
1553 // the requested object.
1554 function getMoleculeForObject ($object_id)
1555 {
1556 $result = usePreparedSelectBlade
1557 (
1558 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
1559 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
1560 array ($object_id)
1561 );
1562 return $result->fetchAll (PDO::FETCH_ASSOC);
1563 }
1564
1565 // This function builds a list of rack-unit-atom records for requested molecule.
1566 function getMolecule ($mid)
1567 {
1568 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
1569 return $result->fetchAll (PDO::FETCH_ASSOC);
1570 }
1571
1572 // returns exactly what is's named after
1573 function lastInsertID ()
1574 {
1575 $result = usePreparedSelectBlade ('select last_insert_id()');
1576 $row = $result->fetch (PDO::FETCH_NUM);
1577 return $row[0];
1578 }
1579
1580 // This function creates a new record in Molecule and number of linked
1581 // R-U-A records in Atom.
1582 function createMolecule ($molData)
1583 {
1584 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
1585 $molecule_id = lastInsertID();
1586 foreach ($molData as $rua)
1587 usePreparedInsertBlade
1588 (
1589 'Atom',
1590 array
1591 (
1592 'molecule_id' => $molecule_id,
1593 'rack_id' => $rua['rack_id'],
1594 'unit_no' => $rua['unit_no'],
1595 'atom' => $rua['atom'],
1596 )
1597 );
1598 return $molecule_id;
1599 }
1600
1601 // History logger. This function assumes certain table naming convention and
1602 // column design:
1603 // - History table must have the same row set (w/o keys) plus one row named
1604 // 'ctime' of type 'timestamp'.
1605 function recordObjectHistory ($object_id)
1606 {
1607 global $remote_username;
1608 usePreparedExecuteBlade
1609 (
1610 'INSERT INTO ObjectHistory ' .
1611 'SELECT id, name, label, objtype_id, asset_no, has_problems, comment, ' .
1612 'CURRENT_TIMESTAMP(), ? FROM Object WHERE id=?',
1613 array ($remote_username, $object_id)
1614 );
1615 }
1616
1617 function getRackspaceHistory ()
1618 {
1619 $result = usePreparedSelectBlade
1620 (
1621 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
1622 "MountOperation ORDER BY ctime DESC"
1623 );
1624 return $result->fetchAll (PDO::FETCH_ASSOC);
1625 }
1626
1627 // This function is used in renderRackspaceHistory()
1628 function getOperationMolecules ($op_id)
1629 {
1630 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
1631 // We expect one row.
1632 $row = $result->fetch (PDO::FETCH_ASSOC);
1633 return array ($row['old_molecule_id'], $row['new_molecule_id']);
1634 }
1635
1636 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
1637 {
1638 $result = usePreparedSelectBlade
1639 (
1640 // Include racks that the object is directly mounted in
1641 "SELECT rack_id FROM RackSpace WHERE object_id = ? " .
1642 "UNION " .
1643 // Include racks that it's parent is mounted in
1644 "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' " .
1645 "UNION " .
1646 // and racks that it is 'Zero-U' mounted in
1647 "SELECT parent_entity_id AS rack_id FROM EntityLink WHERE parent_entity_type = 'rack' AND child_entity_type = 'object' AND child_entity_id = ? " .
1648 'ORDER BY rack_id', array ($object_id, $object_id, $object_id)
1649 );
1650 $rows = $result->fetchAll (PDO::FETCH_NUM);
1651 unset ($result);
1652
1653 $ret = array();
1654 foreach ($rows as $row)
1655 if (! isset ($ret[$row[0]]))
1656 {
1657 if (!$fetch_rackdata)
1658 $rackData = $row[0];
1659 else
1660 {
1661 $rackData = spotEntity ('rack', $row[0]);
1662 amplifyCell ($rackData);
1663 }
1664 $ret[$row[0]] = $rackData;
1665 }
1666 return $ret;
1667 }
1668
1669 function commitAddPort ($object_id, $port_name, $port_type_id, $port_label, $port_l2address)
1670 {
1671 $db_l2address = l2addressForDatabase ($port_l2address);
1672 $matches = array();
1673 switch (1)
1674 {
1675 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
1676 $iif_id = $matches[1];
1677 $oif_id = $matches[2];
1678 break;
1679 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
1680 $iif_id = 1;
1681 $oif_id = $matches[1];
1682 break;
1683 default:
1684 throw new InvalidArgException ('port_type_id', $port_type_id, 'format error');
1685 }
1686 try
1687 {
1688 usePreparedInsertBlade
1689 (
1690 'Port',
1691 array
1692 (
1693 'name' => $port_name,
1694 'object_id' => $object_id,
1695 'label' => $port_label,
1696 'iif_id' => $iif_id,
1697 'type' => $oif_id,
1698 'l2address' => nullIfEmptyStr ($db_l2address),
1699 )
1700 );
1701 }
1702 catch (L2AddressException $e)
1703 {
1704 throw new InvalidRequestArgException ('port_l2address', $port_l2address, $e->getMessage());
1705 }
1706 lastCreated ('port', lastInsertID());
1707 return lastInsertID();
1708 }
1709
1710 function getPortReservationComment ($port_id, $extrasql = '')
1711 {
1712 $result = usePreparedSelectBlade ("SELECT reservation_comment FROM Port WHERE id = ? $extrasql", array ($port_id));
1713 return $result->fetchColumn();
1714 }
1715
1716 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
1717 // string value. In case it is omitted, we just assign it its current value.
1718 // It would be nice to simplify this semantics later.
1719 function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment)
1720 {
1721 $db_l2address = l2addressForDatabase ($port_l2address);
1722 $portinfo = getPortInfo ($port_id);
1723 $reservation_comment = nullIfEmptyStr ($port_reservation_comment);
1724 switch (1)
1725 {
1726 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
1727 $iif_id = $matches[1];
1728 $oif_id = $matches[2];
1729 break;
1730 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
1731 $iif_id = $portinfo['iif_id'];
1732 $oif_id = $matches[1];
1733 break;
1734 default:
1735 throw new InvalidArgException ('port_type_id', $port_type_id, 'format error');
1736 }
1737 try
1738 {
1739 usePreparedUpdateBlade
1740 (
1741 'Port',
1742 array
1743 (
1744 'name' => $port_name,
1745 'iif_id' => $iif_id,
1746 'type' => $oif_id,
1747 'label' => $port_label,
1748 'reservation_comment' => $reservation_comment,
1749 'l2address' => nullIfEmptyStr ($db_l2address),
1750 ),
1751 array
1752 (
1753 'id' => $port_id,
1754 'object_id' => $object_id
1755 )
1756 );
1757 }
1758 catch (L2AddressException $e)
1759 {
1760 throw new InvalidRequestArgException ('port_l2address', $port_l2address, $e->getMessage());
1761 }
1762 if ($portinfo['reservation_comment'] !== $reservation_comment)
1763 addPortLogEntry ($port_id, sprintf ("Reservation changed from '%s' to '%s'", $portinfo['reservation_comment'], $reservation_comment));
1764 }
1765
1766 function commitUpdatePortComment ($port_id, $port_reservation_comment)
1767 {
1768 global $dbxlink;
1769 $dbxlink->beginTransaction();
1770 $prev_comment = getPortReservationComment ($port_id, 'FOR UPDATE');
1771 $reservation_comment = nullIfEmptyStr ($port_reservation_comment);
1772 usePreparedUpdateBlade
1773 (
1774 'Port',
1775 array
1776 (
1777 'reservation_comment' => $reservation_comment,
1778 ),
1779 array
1780 (
1781 'id' => $port_id,
1782 )
1783 );
1784 if ($prev_comment !== $reservation_comment)
1785 addPortLogEntry ($port_id, sprintf ("Reservation changed from '%s' to '%s'", $prev_comment, $reservation_comment));
1786 $dbxlink->commit();
1787 }
1788
1789 function commitUpdatePortOIF ($port_id, $port_type_id)
1790 {
1791 usePreparedUpdateBlade
1792 (
1793 'Port',
1794 array ('type' => $port_type_id),
1795 array ('id' => $port_id)
1796 );
1797 }
1798
1799 function getAllIPv4Allocations ()
1800 {
1801 $result = usePreparedSelectBlade
1802 (
1803 "select object_id as object_id, ".
1804 "Object.name as object_name, ".
1805 "IPv4Allocation.name as name, ".
1806 "IPv4Allocation.type as type, ".
1807 "INET_NTOA(ip) as ip ".
1808 "from IPv4Allocation join Object on id=object_id "
1809 );
1810 return $result->fetchAll (PDO::FETCH_ASSOC);
1811 }
1812
1813 function linkPorts ($porta, $portb, $cable = NULL)
1814 {
1815 if ($porta == $portb)
1816 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
1817
1818 $result = usePreparedSelectBlade
1819 (
1820 'SELECT COUNT(*) FROM Link WHERE porta IN (?,?) OR portb IN (?,?)',
1821 array ($porta, $portb, $porta, $portb)
1822 );
1823 if ($result->fetchColumn () != 0)
1824 throw new RTDatabaseError ("Port ${porta} or ${portb} is already linked");
1825 unset ($result);
1826
1827 $ret = usePreparedInsertBlade
1828 (
1829 'Link',
1830 array
1831 (
1832 'porta' => $porta,
1833 'portb' => $portb,
1834 'cable' => nullIfEmptyStr ($cable),
1835 )
1836 );
1837 usePreparedUpdateBlade ('Port', array ('reservation_comment' => NULL), array ('id' => array ($porta, $portb)));
1838
1839 // log new links
1840 $result = usePreparedSelectBlade
1841 (
1842 "SELECT Port.id, Port.name as port_name, Object.name as obj_name FROM Port " .
1843 "INNER JOIN Object ON Port.object_id = Object.id WHERE Port.id IN (?, ?)",
1844 array ($porta, $portb)
1845 );
1846 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1847 unset ($result);
1848 foreach ($rows as $row)
1849 {
1850 $pair_id = ($row['id'] == $porta ? $portb : $porta);
1851 addPortLogEntry ($pair_id, sprintf ("linked to %s %s", $row['obj_name'], $row['port_name']));
1852 }
1853 return $ret;
1854 }
1855
1856 function commitUpdatePortLink ($port_id, $cable = NULL)
1857 {
1858 return usePreparedUpdateBlade
1859 (
1860 'Link',
1861 array ('cable' => nullIfEmptyStr ($cable)),
1862 array ('porta' => $port_id, 'portb' => $port_id),
1863 'OR'
1864 );
1865 }
1866
1867 function commitUnlinkPort ($port_id)
1868 {
1869 // fetch and log existing link
1870 $result = usePreparedSelectBlade
1871 (
1872 "SELECT pa.id AS id_a, pa.name AS port_name_a, oa.name AS obj_name_a, " .
1873 "pb.id AS id_b, pb.name AS port_name_b, ob.name AS obj_name_b " .
1874 "FROM " .
1875 "Link INNER JOIN Port pa ON pa.id = Link.porta " .
1876 "INNER JOIN Port pb ON pb.id = Link.portb " .
1877 "INNER JOIN RackObject oa ON pa.object_id = oa.id " .
1878 "INNER JOIN RackObject ob ON pb.object_id = ob.id " .
1879 "WHERE " .
1880 "Link.porta = ? OR Link.portb = ?",
1881 array ($port_id, $port_id)
1882 );
1883 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1884 unset ($result);
1885 foreach ($rows as $row)
1886 {
1887 addPortLogEntry ($row['id_a'], sprintf ("unlinked from %s %s", $row['obj_name_b'], $row['port_name_b']));
1888 addPortLogEntry ($row['id_b'], sprintf ("unlinked from %s %s", $row['obj_name_a'], $row['port_name_a']));
1889 }
1890
1891 // remove existing link
1892 return usePreparedDeleteBlade ('Link', array ('porta' => $port_id, 'portb' => $port_id), 'OR');
1893 }
1894
1895 function addPortLogEntry ($port_id, $message)
1896 {
1897 global $disable_logging;
1898 if (isset ($disable_logging) && $disable_logging)
1899 return;
1900 global $remote_username;
1901 usePreparedExecuteBlade
1902 (
1903 "INSERT INTO PortLog (port_id, user, date, message) VALUES (?, ?, NOW(), ?)",
1904 array ($port_id, $remote_username, $message)
1905 );
1906 }
1907
1908 function addIPLogEntry ($ip_bin, $message)
1909 {
1910 switch (strlen ($ip_bin))
1911 {
1912 case 4: return addIPv4LogEntry ($ip_bin, $message);
1913 case 16: return addIPv6LogEntry ($ip_bin, $message);
1914 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
1915 }
1916 }
1917
1918 function addIPv4LogEntry ($ip_bin, $message)
1919 {
1920 global $disable_logging;
1921 if (isset ($disable_logging) && $disable_logging)
1922 return;
1923 global $remote_username;
1924 usePreparedExecuteBlade
1925 (
1926 "INSERT INTO IPv4Log (ip, date, user, message) VALUES (?, NOW(), ?, ?)",
1927 array (ip4_bin2db ($ip_bin), $remote_username, $message)
1928 );
1929 }
1930
1931 function addIPv6LogEntry ($ip_bin, $message)
1932 {
1933 global $disable_logging;
1934 if (isset ($disable_logging) && $disable_logging)
1935 return;
1936 global $remote_username;
1937 usePreparedExecuteBlade
1938 (
1939 "INSERT INTO IPv6Log (ip, date, user, message) VALUES (?, NOW(), ?, ?)",
1940 array ($ip_bin, $remote_username, $message)
1941 );
1942 }
1943
1944 function fetchIPLogEntry ($ip_bin)
1945 {
1946 switch (strlen ($ip_bin))
1947 {
1948 case 4: return fetchIPv4LogEntry ($ip_bin);
1949 case 16: return fetchIPv6LogEntry ($ip_bin);
1950 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
1951 }
1952 }
1953
1954 function fetchIPv4LogEntry ($ip_bin)
1955 {
1956 $result = usePreparedSelectBlade
1957 (
1958 "SELECT date, user, message FROM IPv4Log WHERE ip = ? ORDER BY date ASC",
1959 array (ip4_bin2db ($ip_bin))
1960 );
1961 return $result->fetchAll (PDO::FETCH_ASSOC);
1962 }
1963
1964 function fetchIPv6LogEntry ($ip_bin)
1965 {
1966 $result = usePreparedSelectBlade
1967 (
1968 "SELECT date, user, message FROM IPv6Log WHERE ip = ? ORDER BY date ASC",
1969 array ($ip_bin)
1970 );
1971 return $result->fetchAll (PDO::FETCH_ASSOC);
1972 }
1973
1974 // wrapper around getObjectIPv4AllocationList and getObjectIPv6AllocationList
1975 function getObjectIPAllocationList ($object_id)
1976 {
1977 return
1978 getObjectIPv4AllocationList ($object_id) +
1979 getObjectIPv6AllocationList ($object_id);
1980 }
1981
1982 // Returns all IPv4 addresses allocated to object, but does not attach detailed info about address
1983 // Used instead of getObjectIPv4Allocations if you need perfomance but 'addrinfo' value
1984 function getObjectIPv4AllocationList ($object_id)
1985 {
1986 $ret = array();
1987 $result = usePreparedSelectBlade
1988 (
1989 'SELECT name AS osif, type, ip FROM IPv4Allocation ' .
1990 'WHERE object_id = ?',
1991 array ($object_id)
1992 );
1993 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1994 $ret[ip4_int2bin ($row['ip'])] = array ('osif' => $row['osif'], 'type' => $row['type']);
1995 return $ret;
1996 }
1997
1998 // Returns all IPv6 addresses allocated to object, but does not attach detailed info about address
1999 // Used instead of getObjectIPv6Allocations if you need perfomance but 'addrinfo' value
2000 function getObjectIPv6AllocationList ($object_id)
2001 {
2002 $ret = array();
2003 $result = usePreparedSelectBlade
2004 (
2005 'SELECT name AS osif, type, ip AS ip FROM IPv6Allocation ' .
2006 'WHERE object_id = ?',
2007 array ($object_id)
2008 );
2009 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2010 $ret[$row['ip']] = array ('osif' => $row['osif'], 'type' => $row['type']);
2011 return $ret;
2012 }
2013
2014 // Return all IP addresses allocated to the object sorted by allocation name.
2015 // Attach detailed info about address to each alocation records.
2016 // Index result by binary ip
2017 function getObjectIPAllocations ($object_id)
2018 {
2019 return amplifyAllocationList (getObjectIPAllocationList ($object_id));
2020 }
2021 function getObjectIPv4Allocations ($object_id)
2022 {
2023 return amplifyAllocationList (getObjectIPv4AllocationList ($object_id));
2024 }
2025 function getObjectIPv6Allocations ($object_id)
2026 {
2027 return amplifyAllocationList (getObjectIPv6AllocationList ($object_id));
2028 }
2029
2030 function amplifyAllocationList ($alloc_list)
2031 {
2032 $ret = array();
2033 $sorted = array();
2034 foreach ($alloc_list as $ip_bin => $alloc)
2035 $sorted[$alloc['osif']][$ip_bin] = $alloc;
2036 foreach (sortPortList ($sorted) as $osif => $subarray)
2037 foreach ($subarray as $ip_bin => $alloc)
2038 {
2039 $alloc['addrinfo'] = getIPAddress ($ip_bin);
2040 $ret[$ip_bin] = $alloc;
2041 }
2042 return $ret;
2043 }
2044
2045 function scanIPNet ($net_info, $filter_flags = IPSCAN_ANY)
2046 {
2047 $pairlist = array(
2048 array('first' => $net_info['ip_bin'], 'last' => ip_last ($net_info))
2049 );
2050 return scanIPSpace ($pairlist, $filter_flags);
2051 }
2052
2053 function scanIPSpace ($pairlist, $filter_flags = IPSCAN_ANY)
2054 {
2055 $v4_pairs = array();
2056 $v6_pairs = array();
2057 foreach ($pairlist as $pair)
2058 {
2059 if (strlen ($pair['first']) == 4)
2060 $v4_pairs[] = $pair;
2061 elseif (strlen ($pair['first']) == 16)
2062 $v6_pairs[] = $pair;
2063 }
2064 return
2065 scanIPv4Space ($v4_pairs, $filter_flags) +
2066 scanIPv6Space ($v6_pairs, $filter_flags);
2067 }
2068
2069 // Check the range requested for meaningful IPv4 records, build them
2070 // into a list and return. Return an empty list if nothing matched.
2071 // Both arguments are expected in 4-byte binary string form. The resulting list
2072 // is keyed by 4-byte binary IPs, items aren't sorted.
2073 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
2074 function scanIPv4Space ($pairlist, $filter_flags = IPSCAN_ANY)
2075 {
2076 $ret = array();
2077 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
2078 return $ret;
2079 $pairlist = reduceIPPairList ($pairlist);
2080 // FIXME: this is a copy-and-paste prototype
2081 $or = '';
2082 $whereexpr1 = '(';
2083 $whereexpr2 = '(';
2084 $whereexpr3a = '(';
2085 $whereexpr3b = '(';
2086 $whereexpr4 = '(';
2087 $whereexpr5a = '(';
2088 $whereexpr5b = '(';
2089 $whereexpr6 = '(';
2090 $qparams = array();
2091 $qparams_bin = array();
2092 foreach ($pairlist as $tmp)
2093 {
2094 $whereexpr1 .= $or . "ip between ? and ?";
2095 $whereexpr2 .= $or . "ip between ? and ?";
2096 $whereexpr3a .= $or . "vip between ? and ?";
2097 $whereexpr3b .= $or . "vip between ? and ?";
2098 $whereexpr4 .= $or . "rsip between ? and ?";
2099 $whereexpr5a .= $or . "remoteip between ? and ?";
2100 $whereexpr5b .= $or . "localip between ? and ?";
2101 $whereexpr6 .= $or . "l.ip between ? and ?";
2102 $or = ' or ';
2103 $qparams[] = ip4_bin2db ($tmp['first']);
2104 $qparams[] = ip4_bin2db ($tmp['last']);
2105 $qparams_bin[] = $tmp['first'];
2106 $qparams_bin[] = $tmp['last'];
2107 }
2108 $whereexpr1 .= ')';
2109 $whereexpr2 .= ')';
2110 $whereexpr3a .= ')';
2111 $whereexpr3b .= ')';
2112 $whereexpr4 .= ')';
2113 $whereexpr5a .= ')';
2114 $whereexpr5b .= ')';
2115 $whereexpr6 .= ')';
2116
2117 // 1. collect labels and reservations
2118 if ($filter_flags & IPSCAN_DO_ADDR)
2119 {
2120 $query = "select ip, name, comment, reserved from IPv4Address ".
2121 "where ${whereexpr1} and (reserved = 'yes' or name != '' or comment != '')";
2122 $result = usePreparedSelectBlade ($query, $qparams);
2123 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2124 {
2125 $ip_bin = ip4_int2bin ($row['ip']);
2126 if (!isset ($ret[$ip_bin]))
2127 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2128 $ret[$ip_bin]['name'] = $row['name'];
2129 $ret[$ip_bin]['comment'] = $row['comment'];
2130 $ret[$ip_bin]['reserved'] = $row['reserved'];
2131 }
2132 unset ($result);
2133 }
2134
2135 // 2. check for allocations
2136 if ($filter_flags & IPSCAN_DO_ALLOCS)
2137 {
2138 if ($filter_flags & IPSCAN_RTR_ONLY)
2139 $whereexpr2 .= " AND ia.type = 'router'";
2140 $query =
2141 "select ia.ip, ia.object_id, ia.name, ia.type, Object.name as object_name " .
2142 "from IPv4Allocation AS ia INNER JOIN Object ON ia.object_id = Object.id where ${whereexpr2} order by ia.type";
2143 $result = usePreparedSelectBlade ($query, $qparams);
2144 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2145 {
2146 $ip_bin = ip4_int2bin ($row['ip']);
2147 if (!isset ($ret[$ip_bin]))
2148 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2149 $ret[$ip_bin]['allocs'][] = array
2150 (
2151 'type' => $row['type'],
2152 'name' => $row['name'],
2153 'object_id' => $row['object_id'],
2154 'object_name' => $row['object_name'],
2155 );
2156 }
2157 unset ($result);
2158 }
2159
2160 // 3a. look for virtual services
2161 if ($filter_flags & IPSCAN_DO_VS)
2162 {
2163 $query = "select id, vip from IPv4VS where ${whereexpr3a}";
2164 $result = usePreparedSelectBlade ($query, $qparams_bin);
2165 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2166 unset ($result);
2167 foreach ($allRows as $row)
2168 {
2169 $ip_bin = $row['vip'];
2170 if (!isset ($ret[$ip_bin]))
2171 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2172 $ret[$ip_bin]['vslist'][] = $row['id'];
2173 }
2174
2175 // 3b. look for virtual service groups
2176 $query = "select vs_id, vip from VSIPs where ${whereexpr3b}";
2177 $result = usePreparedSelectBlade ($query, $qparams_bin);
2178 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2179 unset ($result);
2180 foreach ($allRows as $row)
2181 {
2182 $ip_bin = $row['vip'];
2183 if (!isset ($ret[$ip_bin]))
2184 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2185 $ret[$ip_bin]['vsglist'][] = $row['vs_id'];
2186 }
2187 }
2188
2189 // 4. don't forget about real servers along with pools
2190 if ($filter_flags & IPSCAN_DO_RS)
2191 {
2192 $query = "select rsip, rspool_id from IPv4RS where ${whereexpr4}";
2193 $result = usePreparedSelectBlade ($query, $qparams_bin);
2194 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2195 {
2196 $ip_bin = $row['rsip'];
2197 if (!isset ($ret[$ip_bin]))
2198 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2199 $ret[$ip_bin]['rsplist'][] = $row['rspool_id'];
2200 }
2201 unset ($result);
2202 }
2203
2204 // 5. add NAT rules, remote ip
2205 if ($filter_flags & IPSCAN_DO_NAT)
2206 {
2207 $query =
2208 "select " .
2209 "proto, " .
2210 "localip, " .
2211 "localport, " .
2212 "remoteip, " .
2213 "remoteport, " .
2214 "description " .
2215 "from IPv4NAT " .
2216 "where ${whereexpr5a} " .
2217 "order by localip, localport, remoteip, remoteport, proto";
2218 $result = usePreparedSelectBlade ($query, $qparams);
2219 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2220 {
2221 $ip_bin_local = ip4_int2bin ($row['localip']);
2222 $ip_bin_remote = ip4_int2bin ($row['remoteip']);
2223 $row['localip_bin'] = $ip_bin_local;
2224 $row['remoteip_bin'] = $ip_bin_remote;
2225 $row['localip'] = ip_format ($ip_bin_local);
2226 $row['remoteip'] = ip_format ($ip_bin_remote);
2227 if (!isset ($ret[$ip_bin_remote]))
2228 $ret[$ip_bin_remote] = constructIPAddress ($ip_bin_remote);
2229 $ret[$ip_bin_remote]['inpf'][] = $row;
2230 }
2231 unset ($result);
2232 // 5. add NAT rules, local ip
2233 $query =
2234 "select " .
2235 "proto, " .
2236 "localip, " .
2237 "localport, " .
2238 "remoteip, " .
2239 "remoteport, " .
2240 "description " .
2241 "from IPv4NAT " .
2242 "where ${whereexpr5b} " .
2243 "order by localip, localport, remoteip, remoteport, proto";
2244 $result = usePreparedSelectBlade ($query, $qparams);
2245 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2246 {
2247 $ip_bin_local = ip4_int2bin ($row['localip']);
2248 $ip_bin_remote = ip4_int2bin ($row['remoteip']);
2249 $row['localip_bin'] = $ip_bin_local;
2250 $row['remoteip_bin'] = $ip_bin_remote;
2251 $row['localip'] = ip_format ($ip_bin_local);
2252 $row['remoteip'] = ip_format ($ip_bin_remote);
2253 if (!isset ($ret[$ip_bin_local]))
2254 $ret[$ip_bin_local] = constructIPAddress ($ip_bin_local);
2255 $ret[$ip_bin_local]['outpf'][] = $row;
2256 }
2257 unset ($result);
2258 }
2259
2260 // 6. collect last log message
2261 if ($filter_flags & IPSCAN_DO_LOG)
2262 {
2263 $query = "select l.ip, l.user, UNIX_TIMESTAMP(l.date) AS time from IPv4Log l INNER JOIN " .
2264 " (SELECT MAX(id) as id FROM IPv4Log GROUP BY ip) v USING (id) WHERE ${whereexpr6}";
2265 $result = usePreparedSelectBlade ($query, $qparams);
2266 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2267 {
2268 $ip_bin = ip4_int2bin ($row['ip']);
2269 if (isset ($ret[$ip_bin]))
2270 $ret[$ip_bin]['last_log'] = array
2271 (
2272 'user' => $row['user'],
2273 'time' => $row['time'],
2274 );
2275 }
2276 unset ($result);
2277 }
2278
2279 $override = callHook ('scanIPSpace_hook', $ret, $pairlist, $filter_flags);
2280 if (isset ($override))
2281 $ret = $override;
2282
2283 return $ret;
2284 }
2285
2286 // Check the range requested for meaningful IPv6 records, build them
2287 // into a list and return. Return an empty list if nothing matched.
2288 // Both arguments are expected as 16-byte binary IPs. The resulting list
2289 // is keyed by 16-byte bynary IPs, items aren't sorted.
2290 function scanIPv6Space ($pairlist, $filter_flags = IPSCAN_ANY)
2291 {
2292 $ret = array();
2293 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
2294 return $ret;
2295 $pairlist = reduceIPPairList ($pairlist);
2296
2297 $or = '';
2298 $whereexpr1 = '(';
2299 $whereexpr2 = '(';
2300 $whereexpr3a = '(';
2301 $whereexpr3b = '(';
2302 $whereexpr4 = '(';
2303 $whereexpr6 = '(';
2304 $qparams = array();
2305 foreach ($pairlist as $tmp)
2306 {
2307 $whereexpr1 .= $or . "ip between ? and ?";
2308 $whereexpr2 .= $or . "ip between ? and ?";
2309 $whereexpr3a .= $or . "vip between ? and ?";
2310 $whereexpr3b .= $or . "vip between ? and ?";
2311 $whereexpr4 .= $or . "rsip between ? and ?";
2312 $whereexpr6 .= $or . "l.ip between ? and ?";
2313 $or = ' or ';
2314 $qparams[] = $tmp['first'];
2315 $qparams[] = $tmp['last'];
2316 }
2317 $whereexpr1 .= ')';
2318 $whereexpr2 .= ')';
2319 $whereexpr3a .= ')';
2320 $whereexpr3b .= ')';
2321 $whereexpr4 .= ')';
2322 $whereexpr6 .= ')';
2323
2324 // 1. collect labels and reservations
2325 if ($filter_flags & IPSCAN_DO_ADDR)
2326 {
2327 $query = "select ip, name, comment, reserved from IPv6Address ".
2328 "where ${whereexpr1} and (reserved = 'yes' or name != '' or comment != '')";
2329 $result = usePreparedSelectBlade ($query, $qparams);
2330 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2331 {
2332 $ip_bin = $row['ip'];
2333 if (!isset ($ret[$ip_bin]))
2334 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2335 $ret[$ip_bin]['name'] = $row['name'];
2336 $ret[$ip_bin]['comment'] = $row['comment'];
2337 $ret[$ip_bin]['reserved'] = $row['reserved'];
2338 }
2339 unset ($result);
2340 }
2341
2342 // 2. check for allocations
2343 if ($filter_flags & IPSCAN_DO_ALLOCS)
2344 {
2345 if ($filter_flags & IPSCAN_RTR_ONLY)
2346 $whereexpr2 .= " AND ia.type = 'router'";
2347 $query =
2348 "select ia.ip, ia.object_id, ia.name, ia.type, Object.name as object_name " .
2349 "from IPv6Allocation AS ia INNER JOIN Object ON ia.object_id = Object.id where ${whereexpr2} order by ia.type";
2350 $result = usePreparedSelectBlade ($query, $qparams);
2351 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2352 {
2353 $ip_bin = $row['ip'];
2354 if (!isset ($ret[$ip_bin]))
2355 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2356 $ret[$ip_bin]['allocs'][] = array
2357 (
2358 'type' => $row['type'],
2359 'name' => $row['name'],
2360 'object_id' => $row['object_id'],
2361 'object_name' => $row['object_name'],
2362 );
2363 }
2364 unset ($result);
2365 }
2366
2367 // 3a. look for virtual services
2368 if ($filter_flags & IPSCAN_DO_VS)
2369 {
2370 $query = "select id, vip from IPv4VS where ${whereexpr3a}";
2371 $result = usePreparedSelectBlade ($query, $qparams);
2372 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2373 unset ($result);
2374 foreach ($allRows as $row)
2375 {
2376 $ip_bin = $row['vip'];
2377 if (!isset ($ret[$ip_bin]))
2378 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2379 $ret[$ip_bin]['vslist'][] = $row['id'];
2380 }
2381
2382 // 3b. look for virtual service groups
2383 $query = "select vs_id, vip from VSIPs where ${whereexpr3b}";
2384 $result = usePreparedSelectBlade ($query, $qparams);
2385 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
2386 unset ($result);
2387 foreach ($allRows as $row)
2388 {
2389 $ip_bin = $row['vip'];
2390 if (!isset ($ret[$ip_bin]))
2391 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2392 $ret[$ip_bin]['vsglist'][] = $row['vs_id'];
2393 }
2394 }
2395
2396 // 4. don't forget about real servers along with pools
2397 if ($filter_flags & IPSCAN_DO_RS)
2398 {
2399 $query = "select rsip, rspool_id from IPv4RS where ${whereexpr4}";
2400 $result = usePreparedSelectBlade ($query, $qparams);
2401 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2402 {
2403 $ip_bin = $row['rsip'];
2404 if (!isset ($ret[$ip_bin]))
2405 $ret[$ip_bin] = constructIPAddress ($ip_bin);
2406 $ret[$ip_bin]['rsplist'][] = $row['rspool_id'];
2407 }
2408 unset ($result);
2409 }
2410
2411 // 6. collect last log message
2412 if ($filter_flags & IPSCAN_DO_LOG)
2413 {
2414 $query = "select l.ip, l.user, UNIX_TIMESTAMP(l.date) AS time from IPv6Log l INNER JOIN " .
2415 " (SELECT MAX(id) as id FROM IPv6Log GROUP BY ip) v USING (id) WHERE ${whereexpr6}";
2416 $result = usePreparedSelectBlade ($query, $qparams);
2417 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2418 {
2419 $ip_bin = $row['ip'];
2420 if (isset ($ret[$ip_bin]))
2421 $ret[$ip_bin]['last_log'] = array
2422 (
2423 'user' => $row['user'],
2424 'time' => $row['time'],
2425 );
2426 }
2427 unset ($result);
2428 }
2429
2430 $override = callHook ('scanIPSpace_hook', $ret, $pairlist, $filter_flags);
2431 if (isset ($override))
2432 $ret = $override;
2433
2434 return $ret;
2435 }
2436
2437 function bindIPToObject ($ip_bin, $object_id = 0, $name = '', $type = '')
2438 {
2439 switch (strlen ($ip_bin))
2440 {
2441 case 4:
2442 $db_ip = ip4_bin2db ($ip_bin);
2443 $table = 'IPv4Allocation';
2444 $table2 = 'IPv4Address';
2445 break;
2446 case 16:
2447 $db_ip = $ip_bin;
2448 $table = 'IPv6Allocation';
2449 $table2 = 'IPv6Address';
2450 break;
2451 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2452 }
2453
2454 // release IP reservation and/or comment if configured
2455 $release = getConfigVar ('IPV4_AUTO_RELEASE');
2456 if ($release >= 2)
2457 usePreparedExecuteBlade ("DELETE FROM $table2 WHERE ip = ?", array ($db_ip));
2458 elseif ($release >= 1)
2459 usePreparedExecuteBlade ("UPDATE $table2 SET reserved = 'no' WHERE ip = ?", array ($db_ip));
2460
2461 usePreparedInsertBlade
2462 (
2463 $table,
2464 array ('ip' => $db_ip, 'object_id' => $object_id, 'name' => $name, 'type' => $type)
2465 );
2466 // store history line
2467 $cell = spotEntity ('object', $object_id);
2468 setDisplayedName ($cell);
2469 addIPLogEntry ($ip_bin, "Binded with ${cell['dname']}, ifname=$name");
2470 }
2471
2472 function bindIPv4ToObject ($ip_bin, $object_id = 0, $name = '', $type = '')
2473 {
2474 if (strlen ($ip_bin) != 4)
2475 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2476 return bindIPToObject ($ip_bin, $object_id, $name, $type);
2477 }
2478
2479 function bindIPv6ToObject ($ip_bin, $object_id = 0, $name = '', $type = '')
2480 {
2481 if (strlen ($ip_bin) != 16)
2482 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2483 return bindIPToObject ($ip_bin, $object_id, $name, $type);
2484 }
2485
2486 // Universal v4/v6 wrapper around getIPv4AddressNetworkId and getIPv6AddressNetworkId.
2487 // Return the id of the smallest IP network containing the given IP address
2488 // or NULL, if nothing was found. When finding the covering network for
2489 // another network, it is important to filter out matched records with longer
2490 // masks (they aren't going to be the right pick).
2491 function getIPAddressNetworkId ($ip_bin, $masklen = NULL)
2492 {
2493 switch (strlen ($ip_bin))
2494 {
2495 case 4: return getIPv4AddressNetworkId ($ip_bin, isset ($masklen) ? $masklen : 32);
2496 case 16: return getIPv6AddressNetworkId ($ip_bin, isset ($masklen) ? $masklen : 128);
2497 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2498 }
2499 }
2500
2501 // Returns ipv4net or ipv6net entity, or NULL if no spanning network found.
2502 // Throws an exception if $ip_bin is not valid binary address;
2503 function spotNetworkByIP ($ip_bin, $masklen = NULL)
2504 {
2505 $net_id = getIPAddressNetworkId ($ip_bin, $masklen);
2506 if (! $net_id)
2507 return NULL;
2508 switch (strlen ($ip_bin))
2509 {
2510 case 4: return spotEntity ('ipv4net', $net_id);
2511 case 16: return spotEntity ('ipv6net', $net_id);
2512 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2513 }
2514 }
2515
2516 // Return the id of the smallest IPv4 network containing the given IPv4 address
2517 // or NULL, if nothing was found. When finding the covering network for
2518 // another network, it is important to filter out matched records with longer
2519 // masks (they aren't going to be the right pick).
2520 function getIPv4AddressNetworkId ($ip_bin, $masklen = 32)
2521 {
2522 $row = callHook ('fetchIPv4AddressNetworkRow', $ip_bin, $masklen);
2523 return $row === NULL ? NULL : $row['id'];
2524 }
2525
2526 function fetchIPAddressNetworkRow ($ip_bin, $masklen = NULL)
2527 {
2528 switch (strlen ($ip_bin))
2529 {
2530 case 4:
2531 return callHook ('fetchIPv4AddressNetworkRow', $ip_bin, isset ($masklen) ? $masklen : 32);
2532 case 16:
2533 return callHook ('fetchIPv6AddressNetworkRow', $ip_bin, isset ($masklen) ? $masklen : 128);
2534 default:
2535 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary address");
2536 }
2537 }
2538
2539 function fetchIPv4AddressNetworkRow ($ip_bin, $masklen = 32)
2540 {
2541 $ip_db = ip4_bin2db ($ip_bin);
2542 $result = usePreparedSelectBlade
2543 (
2544 'SELECT id, ip, mask, name, comment FROM IPv4Network ' .
2545 'WHERE ? & (4294967295 >> (32 - mask)) << (32 - mask) = ip AND ip <= ? AND mask < ? ' .
2546 'ORDER BY mask DESC LIMIT 1',
2547 array ($ip_db, $ip_db, $masklen)
2548 );
2549 return nullIfFalse ($result->fetch (PDO::FETCH_ASSOC));
2550 }
2551
2552 // Return the id of the smallest IPv6 network containing the given IPv6 address
2553 // ($ip is an instance of IPv4Address class) or NULL, if nothing was found.
2554 function getIPv6AddressNetworkId ($ip_bin, $masklen = 128)
2555 {
2556 $row = callHook ('fetchIPv6AddressNetworkRow', $ip_bin, $masklen);
2557 return $row === NULL ? NULL : $row['id'];
2558 }
2559
2560 function fetchIPv6AddressNetworkRow ($ip_bin, $masklen = 128)
2561 {
2562 $result = usePreparedSelectBlade
2563 (
2564 'SELECT id, ip, mask, last_ip, name, comment FROM IPv6Network ' .
2565 'WHERE ip <= ? AND last_ip >= ? AND mask < ? ' .
2566 'ORDER BY mask DESC LIMIT 1',
2567 array ($ip_bin, $ip_bin, $masklen)
2568 );
2569 return nullIfFalse ($result->fetch (PDO::FETCH_ASSOC));
2570 }
2571
2572 // This function is actually used not only to update, but also to create records,
2573 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
2574 // (MySQL 4.0 workaround).
2575 function updateAddress ($ip_bin, $name = '', $reserved = 'no', $comment)
2576 {
2577 switch (strlen ($ip_bin))
2578 {
2579 case 4:
2580 $table = 'IPv4Address';
2581 $db_ip = ip4_bin2db ($ip_bin);
2582 break;
2583 case 16:
2584 $table = 'IPv6Address';
2585 $db_ip = $ip_bin;
2586 break;
2587 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2588 }
2589
2590 // compute update log message
2591 $result = usePreparedSelectBlade ("SELECT name, comment, reserved FROM $table WHERE ip = ?", array ($db_ip));
2592 $old_name = '';
2593 $old_comment = '';
2594 if ($row = $result->fetch (PDO::FETCH_ASSOC))
2595 {
2596 $old_name = $row['name'];
2597 $old_comment = $row['comment'];
2598 }
2599
2600 // If the 'comment' argument was specified when this function was called, use it.
2601 // If not, retain the old value.
2602 $comment = (func_num_args () == 4 ) ? $comment : $old_comment;
2603 $new_row = array ('name' => $name, 'comment' => $comment, 'reserved' => $reserved);
2604 $new_row_empty = $name == '' && $comment == '' && $reserved == 'no';
2605
2606 unset ($result);
2607 $messages = array ();
2608 if ($name != $old_name)
2609 {
2610 if ($name == '')
2611 $messages[] = "name '$old_name' removed";
2612 elseif ($old_name == '')
2613 $messages[] = "name set to '$name'";
2614 else
2615 $messages[] = "name changed from '$old_name' to '$name'";
2616 }
2617 if ($comment != $old_comment)
2618 {
2619 if ($comment == '')
2620 $messages[] = "comment '$old_comment' removed";
2621 elseif ($old_name == '')
2622 $messages[] = "comment set to '$comment'";
2623 else
2624 $messages[] = "comment changed from '$old_comment' to '$comment'";
2625 }
2626
2627 if ($row && ! $new_row_empty && $row == $new_row)
2628 return;
2629 if ($row)
2630 usePreparedDeleteBlade ($table, array ('ip' => $db_ip));
2631 // INSERT may appear not necessary.
2632 if (! $new_row_empty)
2633 usePreparedInsertBlade
2634 (
2635 $table,
2636 array ('name' => $name, 'comment' => $comment, 'reserved' => $reserved, 'ip' => $db_ip)
2637 );
2638 // store history line
2639 if ($messages)
2640 addIPLogEntry ($ip_bin, ucfirst (implode (', ', $messages)));
2641 }
2642
2643 function updateV4Address ($ip_bin, $name = '', $reserved = 'no', $comment = '')
2644 {
2645 if (strlen ($ip_bin) != 4)
2646 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2647 return updateAddress ($ip_bin, $name, $reserved, $comment);
2648 }
2649
2650 function updateV6Address ($ip_bin, $name = '', $reserved = 'no', $comment = '')
2651 {
2652 if (strlen ($ip_bin) != 16)
2653 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2654 return updateAddress ($ip_bin, $name, $reserved, $comment);
2655 }
2656
2657 function updateIPBond ($ip_bin, $object_id=0, $name='', $type='')
2658 {
2659 switch (strlen ($ip_bin))
2660 {
2661 case 4: return updateIPv4Bond ($ip_bin, $object_id, $name, $type);
2662 case 16: return updateIPv6Bond ($ip_bin, $object_id, $name, $type);
2663 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2664 }
2665 }
2666
2667 function updateIPv4Bond ($ip_bin, $object_id=0, $name='', $type='')
2668 {
2669 usePreparedUpdateBlade
2670 (
2671 'IPv4Allocation',
2672 array
2673 (
2674 'name' => $name,
2675 'type' => $type,
2676 ),
2677 array
2678 (
2679 'ip' => ip4_bin2db ($ip_bin),
2680 'object_id' => $object_id,
2681 )
2682 );
2683 }
2684
2685 function updateIPv6Bond ($ip_bin, $object_id=0, $name='', $type='')
2686 {
2687 usePreparedUpdateBlade
2688 (
2689 'IPv6Allocation',
2690 array
2691 (
2692 'name' => $name,
2693 'type' => $type,
2694 ),
2695 array
2696 (
2697 'ip' => $ip_bin,
2698 'object_id' => $object_id,
2699 )
2700 );
2701 }
2702
2703
2704 function unbindIPFromObject ($ip_bin, $object_id)
2705 {
2706 switch (strlen ($ip_bin))
2707 {
2708 case 4:
2709 $table = 'IPv4Allocation';
2710 $db_ip = ip4_bin2db ($ip_bin);
2711 break;
2712 case 16:
2713 $table = 'IPv6Allocation';
2714 $db_ip = $ip_bin;
2715 break;
2716 default: throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2717 }
2718
2719 $n_deleted = usePreparedDeleteBlade
2720 (
2721 $table,
2722 array ('ip' => $db_ip, 'object_id' => $object_id)
2723 );
2724 if ($n_deleted)
2725 {
2726 // store history line
2727 $cell = spotEntity ('object', $object_id);
2728 setDisplayedName ($cell);
2729 addIPLogEntry ($ip_bin, "Removed from ${cell['dname']}");
2730 }
2731 }
2732
2733 function unbindIPv4FromObject ($ip_bin, $object_id)
2734 {
2735 if (strlen ($ip_bin) != 4)
2736 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2737 return unbindIPFromObject ($ip_bin, $object_id);
2738 }
2739
2740 function unbindIPv6FromObject ($ip_bin, $object_id)
2741 {
2742 if (strlen ($ip_bin) != 16)
2743 throw new InvalidArgException ('ip_bin', $ip_bin, "Invalid binary IP");
2744 return unbindIPFromObject ($ip_bin, $object_id);
2745 }
2746
2747 function getIPv4PrefixSearchResult ($terms)
2748 {
2749 $byname = getSearchResultByField
2750 (
2751 'IPv4Network',
2752 array ('id'),
2753 'name',
2754 $terms,
2755 'ip'
2756 );
2757 $ret = array();
2758 foreach ($byname as $row)
2759 $ret[$row['id']] = spotEntity ('ipv4net', $row['id']);
2760 return $ret;
2761 }
2762
2763 function getIPv6PrefixSearchResult ($terms)
2764 {
2765 $byname = getSearchResultByField
2766 (
2767 'IPv6Network',
2768 array ('id'),
2769 'name',
2770 $terms,
2771 'ip'
2772 );
2773 $ret = array();
2774 foreach ($byname as $row)
2775 $ret[$row['id']] = spotEntity ('ipv6net', $row['id']);
2776 return $ret;
2777 }
2778
2779 function getIPv4AddressSearchResult ($terms)
2780 {
2781 $query = "select ip, name, comment from IPv4Address where ";
2782 $or = '';
2783 $qparams = array();
2784 foreach (explode (' ', $terms) as $term)
2785 {
2786 $query .= $or . "name like ? or comment like ?";
2787 $or = ' or ';
2788 $qparams[] = "%${term}%";
2789 $qparams[] = "%${term}%";
2790 }
2791 $result = usePreparedSelectBlade ($query, $qparams);
2792 $ret = array();
2793 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2794 {
2795 $ip_bin = ip4_int2bin ($row['ip']);
2796 $row['ip'] = $ip_bin;
2797 $ret[$ip_bin] = $row;
2798 }
2799 return $ret;
2800 }
2801
2802 function getIPv6AddressSearchResult ($terms)
2803 {
2804 $query = "select ip, name, comment from IPv6Address 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 return reindexById ($result->fetchAll (PDO::FETCH_ASSOC), 'ip');
2816 }
2817
2818 function getIPv4RSPoolSearchResult ($terms)
2819 {
2820 $byname = getSearchResultByField
2821 (
2822 'IPv4RSPool',
2823 array ('id'),
2824 'name',
2825 $terms,
2826 'name'
2827 );
2828 $ret = array();
2829 foreach ($byname as $row)
2830 $ret[$row['id']] = spotEntity ('ipv4rspool', $row['id']);
2831 return $ret;
2832 }
2833
2834 function getIPv4VServiceSearchResult ($terms)
2835 {
2836 $byname = getSearchResultByField
2837 (
2838 'IPv4VS',
2839 array ('id'),
2840 'name',
2841 $terms,
2842 'vip'
2843 );
2844 $ret = array();
2845 foreach ($byname as $row)
2846 $ret[$row['id']] = spotEntity ('ipv4vs', $row['id']);
2847 return $ret;
2848 }
2849
2850 function getVServiceSearchResult ($terms)
2851 {
2852 $byname = getSearchResultByField
2853 (
2854 'VS',
2855 array ('id'),
2856 'name',
2857 $terms,
2858 'name'
2859 );
2860 $ret = array();
2861 foreach ($byname as $row)
2862 $ret[$row['id']] = spotEntity ('ipvs', $row['id']);
2863 return $ret;
2864 }
2865
2866 function getAccountSearchResult ($terms)
2867 {
2868 $byUsername = getSearchResultByField
2869 (
2870 'UserAccount',
2871 array ('user_id', 'user_name', 'user_realname'),
2872 'user_name',
2873 $terms,
2874 'user_name'
2875 );
2876 $byRealname = getSearchResultByField
2877 (
2878 'UserAccount',
2879 array ('user_id', 'user_name', 'user_realname'),
2880 'user_realname',
2881 $terms,
2882 'user_name'
2883 );
2884 // Merge it together, if duplicates persist, byUsername wins
2885 $ret = array();
2886 foreach (array ($byRealname, $byUsername) as $array)
2887 foreach ($array as $user)
2888 {
2889 $user['realm'] = 'user';
2890 $user['id'] = $user['user_id'];
2891 $ret[$user['user_id']] = $user;
2892 }
2893 return $ret;
2894 }
2895
2896 function getFileSearchResult ($terms)
2897 {
2898 $byName = getSearchResultByField
2899 (
2900 'File',
2901 array ('id'),
2902 'name',
2903 $terms,
2904 'name'
2905 );
2906 $byComment = getSearchResultByField
2907 (
2908 'File',
2909 array ('id'),
2910 'comment',
2911 $terms,
2912 'name'
2913 );
2914 // Filter out dupes.
2915 foreach ($byName as $res1)
2916 foreach (array_keys ($byComment) as $key2)
2917 if ($res1['id'] == $byComment[$key2]['id'])
2918 {
2919 unset ($byComment[$key2]);
2920 continue 2;
2921 }
2922 $ret = array();
2923 foreach (array_merge ($byName, $byComment) as $row)
2924 $ret[$row['id']] = spotEntity ('file', $row['id']);
2925 return $ret;
2926 }
2927
2928 function getRackSearchResult ($terms)
2929 {
2930 $byName = getSearchResultByField
2931 (
2932 'Rack',
2933 array ('id'),
2934 'name',
2935 $terms,
2936 'name'
2937 );
2938 $byComment = getSearchResultByField
2939 (
2940 'Rack',
2941 array ('id'),
2942 'comment',
2943 $terms,
2944 'name'
2945 );
2946 $byAssetNo = getSearchResultByField
2947 (
2948 'Rack',
2949 array ('id'),
2950 'asset_no',
2951 $terms,
2952 'name'
2953 );
2954 $bySticker = getStickerSearchResults ('Rack', $terms);
2955 // Filter out dupes.
2956 foreach ($byName as $res1)
2957 {
2958 foreach (array_keys ($byComment) as $key2)
2959 if ($res1['id'] == $byComment[$key2]['id'])
2960 unset ($byComment[$key2]);
2961 foreach (array_keys ($byAssetNo) as $key3)
2962 if ($res1['id'] == $byAssetNo[$key3]['id'])
2963 unset ($byAssetNo[$key3]);
2964 foreach (array_keys ($bySticker) as $key4)
2965 if ($res1['id'] == $bySticker[$key4]['id'])
2966 unset ($bySticker[$key4]);
2967 }
2968 $ret = array();
2969 foreach (array_merge ($byName, $byComment, $byAssetNo, $bySticker) as $row)
2970 $ret[$row['id']] = spotEntity ('rack', $row['id']);
2971 return $ret;
2972 }
2973
2974 function getRowSearchResult ($terms)
2975 {
2976 $byName = getSearchResultByField
2977 (
2978 'Row',
2979 array ('id'),
2980 'name',
2981 $terms,
2982 'name'
2983 );
2984
2985 $ret = array();
2986 foreach ($byName as $row)
2987 $ret[$row['id']] = spotEntity ('row', $row['id']);
2988 return $ret;
2989 }
2990
2991 function getLocationSearchResult ($terms)
2992 {
2993 $byName = getSearchResultByField
2994 (
2995 'Location',
2996 array ('id'),
2997 'name',
2998 $terms,
2999 'name'
3000 );
3001 $byComment = getSearchResultByField
3002 (
3003 'Location',
3004 array ('id'),
3005 'comment',
3006 $terms,
3007 'name'
3008 );
3009 $bySticker = getStickerSearchResults ('Location', $terms);
3010 // Filter out dupes.
3011 foreach ($byName as $res1)
3012 {
3013 foreach (array_keys ($byComment) as $key2)
3014 if ($res1['id'] == $byComment[$key2]['id'])
3015 unset ($byComment[$key2]);
3016 foreach (array_keys ($bySticker) as $key3)
3017 if ($res1['id'] == $bySticker[$key3]['id'])
3018 unset ($bySticker[$key3]);
3019 }
3020 $ret = array();
3021 foreach (array_merge ($byName, $byComment, $bySticker) as $location)
3022 $ret[$location['id']] = spotEntity ('location', $location['id']);
3023 return $ret;
3024 }
3025
3026 function getVLANSearchResult ($terms)
3027 {
3028 $ret = array();
3029 $byDescr = getSearchResultByField
3030 (
3031 'VLANDescription',
3032 array ('domain_id', 'vlan_id'),
3033 'vlan_descr',
3034 $terms
3035 );
3036 foreach ($byDescr as $row)
3037 {
3038 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
3039 $row['id'] = $vlan_ck;
3040 $ret[$vlan_ck] = $row;
3041 }
3042 return $ret;
3043 }
3044
3045 function getSearchResultByField ($tablename, $retcolumns, $scancolumn, $terms, $ordercolumn = '', $exactness = 0)
3046 {
3047 $query = 'SELECT ' . implode (', ', $retcolumns) . " FROM ${tablename} WHERE ";
3048 $qparams = array();
3049 $pfx = '';
3050 $pterms = $exactness == 3 ? explode (' ', $terms) : parseSearchTerms ($terms);
3051 foreach ($pterms as $term)
3052 {
3053 switch ($exactness)
3054 {
3055 case 3:
3056 $query .= $pfx . "${scancolumn} REGEXP ?";
3057 $qparams[] = $term;
3058 break;
3059 case 2: // does this work as expected?
3060 $query .= $pfx . "BINARY ${scancolumn} = ?";
3061 $qparams[] = $term;
3062 break;
3063 case 1:
3064 $query .= $pfx . "${scancolumn} = ?";
3065 $qparams[] = $term;
3066 break;
3067 default:
3068 $query .= $pfx . "${scancolumn} LIKE ?";
3069 $qparams[] = "%${term}%";
3070 break;
3071 }
3072 $pfx = ' OR ';
3073 }
3074 if ($ordercolumn != '')
3075 $query .= " ORDER BY ${ordercolumn}";
3076 $result = usePreparedSelectBlade ($query, $qparams);
3077 return $result->fetchAll (PDO::FETCH_ASSOC);
3078 }
3079
3080 function getObjectSearchResults ($what)
3081 {
3082 $ret = array();
3083 global $searchfunc;
3084 foreach ($searchfunc['object'] as $method => $func)
3085 foreach ($func ($what) as $objRecord)
3086 {
3087 $ret[$objRecord['id']]['id'] = $objRecord['id'];
3088 $ret[$objRecord['id']][$method] = $objRecord[$method];
3089 }
3090 foreach (getStickerSearchResults ('RackObject', $what) as $objRecord)
3091 {
3092 $ret[$objRecord['id']]['id'] = $objRecord['id'];
3093 $ret[$objRecord['id']]['by_sticker'] = $objRecord['by_sticker'];
3094 }
3095 return $ret;
3096 }
3097
3098 function getObjectAttrsSearchResults ($what)
3099 {
3100 $ret = array();
3101 foreach (array ('name', 'label', 'asset_no', 'comment') as $column)
3102 {
3103 $tmp = getSearchResultByField
3104 (
3105 'RackObject',
3106 array ('id'),
3107 $column,
3108 $what,
3109 $column
3110 );
3111 foreach ($tmp as $row)
3112 {
3113 $ret[$row['id']]['id'] = $row['id'];
3114 $ret[$row['id']]['by_attr'][] = $column;
3115 }
3116 }
3117 return $ret;
3118 }
3119
3120 // Search stickers and return a list of pairs "object_id-attribute_id"
3121 // that matched. A partilar object_id could be returned more than once, if it has
3122 // multiple matching stickers. Search is only performed on "string" or "dict" attributes.
3123 function getStickerSearchResults ($tablename, $what)
3124 {
3125 $attr_types = array();
3126 $result = usePreparedSelectBlade
3127 (
3128 'SELECT AV.object_id, AV.attr_id FROM AttributeValue AV ' .
3129 "INNER JOIN ${tablename} O ON AV.object_id = O.id " .
3130 'INNER JOIN Attribute A ON AV.attr_id = A.id ' .
3131 'LEFT JOIN AttributeMap AM ON A.type = "dict" AND AV.object_tid = AM.objtype_id AND AV.attr_id = AM.attr_id ' .
3132 'LEFT JOIN Dictionary D ON AM.chapter_id = D.chapter_id AND AV.uint_value = D.dict_key ' .
3133 'WHERE string_value LIKE ? ' .
3134 'OR (A.type = "dict" AND dict_value LIKE ?) ORDER BY object_id',
3135 array ("%${what}%", "%${what}%")
3136 );
3137 $ret = array ();
3138 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3139 {
3140 if (! array_key_exists ($row['attr_id'], $attr_types))
3141 $attr_types[$row['attr_id']] = getAttrType ($row['attr_id']);
3142 if (in_array ($attr_types[$row['attr_id']], array ('string', 'dict')))
3143 {
3144 $ret[$row['object_id']]['id'] = $row['object_id'];
3145 $ret[$row['object_id']]['by_sticker'][] = $row['attr_id'];
3146 }
3147 }
3148 return $ret;
3149 }
3150
3151 // search in port "reservation comment", "label" and "L2 address" columns
3152 function getPortSearchResults ($what)
3153 {
3154 $ret = array();
3155 $ports = getSearchResultByField
3156 (
3157 'Port',
3158 array ('object_id', 'id', 'reservation_comment'),
3159 'reservation_comment',
3160 $what,
3161 'object_id',
3162 0
3163 );
3164 foreach ($ports as $port)
3165 {
3166 $ret[$port['object_id']]['id'] = $port['object_id'];
3167 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
3168 }
3169 $ports = getSearchResultByField
3170 (
3171 'Port',
3172 array ('object_id', 'id', 'label'),
3173 'label',
3174 $what,
3175 'object_id',
3176 0
3177 );
3178 foreach ($ports as $port)
3179 {
3180 $ret[$port['object_id']]['id'] = $port['object_id'];
3181 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
3182 }
3183 try
3184 {
3185 $db_l2address = l2addressForDatabase ($what);
3186 }
3187 catch (InvalidArgException $e)
3188 {
3189 return $ret;
3190 }
3191 $ports = getSearchResultByField
3192 (
3193 'Port',
3194 array ('object_id', 'id', 'l2address'),
3195 'l2address',
3196 $db_l2address,
3197 'object_id',
3198 2
3199 );
3200 foreach ($ports as $port)
3201 {
3202 $ret[$port['object_id']]['id'] = $port['object_id'];
3203 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
3204 }
3205 return $ret;
3206 }
3207
3208 // search in IPv4 allocations
3209 function getObjectIfacesSearchResults ($what)
3210 {
3211 $ret = array();
3212 $ifaces4 = getSearchResultByField
3213 (
3214 'IPv4Allocation',
3215 array ('object_id', 'name'),
3216 'name',
3217 $what,
3218 'object_id'
3219 );
3220 $ifaces6 = getSearchResultByField
3221 (
3222 'IPv6Allocation',
3223 array ('object_id', 'name'),
3224 'name',
3225 $what,
3226 'object_id'
3227 );
3228 foreach (array_merge ($ifaces4, $ifaces6) as $row)
3229 {
3230 $ret[$row['object_id']]['id'] = $row['object_id'];
3231 $ret[$row['object_id']]['by_iface'][] = $row['name'];
3232 }
3233 return $ret;
3234 }
3235
3236 function getObjectNATSearchResults ($what)
3237 {
3238 $ret = array();
3239 $ifaces = getSearchResultByField
3240 (
3241 'IPv4NAT',
3242 array ('object_id', 'description'),
3243 'description',
3244 $what,
3245 'object_id'
3246 );
3247 foreach ($ifaces as $row)
3248 {
3249 $ret[$row['object_id']]['id'] = $row['object_id'];
3250 $ret[$row['object_id']]['by_nat'][] = $row['description'];
3251 }
3252 return $ret;
3253 }
3254
3255 function searchCableIDs ($what)
3256 {
3257 $ret = array();
3258 $result = usePreparedSelectBlade
3259 (
3260 'SELECT object_id, cable ' .
3261 'FROM Link INNER JOIN Port ON porta = Port.id OR portb = Port.id ' .
3262 'WHERE cable LIKE ? ORDER BY object_id',
3263 array ("%${what}%")
3264 );
3265 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3266 {
3267 $ret[$row['object_id']]['id'] = $row['object_id'];
3268 $ret[$row['object_id']]['by_cableid'][] = $row['cable'];
3269 }
3270 return $ret;
3271 }
3272
3273 // This function returns either port ID or NULL for specified arguments.
3274 function getPortIDs ($object_id, $port_name)
3275 {
3276 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
3277 return reduceSubarraysToColumn ($result->fetchAll (PDO::FETCH_ASSOC), 'id');
3278 }
3279
3280 // Search in "FQDN" attribute only, and return object ID, when there is exactly
3281 // one result found (and NULL in any other case).
3282 function searchByMgmtHostname ($string)
3283 {
3284 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
3285 $rows = $result->fetchAll (PDO::FETCH_NUM);
3286 if (count ($rows) == 1)
3287 return $rows[0][0];
3288 unset ($result);
3289
3290 // second attempt: search for FQDN part, separated by dot.
3291 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value LIKE ? LIMIT 2', array ("$string.%"));
3292 $rows = $result->fetchAll (PDO::FETCH_NUM);
3293 return count ($rows) == 1 ? $rows[0][0] : NULL;
3294 }
3295
3296 // returns an array of object ids
3297 function searchByAttrValue ($attr_id, $value)
3298 {
3299 $type = getAttrType ($attr_id);
3300 if (! isset ($type))
3301 throw new InvalidArgException ('attr_id', $attr_id, "No such attribute");
3302
3303 switch ($type)
3304 {
3305 case 'string':
3306 $field = 'string_value';
3307 break;
3308 case 'float':
3309 $field = 'float_value';
3310 break;
3311 case 'uint':
3312 case 'dict':
3313 case 'date':
3314 $field = 'uint_value';
3315 break;
3316 default:
3317 throw new InvalidArgException ('type', $type);
3318 }
3319
3320 $result = usePreparedSelectBlade ("
3321 SELECT object_id FROM AttributeValue
3322 WHERE
3323 attr_id = ?
3324 AND $field = ?
3325 ", array ($attr_id, $value)
3326 );
3327 return $result->fetchAll (PDO::FETCH_COLUMN, 0);
3328 }
3329
3330
3331 // returns user_id
3332 // throws an exception if error occured
3333 function commitCreateUserAccount ($username, $realname, $password)
3334 {
3335 usePreparedInsertBlade
3336 (
3337 'UserAccount',
3338 array
3339 (
3340 'user_name' => $username,
3341 'user_realname' => $realname == '' ? NULL : $realname,
3342 'user_password_hash' => $password,
3343 )
3344 );
3345 $user_id = lastInsertID();
3346 lastCreated ('user', $user_id);
3347 return $user_id;
3348 }
3349
3350 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
3351 {
3352 usePreparedUpdateBlade
3353 (
3354 'UserAccount',
3355 array
3356 (
3357 'user_name' => $new_username,
3358 'user_realname' => $new_realname == '' ? NULL : $new_realname,
3359 'user_password_hash' => $new_password,
3360 ),
3361 array ('user_id' => $id)
3362 );
3363 }
3364
3365 // This function returns an array of all port type pairs from PortCompat table.
3366 function getPortOIFCompat ($ignore_cache = FALSE)
3367 {
3368 static $cache = NULL;
3369 if (! $ignore_cache && isset ($cache))
3370 return $cache;
3371
3372 $query =
3373 "SELECT type1, type2, POI1.oif_name AS type1name, POI2.oif_name AS type2name FROM " .
3374 "PortCompat AS pc INNER JOIN PortOuterInterface AS POI1 ON pc.type1 = POI1.id " .
3375 "INNER JOIN PortOuterInterface AS POI2 ON pc.type2 = POI2.id " .
3376 'ORDER BY type1name, type2name';
3377 $result = usePreparedSelectBlade ($query);
3378 $cache = $result->fetchAll (PDO::FETCH_ASSOC);
3379 return $cache;
3380 }
3381
3382 function addPortOIFCompat ($type1, $type2)
3383 {
3384 return usePreparedExecuteBlade ("INSERT IGNORE INTO PortCompat (type1, type2) VALUES (?, ?),(?, ?)", array ($type1, $type2, $type2, $type1));
3385 }
3386
3387 function deletePortOIFCompat ($type1, $type2)
3388 {
3389 return usePreparedExecuteBlade ("DELETE FROM PortCompat WHERE (type1 = ? AND type2 = ?) OR (type1 = ? AND type2 = ?)", array ($type1, $type2, $type2, $type1));
3390 }
3391
3392 // Returns an array of all object type pairs from the ObjectParentCompat table.
3393 function getObjectParentCompat ()
3394 {
3395 $result = usePreparedSelectBlade
3396 (
3397 'SELECT parent_objtype_id, child_objtype_id, d1.dict_value AS parent_name, d2.dict_value AS child_name, ' .