r4138 commitResetObject(): use appropriate function for DELETE
[racktables] / inc / database.php
1 <?php
2 /*
3 *
4 * This file is a library of database access functions for RackTables.
5 *
6 */
7
8 $SQLSchema = array
9 (
10 'object' => array
11 (
12 'table' => 'RackObject',
13 'columns' => array
14 (
15 'id' => 'id',
16 'name' => 'name',
17 'label' => 'label',
18 'barcode' => 'barcode',
19 'asset_no' => 'asset_no',
20 'objtype_id' => 'objtype_id',
21 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
22 'Rack_name' => '(select name from Rack where id = rack_id)',
23 'row_id' => '(select row_id from Rack where id = rack_id)',
24 'Row_name' => '(select name from RackRow where id = row_id)',
25 'has_problems' => 'has_problems',
26 'comment' => 'comment',
27 'nports' => '(SELECT COUNT(*) FROM Port WHERE object_id = RackObject.id)',
28 'runs8021Q' => '(SELECT 1 FROM VLANSwitch WHERE object_id = id LIMIT 1)',
29 ),
30 'keycolumn' => 'id',
31 'ordcolumns' => array ('RackObject.name'),
32 ),
33 'user' => array
34 (
35 'table' => 'UserAccount',
36 'columns' => array
37 (
38 'user_id' => 'user_id',
39 'user_name' => 'user_name',
40 'user_password_hash' => 'user_password_hash',
41 'user_realname' => 'user_realname',
42 ),
43 'keycolumn' => 'user_id',
44 'ordcolumns' => array ('UserAccount.user_name'),
45 ),
46 'ipv4net' => array
47 (
48 'table' => 'IPv4Network',
49 'columns' => array
50 (
51 'id' => 'id',
52 'ip' => 'INET_NTOA(IPv4Network.ip)',
53 'mask' => 'mask',
54 'name' => 'name',
55 'comment' => 'comment',
56 'parent_id' => '(SELECT id FROM IPv4Network AS subt WHERE IPv4Network.ip & (4294967295 >> (32 - subt.mask)) << (32 - subt.mask) = subt.ip and subt.mask < IPv4Network.mask ORDER BY subt.mask DESC limit 1)',
57 'vlanc' => '(SELECT COUNT(*) FROM VLANIPv4 WHERE ipv4net_id = id)',
58 ),
59 'keycolumn' => 'id',
60 'ordcolumns' => array ('IPv4Network.ip', 'IPv4Network.mask'),
61 ),
62 'ipv6net' => array
63 (
64 'table' => 'IPv6Network',
65 'columns' => array
66 (
67 'id' => 'id',
68 'ip_bin' => 'ip',
69 'mask' => 'mask',
70 'name' => 'name',
71 'comment' => 'comment',
72 'parent_id' => '(SELECT id FROM IPv6Network AS subt WHERE IPv6Network.ip >= subt.ip AND IPv6Network.last_ip <= subt.last_ip AND IPv6Network.mask > subt.mask ORDER BY subt.mask DESC limit 1)',
73 'vlanc' => '(SELECT COUNT(*) FROM VLANIPv6 WHERE ipv6net_id = id)',
74 ),
75 'keycolumn' => 'id',
76 'ordcolumns' => array ('IPv6Network.ip', 'IPv6Network.mask'),
77 ),
78 'file' => array
79 (
80 'table' => 'File',
81 'columns' => array
82 (
83 'id' => 'id',
84 'name' => 'name',
85 'type' => 'type',
86 'size' => 'size',
87 'ctime' => 'ctime',
88 'mtime' => 'mtime',
89 'atime' => 'atime',
90 'comment' => 'comment',
91 ),
92 'keycolumn' => 'id',
93 'ordcolumns' => array ('File.name'),
94 ),
95 'ipv4vs' => array
96 (
97 'table' => 'IPv4VS',
98 'columns' => array
99 (
100 'id' => 'id',
101 'vip' => 'INET_NTOA(vip)',
102 'vport' => 'vport',
103 'proto' => 'proto',
104 'name' => 'name',
105 'vsconfig' => 'vsconfig',
106 'rsconfig' => 'rsconfig',
107 'poolcount' => '(select count(vs_id) from IPv4LB where vs_id = id)',
108 'dname' => 'CONCAT_WS("/", CONCAT_WS(":", INET_NTOA(vip), vport), proto)',
109 ),
110 'keycolumn' => 'id',
111 'ordcolumns' => array ('IPv4VS.vip', 'IPv4VS.proto', 'IPv4VS.vport'),
112 ),
113 'ipv4rspool' => array
114 (
115 'table' => 'IPv4RSPool',
116 'columns' => array
117 (
118 'id' => 'id',
119 'name' => 'name',
120 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
121 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
122 'vsconfig' => 'vsconfig',
123 'rsconfig' => 'rsconfig',
124 ),
125 'keycolumn' => 'id',
126 'ordcolumns' => array ('IPv4RSPool.name', 'IPv4RSPool.id'),
127 ),
128 'rack' => array
129 (
130 'table' => 'Rack',
131 'columns' => array
132 (
133 'id' => 'id',
134 'name' => 'name',
135 'height' => 'height',
136 'comment' => 'comment',
137 'row_id' => 'row_id',
138 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
139 ),
140 'keycolumn' => 'id',
141 'ordcolumns' => array ('row_name', 'Rack.name'),
142 'pidcolumn' => 'row_id',
143 ),
144 );
145
146 $searchfunc = array
147 (
148 'object' => array
149 (
150 'by_sticker' => 'getStickerSearchResults',
151 'by_port' => 'getPortSearchResults',
152 'by_attr' => 'getObjectAttrsSearchResults',
153 'by_iface' => 'getObjectIfacesSearchResults',
154 'by_nat' => 'getObjectNATSearchResults',
155 ),
156 );
157
158 $tablemap_8021q = array
159 (
160 'desired' => array
161 (
162 'pvm' => 'PortVLANMode',
163 'pav' => 'PortAllowedVLAN',
164 'pnv' => 'PortNativeVLAN',
165 ),
166 'cached' => array
167 (
168 'pvm' => 'CachedPVM',
169 'pav' => 'CachedPAV',
170 'pnv' => 'CachedPNV',
171 ),
172 );
173
174 // VST roles
175 $port_role_options = array
176 (
177 'none' => 'none',
178 'access' => 'user: access only',
179 'trunk' => 'user: trunk only',
180 'anymode' => 'user: any mode',
181 'uplink' => 'system: uplink trunk',
182 'downlink' => 'system: downlink trunk',
183 );
184
185 $object_attribute_cache = array();
186
187 function escapeString ($value, $do_db_escape = FALSE)
188 {
189 $ret = htmlspecialchars ($value, ENT_QUOTES, 'UTF-8');
190 if ($do_db_escape)
191 {
192 global $dbxlink;
193 $ret = substr ($dbxlink->quote ($ret), 1, -1);
194 }
195 return $ret;
196 }
197
198 // Return detailed information about one rack row.
199 function getRackRowInfo ($rackrow_id)
200 {
201 $query =
202 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
203 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
204 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
205 "where RackRow.id = ? " .
206 "group by RackRow.id";
207 $result = usePreparedSelectBlade ($query, array ($rackrow_id));
208 if ($row = $result->fetch (PDO::FETCH_ASSOC))
209 return $row;
210 else
211 throw new EntityNotFoundException ('rackrow', $rackrow_id);
212 }
213
214 function getRackRows ()
215 {
216 $result = usePreparedSelectBlade ('SELECT id, name FROM RackRow ORDER BY name');
217 $rows = array();
218 while ($row = $result->fetch (PDO::FETCH_ASSOC))
219 $rows[$row['id']] = $row['name'];
220 return $rows;
221 }
222
223 // Return a simple object list w/o related information, so that the returned value
224 // can be directly used by printSelect(). An optional argument is the name of config
225 // option with constraint in RackCode.
226 function getNarrowObjectList ($varname = '')
227 {
228 $wideList = listCells ('object');
229 if (strlen ($varname) and strlen (getConfigVar ($varname)))
230 {
231 global $parseCache;
232 if (!isset ($parseCache[$varname]))
233 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
234 if ($parseCache[$varname]['result'] != 'ACK')
235 return array();
236 $wideList = filterCellList ($wideList, $parseCache[$varname]['load']);
237 }
238 $ret = array();
239 foreach ($wideList as $cell)
240 $ret[$cell['id']] = $cell['dname'];
241 return $ret;
242 }
243
244 // For a given realm return a list of entity records, each with
245 // enough information for judgeCell() to execute.
246 function listCells ($realm, $parent_id = 0)
247 {
248 if (!$parent_id)
249 {
250 global $entityCache;
251 if (isset ($entityCache['complete'][$realm]))
252 return $entityCache['complete'][$realm];
253 }
254 global $SQLSchema;
255 if (!isset ($SQLSchema[$realm]))
256 throw new InvalidArgException ('realm', $realm);
257 $SQLinfo = $SQLSchema[$realm];
258 $qparams = array ();
259 $query = 'SELECT ';
260 foreach ($SQLinfo['columns'] as $alias => $expression)
261 // Automatically prepend table name to each single column, but leave all others intact.
262 $query .= ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}") . ', ';
263 $query = trim($query, ', ');
264 $query .= " FROM ${SQLinfo['table']}";
265 if (isset ($SQLinfo['pidcolumn']) and $parent_id)
266 {
267 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ?";
268 $qparams[] = $parent_id;
269 }
270 $query .= " ORDER BY ";
271 foreach ($SQLinfo['ordcolumns'] as $oc)
272 $query .= "${oc}, ";
273 $query = trim($query, ', ');
274 $result = usePreparedSelectBlade ($query, $qparams);
275 $ret = array();
276 // Index returned result by the value of key column.
277 while ($row = $result->fetch (PDO::FETCH_ASSOC))
278 {
279 $entity_id = $row[$SQLinfo['keycolumn']];
280 $ret[$entity_id] = array ('realm' => $realm);
281 $ret[$entity_id]['etags'] = array();
282 foreach (array_keys ($SQLinfo['columns']) as $alias)
283 $ret[$entity_id][$alias] = $row[$alias];
284 }
285 unset($result);
286
287 // select tags and link them to previosly fetched entities
288 $query = 'SELECT entity_id, tag_id FROM TagStorage WHERE entity_realm = ?';
289 $result = usePreparedSelectBlade ($query, array($realm));
290 global $taglist;
291 while ($row = $result->fetch (PDO::FETCH_ASSOC))
292 {
293 if (array_key_exists($row['entity_id'], $ret))
294 $ret[$row['entity_id']]['etags'][] = array
295 (
296 'id' => $row['tag_id'],
297 'tag' => $taglist[$row['tag_id']]['tag'],
298 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
299 );
300 }
301 unset($result);
302 // Add necessary finish to the list before returning it. Maintain caches.
303 if (!$parent_id)
304 unset ($entityCache['partial'][$realm]);
305 if ($realm == 'object') // cache all attributes of all objects to speed up autotags calculation
306 cacheAllObjectsAttributes();
307 foreach (array_keys ($ret) as $entity_id)
308 {
309 $ret[$entity_id]['etags'] = getExplicitTagsOnly ($ret[$entity_id]['etags']);
310 $ret[$entity_id]['itags'] = getImplicitTags ($ret[$entity_id]['etags']);
311 $ret[$entity_id]['atags'] = generateEntityAutoTags ($ret[$entity_id]);
312 switch ($realm)
313 {
314 case 'object':
315 setDisplayedName ($ret[$entity_id]);
316 break;
317 case 'ipv4net':
318 $ret[$entity_id]['ip_bin'] = ip2long ($ret[$entity_id]['ip']);
319 $ret[$entity_id]['mask_bin'] = binMaskFromDec ($ret[$entity_id]['mask']);
320 $ret[$entity_id]['mask_bin_inv'] = binInvMaskFromDec ($ret[$entity_id]['mask']);
321 $ret[$entity_id]['db_first'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] & $ret[$entity_id]['mask_bin']);
322 $ret[$entity_id]['db_last'] = sprintf ('%u', 0x00000000 + $ret[$entity_id]['ip_bin'] | ($ret[$entity_id]['mask_bin_inv']));
323 break;
324 case 'ipv6net':
325 $ret[$entity_id]['ip_bin'] = new IPv6Address ($ret[$entity_id]['ip_bin']);
326 $ret[$entity_id]['ip'] = $ret[$entity_id]['ip_bin']->format();
327 $ret[$entity_id]['db_first'] = $ret[$entity_id]['ip_bin']->get_first_subnet_address($ret[$entity_id]['mask']);
328 $ret[$entity_id]['db_last'] = $ret[$entity_id]['ip_bin']->get_last_subnet_address($ret[$entity_id]['mask']);
329 break;
330 default:
331 break;
332 }
333 if (!$parent_id)
334 $entityCache['complete'][$realm][$entity_id] = $ret[$entity_id];
335 else
336 $entityCache['partial'][$realm][$entity_id] = $ret[$entity_id];
337 }
338 return $ret;
339 }
340
341 // Very much like listCells(), but return only one record requested (or NULL,
342 // if it does not exist).
343 function spotEntity ($realm, $id)
344 {
345 global $entityCache;
346 if (isset ($entityCache['complete'][$realm]))
347 // Emphasize the absence of record, if listCells() has already been called.
348 if (isset ($entityCache['complete'][$realm][$id]))
349 return $entityCache['complete'][$realm][$id];
350 else
351 throw new EntityNotFoundException ($realm, $id);
352 elseif (isset ($entityCache['partial'][$realm][$id]))
353 return $entityCache['partial'][$realm][$id];
354 global $SQLSchema;
355 if (!isset ($SQLSchema[$realm]))
356 throw new InvalidArgException ('realm', $realm);
357 $SQLinfo = $SQLSchema[$realm];
358 $query = 'SELECT tag_id';
359 foreach ($SQLinfo['columns'] as $alias => $expression)
360 // Automatically prepend table name to each single column, but leave all others intact.
361 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
362 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
363 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ?";
364 $query .= " ORDER BY tag_id";
365 $result = usePreparedSelectBlade ($query, array ($realm, $id));
366 $ret = array();
367 global $taglist;
368 while ($row = $result->fetch (PDO::FETCH_ASSOC))
369 if (!isset ($ret['realm']))
370 {
371 $ret = array ('realm' => $realm);
372 foreach (array_keys ($SQLinfo['columns']) as $alias)
373 $ret[$alias] = $row[$alias];
374 $ret['etags'] = array();
375 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
376 $ret['etags'][] = array
377 (
378 'id' => $row['tag_id'],
379 'tag' => $taglist[$row['tag_id']]['tag'],
380 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
381 );
382 }
383 elseif (isset ($taglist[$row['tag_id']]))
384 $ret['etags'][] = array
385 (
386 'id' => $row['tag_id'],
387 'tag' => $taglist[$row['tag_id']]['tag'],
388 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
389 );
390 unset ($result);
391 if (!isset ($ret['realm'])) // no rows were returned
392 throw new EntityNotFoundException ($realm, $id);
393 $ret['etags'] = getExplicitTagsOnly ($ret['etags']);
394 $ret['itags'] = getImplicitTags ($ret['etags']);
395 $ret['atags'] = generateEntityAutoTags ($ret);
396 switch ($realm)
397 {
398 case 'object':
399 setDisplayedName ($ret);
400 break;
401 case 'ipv4net':
402 $ret['ip_bin'] = ip2long ($ret['ip']);
403 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
404 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
405 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
406 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
407 break;
408 case 'ipv6net':
409 $ret['ip_bin'] = new IPv6Address ($ret['ip_bin']);
410 $ret['ip'] = $ret['ip_bin']->format();
411 $ret['db_first'] = $ret['ip_bin']->get_first_subnet_address($ret['mask']);
412 $ret['db_last'] = $ret['ip_bin']->get_last_subnet_address($ret['mask']);
413 break;
414 default:
415 break;
416 }
417 $entityCache['partial'][$realm][$id] = $ret;
418 return $ret;
419 }
420
421 // This function can be used with array_walk().
422 function amplifyCell (&$record, $dummy = NULL)
423 {
424 switch ($record['realm'])
425 {
426 case 'object':
427 $record['ports'] = getObjectPortsAndLinks ($record['id']);
428 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
429 $record['ipv6'] = getObjectIPv6Allocations ($record['id']);
430 $record['nat4'] = getNATv4ForObject ($record['id']);
431 $record['ipv4rspools'] = getRSPoolsForObject ($record['id']);
432 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
433 break;
434 case 'file':
435 $record['links'] = getFileLinks ($record['id']);
436 break;
437 case 'ipv4rspool':
438 $record['lblist'] = array();
439 $query = "select object_id, vs_id, lb.vsconfig, lb.rsconfig, lb.prio from " .
440 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
441 "where rspool_id = ? order by object_id, vip, vport";
442 $result = usePreparedSelectBlade ($query, array ($record['id']));
443 while ($row = $result->fetch (PDO::FETCH_ASSOC))
444 $record['lblist'][$row['object_id']][$row['vs_id']] = array
445 (
446 'rsconfig' => $row['rsconfig'],
447 'vsconfig' => $row['vsconfig'],
448 'prio' => $row['prio'],
449 );
450 unset ($result);
451 $record['rslist'] = array();
452 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
453 "IPv4RS where rspool_id = ? order by IPv4RS.rsip, rsport";
454 $result = usePreparedSelectBlade ($query, array ($record['id']));
455 while ($row = $result->fetch (PDO::FETCH_ASSOC))
456 $record['rslist'][$row['id']] = array
457 (
458 'inservice' => $row['inservice'],
459 'rsip' => $row['rsip'],
460 'rsport' => $row['rsport'],
461 'rsconfig' => $row['rsconfig'],
462 );
463 unset ($result);
464 break;
465 case 'ipv4vs':
466 // Get the detailed composition of a particular virtual service, namely the list
467 // of all pools, each shown with the list of objects servicing it. VS/RS configs
468 // will be returned as well.
469 $record['rspool'] = array();
470 $query = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
471 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, lb.prio from " .
472 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
473 "where vs_id = ? order by pool.name, object_id";
474 $result = usePreparedSelectBlade ($query, array ($record['id']));
475 while ($row = $result->fetch (PDO::FETCH_ASSOC))
476 {
477 if (!isset ($record['rspool'][$row['id']]))
478 $record['rspool'][$row['id']] = array
479 (
480 'name' => $row['name'],
481 'vsconfig' => $row['vsconfig'],
482 'rsconfig' => $row['rsconfig'],
483 'lblist' => array(),
484 );
485 if ($row['object_id'] == NULL)
486 continue;
487 $record['rspool'][$row['id']]['lblist'][$row['object_id']] = array
488 (
489 'vsconfig' => $row['lb_vsconfig'],
490 'rsconfig' => $row['lb_rsconfig'],
491 'prio' => $row['prio'],
492 );
493 }
494 unset ($result);
495 break;
496 case 'rack':
497 $record['mountedObjects'] = array();
498 // start with default rackspace
499 for ($i = $record['height']; $i > 0; $i--)
500 for ($locidx = 0; $locidx < 3; $locidx++)
501 $record[$i][$locidx]['state'] = 'F';
502 // load difference
503 $query =
504 "select unit_no, atom, state, object_id " .
505 "from RackSpace where rack_id = ? and " .
506 "unit_no between 1 and ? order by unit_no";
507 $result = usePreparedSelectBlade ($query, array ($record['id'], $record['height']));
508 global $loclist;
509 $mounted_objects = array();
510 while ($row = $result->fetch (PDO::FETCH_ASSOC))
511 {
512 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
513 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
514 if ($row['state'] == 'T' and $row['object_id'] != NULL)
515 $mounted_objects[$row['object_id']] = TRUE;
516 }
517 $record['mountedObjects'] = array_keys ($mounted_objects);
518 unset ($result);
519 break;
520 case 'ipv4net':
521 $record['8021q'] = getIPv4Network8021QBindings ($record['id']);
522 break;
523 case 'ipv6net':
524 $record['8021q'] = getIPv6Network8021QBindings ($record['id']);
525 break;
526 default:
527 }
528 }
529
530 function getObjectPortsAndLinks ($object_id)
531 {
532 $query = "SELECT id, name, label, l2address, iif_id, (SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name, " .
533 "type AS oif_id, (SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, reservation_comment " .
534 "FROM Port WHERE object_id = ?";
535 // list and decode all ports of the current object
536 $result = usePreparedSelectBlade ($query, array ($object_id));
537 $ret=array();
538 while ($row = $result->fetch (PDO::FETCH_ASSOC))
539 {
540 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
541 $row['remote_id'] = NULL;
542 $row['remote_name'] = NULL;
543 $row['remote_object_id'] = NULL;
544 $ret[] = $row;
545 }
546 unset ($result);
547 // now find and decode remote ends for all locally terminated connections
548 // FIXME: can't this data be extracted in one pass with sub-queries?
549 foreach (array_keys ($ret) as $tmpkey)
550 {
551 $portid = $ret[$tmpkey]['id'];
552 $remote_id = NULL;
553 $query = "select porta, portb, cable from Link where porta = ? or portb = ?";
554 $result = usePreparedSelectBlade ($query, array ($portid, $portid));
555 $cable = "CableID n/a";
556 if ($row = $result->fetch (PDO::FETCH_ASSOC))
557 {
558 if ($portid != $row['porta'])
559 $remote_id = $row['porta'];
560 elseif ($portid != $row['portb'])
561 $remote_id = $row['portb'];
562 $cable = $row['cable'];
563 }
564 unset ($result);
565 if ($remote_id) // there's a remote end here
566 {
567 $query = "SELECT name, object_id FROM Port WHERE id = ?";
568 $result = usePreparedSelectBlade ($query, array ($remote_id));
569 if ($row = $result->fetch (PDO::FETCH_ASSOC))
570 {
571 $ret[$tmpkey]['remote_name'] = $row['name'];
572 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
573 $ret[$tmpkey]['cableid'] = $cable;
574 }
575 $ret[$tmpkey]['remote_id'] = $remote_id;
576 unset ($result);
577 }
578 }
579 return sortPortList ($ret, TRUE);
580 }
581
582 function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
583 {
584 if ($row_id <= 0 or $height <= 0 or !strlen ($name))
585 return FALSE;
586 $result = usePreparedInsertBlade
587 (
588 'Rack',
589 array
590 (
591 'row_id' => $row_id,
592 'name' => $name,
593 'height' => $height,
594 'comment' => $comment
595 )
596 );
597 $last_insert_id = lastInsertID();
598 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', $last_insert_id);
599 }
600
601 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
602 {
603 // Maintain UNIQUE INDEX for common names and asset tags by
604 // filtering out empty strings (not NULLs).
605 $result1 = usePreparedInsertBlade
606 (
607 'RackObject',
608 array
609 (
610 'name' => !strlen ($new_name) ? NULL : $new_name,
611 'label' => $new_label,
612 'barcode' => !strlen ($new_barcode) ? NULL : $new_barcode,
613 'objtype_id' => $new_type_id,
614 'asset_no' => !strlen ($new_asset_no) ? NULL : $new_asset_no,
615 )
616 );
617 $last_insert_id = lastInsertID();
618 // Do AutoPorts magic
619 executeAutoPorts ($last_insert_id, $new_type_id);
620 // Now tags...
621 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
622
623 recordHistory ('RackObject', $last_insert_id);
624
625 return $last_insert_id;
626 }
627
628 function commitUpdateObject ($object_id, $new_name, $new_label, $new_barcode, $new_has_problems, $new_asset_no, $new_comment)
629 {
630 usePreparedUpdateBlade
631 (
632 'RackObject',
633 array
634 (
635 'name' => !mb_strlen ($new_name) ? NULL : $new_name,
636 'label' => $new_label,
637 'barcode' => !mb_strlen ($new_barcode) ? NULL : $new_barcode,
638 'has_problems' => $new_has_problems,
639 'asset_no' => !mb_strlen ($new_asset_no) ? NULL : $new_asset_no,
640 'comment' => $new_comment,
641 ),
642 array
643 (
644 'id' => $object_id
645 )
646 );
647 return recordHistory ('RackObject', $object_id);
648 }
649
650 // Remove file links related to the entity, but leave the entity and file(s) intact.
651 function releaseFiles ($entity_realm, $entity_id)
652 {
653 usePreparedDeleteBlade ('FileLink', array ('entity_type' => $entity_realm, 'entity_id' => $entity_id));
654 }
655
656 // There are times when you want to delete all traces of an object
657 function commitDeleteObject ($object_id = 0)
658 {
659 // Reset most of stuff
660 commitResetObject ($object_id);
661 // Object itself
662 usePreparedDeleteBlade ('RackObject', array ('id' => $object_id));
663 }
664
665 function commitResetObject ($object_id = 0)
666 {
667 releaseFiles ('object', $object_id);
668 destroyTagsForEntity ('object', $object_id);
669 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
670 usePreparedDeleteBlade ('IPv4Allocation', array ('object_id' => $object_id));
671 usePreparedDeleteBlade ('IPv6Allocation', array ('object_id' => $object_id));
672 usePreparedDeleteBlade ('IPv4NAT', array ('object_id' => $object_id));
673 // Rack space
674 usePreparedExecuteBlade ('DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
675 usePreparedExecuteBlade ('DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
676 usePreparedDeleteBlade ('MountOperation', array ('object_id' => $object_id));
677 usePreparedDeleteBlade ('RackSpace', array ('object_id' => $object_id));
678 // 802.1Q
679 usePreparedDeleteBlade ('PortVLANMode', array ('object_id' => $object_id));
680 usePreparedDeleteBlade ('PortNativeVLAN', array ('object_id' => $object_id));
681 usePreparedDeleteBlade ('PortAllowedVLAN', array ('object_id' => $object_id));
682 usePreparedDeleteBlade ('CachedPVM', array ('object_id' => $object_id));
683 usePreparedDeleteBlade ('VLANSwitch', array ('object_id' => $object_id));
684 // Ports & links
685 usePreparedDeleteBlade ('Port', array ('object_id' => $object_id));
686 // CN
687 usePreparedUpdateBlade ('RackObject', array ('name' => NULL, 'label' => ''), array ('id' => $object_id));
688 // FQDN
689 commitUpdateAttrValue ($object_id, 3, "");
690 // log history
691 recordHistory ('RackObject', $object_id);
692 }
693
694 function commitDeleteRack($rack_id)
695 {
696 releaseFiles ('rack', $rack_id);
697 destroyTagsForEntity ('rack', $rack_id);
698 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
699 usePreparedDeleteBlade ('RackHistory', array ('id' => $rack_id));
700 usePreparedDeleteBlade ('Rack', array ('id' => $rack_id));
701 return TRUE;
702 }
703
704 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
705 {
706 // Can't shrink a rack if rows being deleted contain mounted objects
707 $check_result = usePreparedSelectBlade ('SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = ? AND unit_no > ?', array ($rack_id, $new_height));
708 $check_row = $check_result->fetch (PDO::FETCH_ASSOC);
709 unset ($check_result);
710 if ($check_row['count'] > 0)
711 throw new InvalidArgException ('new_height', $new_height, 'Cannot shrink rack, objects are still mounted there');
712 usePreparedUpdateBlade
713 (
714 'Rack',
715 array
716 (
717 'name' => $new_name,
718 'height' => $new_height,
719 'comment' => $new_comment,
720 'row_id' => $new_row_id,
721 ),
722 array
723 (
724 'id' => $rack_id,
725 )
726 );
727 return recordHistory ('Rack', $rack_id);
728 }
729
730 // This function accepts rack data returned by amplifyCell(), validates and applies changes
731 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
732 // correspond to current rack ID.
733 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
734 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
735 // The function returns the modified rack upon success.
736 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
737 {
738 global $loclist;
739 $rack_id = $rackData['id'];
740 $rack_name = $rackData['name'];
741 $rackchanged = FALSE;
742 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
743 {
744 for ($locidx = 0; $locidx < 3; $locidx++)
745 {
746 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
747 continue;
748 // detect a change
749 $state = $rackData[$unit_no][$locidx]['state'];
750 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
751 $newstate = $checked_state;
752 else
753 $newstate = $unchecked_state;
754 if ($state == $newstate)
755 continue;
756 $rackchanged = TRUE;
757 // and validate
758 $atom = $loclist[$locidx];
759 // The only changes allowed are those introduced by checkbox grid.
760 if
761 (
762 !($state == $checked_state && $newstate == $unchecked_state) &&
763 !($state == $unchecked_state && $newstate == $checked_state)
764 )
765 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
766 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
767 // anyway and then looking for probable need of INSERT.
768 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom));
769 if ($newstate != 'F')
770 usePreparedInsertBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom, 'state' => $newstate));
771 if ($newstate == 'T' and $object_id != 0)
772 {
773 // At this point we already have a record in RackSpace.
774 $r = usePreparedUpdateBlade
775 (
776 'RackSpace',
777 array ('object_id' => $object_id),
778 array
779 (
780 'rack_id' => $rack_id,
781 'unit_no' => $unit_no,
782 'atom' => $atom,
783 )
784 );
785 if ($r === FALSE)
786 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
787 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
788 }
789 }
790 }
791 if ($rackchanged)
792 {
793 usePreparedUpdateBlade ('Rack', array ('thumb_data' => NULL), array ('id' => $rack_id));
794 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
795 }
796 else
797 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
798 }
799
800 // This function builds a list of rack-unit-atom records, which are assigned to
801 // the requested object.
802 function getMoleculeForObject ($object_id)
803 {
804 $result = usePreparedSelectBlade
805 (
806 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
807 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
808 array ($object_id)
809 );
810 return $result->fetchAll (PDO::FETCH_ASSOC);
811 }
812
813 // This function builds a list of rack-unit-atom records for requested molecule.
814 function getMolecule ($mid = 0)
815 {
816 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
817 return $result->fetchAll (PDO::FETCH_ASSOC);
818 }
819
820 // returns exactly what is's named after
821 function lastInsertID ()
822 {
823 $result = usePreparedSelectBlade ('select last_insert_id()');
824 $row = $result->fetch (PDO::FETCH_NUM);
825 return $row[0];
826 }
827
828 // This function creates a new record in Molecule and number of linked
829 // R-U-A records in Atom.
830 function createMolecule ($molData)
831 {
832 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
833 $molecule_id = lastInsertID();
834 foreach ($molData as $rua)
835 usePreparedInsertBlade
836 (
837 'Atom',
838 array
839 (
840 'molecule_id' => $molecule_id,
841 'rack_id' => $rua['rack_id'],
842 'unit_no' => $rua['unit_no'],
843 'atom' => $rua['atom'],
844 )
845 );
846 return $molecule_id;
847 }
848
849 // History logger. This function assumes certain table naming convention and
850 // column design:
851 // 1. History table name equals to dictionary table name plus 'History'.
852 // 2. History table must have the same row set (w/o keys) plus one row named
853 // 'ctime' of type 'timestamp'.
854 function recordHistory ($tableName, $orig_id)
855 {
856 global $remote_username;
857 return FALSE !== usePreparedExecuteBlade
858 (
859 "INSERT INTO ${tableName}History SELECT *, CURRENT_TIMESTAMP(), ? " .
860 "FROM ${tableName} WHERE id=?",
861 array ($remote_username, $orig_id)
862 );
863 }
864
865 function getRackspaceHistory ()
866 {
867 $result = usePreparedSelectBlade
868 (
869 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
870 "MountOperation ORDER BY ctime DESC"
871 );
872 return $result->fetchAll (PDO::FETCH_ASSOC);
873 }
874
875 // This function is used in renderRackspaceHistory()
876 function getOperationMolecules ($op_id = 0)
877 {
878 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
879 // We expect one row.
880 $row = $result->fetch (PDO::FETCH_ASSOC);
881 return array ($row['old_molecule_id'], $row['new_molecule_id']);
882 }
883
884 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
885 {
886 $result = usePreparedSelectBlade ('SELECT DISTINCT rack_id FROM RackSpace WHERE object_id = ? ORDER BY rack_id', array ($object_id));
887 $rows = $result->fetchAll (PDO::FETCH_NUM);
888 unset ($result);
889 $ret = array();
890 foreach ($rows as $row)
891 {
892 if (!$fetch_rackdata)
893 {
894 $ret[$row[0]] = $row[0];
895 continue;
896 }
897 $rackData = spotEntity ('rack', $row[0]);
898 amplifyCell ($rackData);
899 $ret[$row[0]] = $rackData;
900 }
901 return $ret;
902 }
903
904 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
905 {
906 $db_l2address = l2addressForDatabase ($port_l2address);
907 global $dbxlink;
908 $dbxlink->exec ('LOCK TABLES Port WRITE');
909 if (alreadyUsedL2Address ($db_l2address, $object_id))
910 {
911 $dbxlink->exec ('UNLOCK TABLES');
912 return "address ${db_l2address} belongs to another object";
913 }
914 $matches = array();
915 switch (1)
916 {
917 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
918 $iif_id = $matches[1];
919 $oif_id = $matches[2];
920 break;
921 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
922 $iif_id = 1;
923 $oif_id = $matches[1];
924 break;
925 default:
926 $dbxlink->exec ('UNLOCK TABLES');
927 return "invalid port type id '${port_type_id}'";
928 }
929 $result = usePreparedInsertBlade
930 (
931 'Port',
932 array
933 (
934 'name' => $port_name,
935 'object_id' => $object_id,
936 'label' => $port_label,
937 'iif_id' => $iif_id,
938 'type' => $oif_id,
939 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
940 )
941 );
942 $dbxlink->exec ('UNLOCK TABLES');
943 if ($result)
944 return '';
945 else
946 return 'SQL query failed';
947 }
948
949 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
950 // string value. In case it is omitted, we just assign it its current value.
951 // It would be nice to simplify this semantics later.
952 function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment)
953 {
954 $db_l2address = l2addressForDatabase ($port_l2address);
955 global $dbxlink;
956 $dbxlink->exec ('LOCK TABLES Port WRITE');
957 if (alreadyUsedL2Address ($db_l2address, $object_id))
958 {
959 $dbxlink->exec ('UNLOCK TABLES');
960 // FIXME: it is more correct to throw InvalidArgException here
961 // and convert it to InvalidRequestArgException at upper level,
962 // when there is a mean to do that.
963 throw new InvalidRequestArgException ('port_l2address', $db_l2address, 'address belongs to another object');
964 }
965 usePreparedUpdateBlade
966 (
967 'Port',
968 array
969 (
970 'name' => $port_name,
971 'type' => $port_type_id,
972 'label' => $port_label,
973 'reservation_comment' => mb_strlen ($port_reservation_comment) ? $port_reservation_comment : NULL,
974 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
975 ),
976 array
977 (
978 'id' => $port_id,
979 'object_id' => $object_id
980 )
981 );
982 $dbxlink->exec ('UNLOCK TABLES');
983 }
984
985 function getAllIPv4Allocations ()
986 {
987 $result = usePreparedSelectBlade
988 (
989 "select object_id as object_id, ".
990 "RackObject.name as object_name, ".
991 "IPv4Allocation.name as name, ".
992 "INET_NTOA(ip) as ip ".
993 "from IPv4Allocation join RackObject on id=object_id "
994 );
995 $ret = array();
996 while ($row = $result->fetch (PDO::FETCH_ASSOC))
997 $ret[] = $row;
998 return $ret;
999 }
1000
1001 function linkPorts ($porta, $portb, $cable = NULL)
1002 {
1003 if ($porta == $portb)
1004 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
1005
1006 global $dbxlink;
1007 $dbxlink->exec ('LOCK TABLES Link WRITE');
1008 $result = usePreparedSelectBlade
1009 (
1010 'SELECT COUNT(*) FROM Link WHERE porta IN (?,?) OR portb IN (?,?)',
1011 array ($porta, $portb, $porta, $portb)
1012 );
1013 if ($result->fetchColumn () != 0)
1014 {
1015 $dbxlink->exec ('UNLOCK TABLES');
1016 return "Port ${porta} or ${portb} is already linked";
1017 }
1018 if ($porta > $portb)
1019 {
1020 $tmp = $porta;
1021 $porta = $portb;
1022 $portb = $tmp;
1023 }
1024 $ret = FALSE !== usePreparedInsertBlade ('Link', array ('porta' => $porta, 'portb' => $portb, 'cable' => $cable));
1025 $dbxlink->exec ('UNLOCK TABLES');
1026 $ret = $ret and FALSE !== usePreparedExecuteBlade
1027 (
1028 'UPDATE Port SET reservation_comment=NULL WHERE id IN(?, ?)',
1029 array ($porta, $portb)
1030 );
1031 return $ret ? '' : 'query failed';
1032 }
1033
1034 // Return all IPv4 addresses allocated to the objects. Attach detailed
1035 // info about address to each alocation records. Index result by dotted-quad
1036 // address.
1037 function getObjectIPv4Allocations ($object_id = 0)
1038 {
1039 $ret = array();
1040 $result = usePreparedSelectBlade
1041 (
1042 'SELECT name AS osif, type, inet_ntoa(ip) AS dottedquad FROM IPv4Allocation ' .
1043 'WHERE object_id = ? ORDER BY ip',
1044 array ($object_id)
1045 );
1046 // don't spawn a sub-query with unfetched buffer, it may fail
1047 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1048 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1049 unset ($result);
1050 foreach (array_keys ($ret) as $dottedquad)
1051 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
1052 return $ret;
1053 }
1054
1055 // Return all IPv6 addresses allocated to the objects. Attach detailed
1056 // info about address to each alocation records. Index result by binary string of IPv6
1057 function getObjectIPv6Allocations ($object_id = 0)
1058 {
1059 $ret = array();
1060 $result = usePreparedSelectBlade
1061 (
1062 'SELECT name AS osif, type, ip AS ip FROM IPv6Allocation ' .
1063 'WHERE object_id = ? ORDER BY ip',
1064 array ($object_id)
1065 );
1066 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1067 $ret[$row['ip']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1068 unset ($result);
1069 foreach (array_keys ($ret) as $ip_bin)
1070 $ret[$ip_bin]['addrinfo'] = getIPv6Address (new IPv6Address ($ip_bin));
1071 return $ret;
1072 }
1073
1074 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
1075 function constructIPv4Address ($dottedquad = NULL)
1076 {
1077 $ret = array
1078 (
1079 'version' => 4,
1080 'name' => '',
1081 'reserved' => 'no',
1082 'outpf' => array(),
1083 'inpf' => array(),
1084 'rslist' => array(),
1085 'allocs' => array(),
1086 'lblist' => array()
1087 );
1088 if ($dottedquad != NULL)
1089 $ret['ip'] = $dottedquad;
1090 return $ret;
1091 }
1092
1093 // Return minimal IPv6 address, optionally with "ip" key set, if requested.
1094 function constructIPv6Address ($bin_ip = NULL)
1095 {
1096 $ret = array
1097 (
1098 'version' => 6,
1099 'name' => '',
1100 'reserved' => 'no',
1101 'allocs' => array(),
1102 );
1103 if ($bin_ip != NULL)
1104 $ret['ip'] = $bin_ip->format();
1105 return $ret;
1106 }
1107
1108 // Check the range requested for meaningful IPv4 records, build them
1109 // into a list and return. Return an empty list if nothing matched.
1110 // Both arguments are expected in signed int32 form. The resulting list
1111 // is keyed by uint32 form of each IP address, items aren't sorted.
1112 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
1113 function scanIPv4Space ($pairlist)
1114 {
1115 $ret = array();
1116 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
1117 return $ret;
1118 // FIXME: this is a copy-and-paste prototype
1119 $or = '';
1120 $whereexpr1 = '(';
1121 $whereexpr2 = '(';
1122 $whereexpr3 = '(';
1123 $whereexpr4 = '(';
1124 $whereexpr5a = '(';
1125 $whereexpr5b = '(';
1126 $qparams = array();
1127 foreach ($pairlist as $tmp)
1128 {
1129 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
1130 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
1131 $whereexpr1 .= $or . "ip between ? and ?";
1132 $whereexpr2 .= $or . "ip between ? and ?";
1133 $whereexpr3 .= $or . "vip between ? and ?";
1134 $whereexpr4 .= $or . "rsip between ? and ?";
1135 $whereexpr5a .= $or . "remoteip between ? and ?";
1136 $whereexpr5b .= $or . "localip between ? and ?";
1137 $or = ' or ';
1138 $qparams[] = $db_first;
1139 $qparams[] = $db_last;
1140 }
1141 $whereexpr1 .= ')';
1142 $whereexpr2 .= ')';
1143 $whereexpr3 .= ')';
1144 $whereexpr4 .= ')';
1145 $whereexpr5a .= ')';
1146 $whereexpr5b .= ')';
1147
1148 // 1. collect labels and reservations
1149 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
1150 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1151 $result = usePreparedSelectBlade ($query, $qparams);
1152 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1153 {
1154 $ip_bin = ip2long ($row['ip']);
1155 if (!isset ($ret[$ip_bin]))
1156 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1157 $ret[$ip_bin]['name'] = $row['name'];
1158 $ret[$ip_bin]['reserved'] = $row['reserved'];
1159 }
1160 unset ($result);
1161
1162 // 2. check for allocations
1163 $query =
1164 "select INET_NTOA(ip) as ip, object_id, name, type " .
1165 "from IPv4Allocation where ${whereexpr2} order by type";
1166 $result = usePreparedSelectBlade ($query, $qparams);
1167 // release DBX early to avoid issues with nested spotEntity() calls
1168 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1169 unset ($result);
1170 foreach ($allRows as $row)
1171 {
1172 $ip_bin = ip2long ($row['ip']);
1173 if (!isset ($ret[$ip_bin]))
1174 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1175 $oinfo = spotEntity ('object', $row['object_id']);
1176 $ret[$ip_bin]['allocs'][] = array
1177 (
1178 'type' => $row['type'],
1179 'name' => $row['name'],
1180 'object_id' => $row['object_id'],
1181 'object_name' => $oinfo['dname'],
1182 );
1183 }
1184
1185 // 3. look for virtual services and related LB
1186 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, object_id " .
1187 "from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1188 "where ${whereexpr3} order by vport, proto, object_id";
1189 $result = usePreparedSelectBlade ($query, $qparams);
1190 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1191 unset ($result);
1192 foreach ($allRows as $row)
1193 {
1194 $ip_bin = ip2long ($row['ip']);
1195 if (!isset ($ret[$ip_bin]))
1196 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1197 $oinfo = spotEntity ('object', $row['object_id']);
1198 $ret[$ip_bin]['lblist'][] = array
1199 (
1200 'vport' => $row['vport'],
1201 'proto' => $row['proto'],
1202 'vs_id' => $row['vs_id'],
1203 'name' => $row['name'],
1204 'vip' => $row['ip'],
1205 'object_id' => $row['object_id'],
1206 'object_name' => $oinfo['dname'],
1207 );
1208 }
1209
1210 // 4. don't forget about real servers along with pools
1211 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1212 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
1213 "where ${whereexpr4} " .
1214 "order by ip, rsport, rspool_id";
1215 $result = usePreparedSelectBlade ($query, $qparams);
1216 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1217 {
1218 $ip_bin = ip2long ($row['ip']);
1219 if (!isset ($ret[$ip_bin]))
1220 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1221 $tmp = array();
1222 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1223 $tmp[$cname] = $row[$cname];
1224 $ret[$ip_bin]['rslist'][] = $tmp;
1225 }
1226 unset ($result);
1227
1228 // 5. add NAT rules, part 1
1229 $query =
1230 "select " .
1231 "proto, " .
1232 "INET_NTOA(localip) as localip, " .
1233 "localport, " .
1234 "INET_NTOA(remoteip) as remoteip, " .
1235 "remoteport, " .
1236 "description " .
1237 "from IPv4NAT " .
1238 "where ${whereexpr5a} " .
1239 "order by localip, localport, remoteip, remoteport, proto";
1240 $result = usePreparedSelectBlade ($query, $qparams);
1241 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1242 {
1243 $remoteip_bin = ip2long ($row['remoteip']);
1244 if (!isset ($ret[$remoteip_bin]))
1245 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1246 $ret[$remoteip_bin]['inpf'][] = $row;
1247 }
1248 unset ($result);
1249 // 5. add NAT rules, part 2
1250 $query =
1251 "select " .
1252 "proto, " .
1253 "INET_NTOA(localip) as localip, " .
1254 "localport, " .
1255 "INET_NTOA(remoteip) as remoteip, " .
1256 "remoteport, " .
1257 "description " .
1258 "from IPv4NAT " .
1259 "where ${whereexpr5b} " .
1260 "order by localip, localport, remoteip, remoteport, proto";
1261 $result = usePreparedSelectBlade ($query, $qparams);
1262 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1263 {
1264 $localip_bin = ip2long ($row['localip']);
1265 if (!isset ($ret[$localip_bin]))
1266 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1267 $ret[$localip_bin]['outpf'][] = $row;
1268 }
1269 unset ($result);
1270 return $ret;
1271 }
1272
1273 // Check the range requested for meaningful IPv6 records, build them
1274 // into a list and return. Return an empty list if nothing matched.
1275 // Both arguments are expected as instances of IPv6Address class. The resulting list
1276 // is keyed by uint32 form of each IP address, items aren't sorted.
1277 function scanIPv6Space ($pairlist)
1278 {
1279 $ret = array();
1280 $wheres = array();
1281 foreach ($pairlist as $pair)
1282 {
1283 $wheres[] = "ip >= ? AND ip <= ?";
1284 $qparams[] = (string) $pair['first'];
1285 $qparams[] = (string) $pair['last'];
1286 }
1287 if (! count ($wheres)) // this is normal for a network completely divided into smaller parts
1288 return $ret;
1289 $whereexpr = '(' .implode (' OR ', $wheres) . ')';
1290
1291 // 1. collect labels and reservations
1292 $query = "select ip, name, reserved from IPv6Address ".
1293 "where ${whereexpr} and (reserved = 'yes' or name != '')";
1294 $result = usePreparedSelectBlade ($query, $qparams);
1295 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1296 {
1297 $ip_bin = new IPv6Address ($row['ip']);
1298 $key = (string)$ip_bin;
1299 if (!isset ($ret[$key]))
1300 $ret[$key] = constructIPv6Address ($ip_bin);
1301 $ret[$key]['name'] = $row['name'];
1302 $ret[$key]['reserved'] = $row['reserved'];
1303 }
1304 unset ($result);
1305
1306 // 2. check for allocations
1307 $query =
1308 "select ip, object_id, name, type " .
1309 "from IPv6Allocation where ${whereexpr} order by type";
1310 $result = usePreparedSelectBlade ($query, $qparams);
1311 // release DBX early to avoid issues with nested spotEntity() calls
1312 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1313 unset ($result);
1314 foreach ($allRows as $row)
1315 {
1316 $ip_bin = new IPv6Address ($row['ip']);
1317 $key = (string)$ip_bin;
1318 if (!isset ($ret[$key]))
1319 $ret[$key] = constructIPv6Address ($ip_bin);
1320 $oinfo = spotEntity ('object', $row['object_id']);
1321 $ret[$key]['allocs'][] = array
1322 (
1323 'type' => $row['type'],
1324 'name' => $row['name'],
1325 'object_id' => $row['object_id'],
1326 'object_name' => $oinfo['dname'],
1327 );
1328 }
1329 return $ret;
1330 }
1331
1332 // this is a wrapper around getIPv4Address and getIPv6Address
1333 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1334 function getIPAddress ($ip)
1335 {
1336 if (is_a ($ip, 'IPv6Address'))
1337 return getIPv6Address ($ip);
1338 $ipv6 = new IPv6Address;
1339 if ($ipv6->parse ($ip))
1340 return getIPv6Address ($ipv6);
1341 return getIPv4Address ($ip);
1342 }
1343
1344 function getIPv4Address ($dottedquad = '')
1345 {
1346 if ($dottedquad == '')
1347 throw new InvalidArgException ('$dottedquad', $dottedquad);
1348 $i32 = ip2long ($dottedquad); // signed 32 bit
1349 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1350 if (empty ($scanres))
1351 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1352 return constructIPv4Address ($dottedquad);
1353 markupIPAddrList ($scanres);
1354 return $scanres[$i32];
1355 }
1356
1357 // returns the array of structure described by constructIPv6Address
1358 function getIPv6Address ($v6addr)
1359 {
1360 if (! is_object ($v6addr))
1361 throw new InvalidArgException ('$v6addr', $v6addr);
1362 $scanres = scanIPv6Space (array (array ('first' => $v6addr, 'last' => $v6addr)));
1363 if (empty ($scanres))
1364 return constructIPv6Address ($v6addr);
1365 markupIPAddrList ($scanres);
1366 return array_shift ($scanres);
1367 }
1368
1369 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1370 {
1371 return usePreparedExecuteBlade
1372 (
1373 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1374 array ($ip, $object_id, $name, $type)
1375 );
1376 }
1377
1378 function bindIPv6ToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1379 {
1380 return usePreparedInsertBlade
1381 (
1382 'IPv6Allocation',
1383 array ('ip' => $ip, 'object_id' => $object_id, 'name' => $name, 'type' => $type)
1384 );
1385 }
1386
1387 // Return the id of the smallest IPv4 network containing the given IPv4 address
1388 // or NULL, if nothing was found. When finding the covering network for
1389 // another network, it is important to filter out matched records with longer
1390 // masks (they aren't going to be the right pick).
1391 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1392 {
1393 $query = 'select id from IPv4Network where ' .
1394 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1395 "and mask < ? " .
1396 'order by mask desc limit 1';
1397 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
1398 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1399 return $row['id'];
1400 return NULL;
1401 }
1402
1403 // Return the id of the smallest IPv6 network containing the given IPv6 address
1404 // ($ip is an instance of IPv4Address class) or NULL, if nothing was found.
1405 function getIPv6AddressNetworkId ($ip, $masklen = 128)
1406 {
1407 $query = 'select id from IPv6Network where ip <= ? AND last_ip >= ? and mask < ? order by mask desc limit 1';
1408 $result = usePreparedSelectBlade ($query, array ((string)$ip, (string)$ip, $masklen));
1409 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1410 return $row['id'];
1411 return NULL;
1412 }
1413
1414 // It is a wrapper around updateV4Address and updateV6Address.
1415 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1416 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1417 {
1418 if (is_a ($ip, 'IPv6Address'))
1419 return updateV6Address ($ip, $name, $reserved);
1420 $ipv6 = new IPv6Address;
1421 if ($ipv6->parse ($ip))
1422 return updateV6Address ($ipv6, $name, $reserved);
1423 return updateV4Address ($ip, $name, $reserved);
1424 }
1425
1426 // This function is actually used not only to update, but also to create records,
1427 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1428 // (MySQL 4.0 workaround).
1429 function updateV4Address ($ip = 0, $name = '', $reserved = 'no')
1430 {
1431 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
1432 // INSERT may appear not necessary.
1433 if ($name == '' and $reserved == 'no')
1434 return '';
1435 $ret = usePreparedExecuteBlade
1436 (
1437 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1438 array ($name, $reserved, $ip)
1439 );
1440 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
1441 }
1442
1443 function updateV6Address ($ip, $name = '', $reserved = 'no')
1444 {
1445 usePreparedDeleteBlade ('IPv6Address', array ('ip' => $ip));
1446 // INSERT may appear not necessary.
1447 if ($name == '' and $reserved == 'no')
1448 return '';
1449 $ret = usePreparedInsertBlade
1450 (
1451 'IPv6Address',
1452 array ('name' => $name, 'reserved' => $reserved, 'ip' => $ip)
1453 );
1454 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
1455 }
1456
1457 function updateBond ($ip='', $object_id=0, $name='', $type='')
1458 {
1459 return usePreparedExecuteBlade
1460 (
1461 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1462 array ($name, $type, $ip, $object_id)
1463 );
1464 }
1465
1466 function updateIPv6Bond ($ip='', $object_id=0, $name='', $type='')
1467 {
1468 return usePreparedUpdateBlade
1469 (
1470 'IPv6Allocation',
1471 array
1472 (
1473 'name' => $name,
1474 'type' => $type,
1475 ),
1476 array
1477 (
1478 'ip' => $ip,
1479 'object_id' => $object_id,
1480 )
1481 );
1482 }
1483
1484 function unbindIpFromObject ($ip, $object_id)
1485 {
1486 return usePreparedExecuteBlade
1487 (
1488 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1489 array ($ip, $object_id)
1490 );
1491 }
1492
1493 function unbindIPv6FromObject ($ip, $object_id)
1494 {
1495 return usePreparedDeleteBlade
1496 (
1497 'IPv6Allocation',
1498 array ('ip' => $ip, 'object_id' => $object_id)
1499 );
1500 }
1501
1502 function getIPv4PrefixSearchResult ($terms)
1503 {
1504 $byname = getSearchResultByField
1505 (
1506 'IPv4Network',
1507 array ('id'),
1508 'name',
1509 $terms,
1510 'ip'
1511 );
1512 $ret = array();
1513 foreach ($byname as $row)
1514 $ret[$row['id']] = spotEntity ('ipv4net', $row['id']);
1515 return $ret;
1516 }
1517
1518 function getIPv6PrefixSearchResult ($terms)
1519 {
1520 $byname = getSearchResultByField
1521 (
1522 'IPv6Network',
1523 array ('id'),
1524 'name',
1525 $terms,
1526 'ip'
1527 );
1528 $ret = array();
1529 foreach ($byname as $row)
1530 $ret[$row['id']] = spotEntity ('ipv6net', $row['id']);
1531 return $ret;
1532 }
1533
1534 function getIPv4AddressSearchResult ($terms)
1535 {
1536 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1537 $or = '';
1538 $qparams = array();
1539 foreach (explode (' ', $terms) as $term)
1540 {
1541 $query .= $or . "name like ?";
1542 $or = ' or ';
1543 $qparams[] = "%${term}%";
1544 }
1545 $result = usePreparedSelectBlade ($query, $qparams);
1546 $ret = array();
1547 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1548 $ret[$row['ip']] = $row;
1549 return $ret;
1550 }
1551
1552 function getIPv6AddressSearchResult ($terms)
1553 {
1554 $query = "select ip, name from IPv6Address where ";
1555 $or = '';
1556 $qparams = array();
1557 foreach (explode (' ', $terms) as $term)
1558 {
1559 $query .= $or . "name like ?";
1560 $or = ' or ';
1561 $qparams[] = "%${term}%";
1562 }
1563 $result = usePreparedSelectBlade ($query, $qparams);
1564 $ret = array();
1565 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1566 $ret[$row['ip']] = $row;
1567 return $ret;
1568 }
1569
1570 function getIPv4RSPoolSearchResult ($terms)
1571 {
1572 $byname = getSearchResultByField
1573 (
1574 'IPv4RSPool',
1575 array ('id'),
1576 'name',
1577 $terms,
1578 'name'
1579 );
1580 $ret = array();
1581 foreach ($byname as $row)
1582 $ret[$row['id']] = spotEntity ('ipv4rspool', $row['id']);
1583 return $ret;
1584 }
1585
1586 function getIPv4VServiceSearchResult ($terms)
1587 {
1588 $byname = getSearchResultByField
1589 (
1590 'IPv4VS',
1591 array ('id'),
1592 'name',
1593 $terms,
1594 'vip'
1595 );
1596 $ret = array();
1597 foreach ($byname as $row)
1598 $ret[$row['id']] = spotEntity ('ipv4vs', $row['id']);
1599 return $ret;
1600 }
1601
1602 function getAccountSearchResult ($terms)
1603 {
1604 $byUsername = getSearchResultByField
1605 (
1606 'UserAccount',
1607 array ('user_id', 'user_name', 'user_realname'),
1608 'user_name',
1609 $terms,
1610 'user_name'
1611 );
1612 $byRealname = getSearchResultByField
1613 (
1614 'UserAccount',
1615 array ('user_id', 'user_name', 'user_realname'),
1616 'user_realname',
1617 $terms,
1618 'user_name'
1619 );
1620 // Merge it together, if duplicates persist, byUsername wins
1621 foreach (array ($byRealname, $byUsername) as $array)
1622 foreach ($array as $user)
1623 {
1624 $user['realm'] = 'user';
1625 $ret[$user['user_id']] = $user;
1626 }
1627 return $ret;
1628 }
1629
1630 function getFileSearchResult ($terms)
1631 {
1632 $byName = getSearchResultByField
1633 (
1634 'File',
1635 array ('id'),
1636 'name',
1637 $terms,
1638 'name'
1639 );
1640 $byComment = getSearchResultByField
1641 (
1642 'File',
1643 array ('id'),
1644 'comment',
1645 $terms,
1646 'name'
1647 );
1648 // Filter out dupes.
1649 foreach ($byName as $res1)
1650 foreach (array_keys ($byComment) as $key2)
1651 if ($res1['id'] == $byComment[$key2]['id'])
1652 {
1653 unset ($byComment[$key2]);
1654 continue 2;
1655 }
1656 $ret = array();
1657 foreach (array_merge ($byName, $byComment) as $row)
1658 $ret[$row['id']] = spotEntity ('file', $row['id']);
1659 return $ret;
1660 }
1661
1662 function getRackSearchResult ($terms)
1663 {
1664 $byName = getSearchResultByField
1665 (
1666 'Rack',
1667 array ('id'),
1668 'name',
1669 $terms,
1670 'name'
1671 );
1672 $byComment = getSearchResultByField
1673 (
1674 'Rack',
1675 array ('id'),
1676 'comment',
1677 $terms,
1678 'name'
1679 );
1680 // Filter out dupes.
1681 foreach ($byName as $res1)
1682 foreach (array_keys ($byComment) as $key2)
1683 if ($res1['id'] == $byComment[$key2]['id'])
1684 {
1685 unset ($byComment[$key2]);
1686 continue 2;
1687 }
1688 $ret = array();
1689 foreach (array_merge ($byName, $byComment) as $row)
1690 $ret[$row['id']] = spotEntity ('rack', $row['id']);
1691 return $ret;
1692 }
1693
1694 function getVLANSearchResult ($terms)
1695 {
1696 $ret = array();
1697 $matches = array();
1698 if (preg_match ('/^vlan\s*(\d+)$/i', $terms, $matches))
1699 {
1700 $byID = getSearchResultByField
1701 (
1702 'VLANDescription',
1703 array ('domain_id', 'vlan_id'),
1704 'vlan_id',
1705 $matches[1],
1706 'domain_id',
1707 1
1708 );
1709 foreach ($byID as $row)
1710 {
1711 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1712 $ret[$vlan_ck] = $vlan_ck;
1713 }
1714 }
1715 else
1716 {
1717 $byDescr = getSearchResultByField
1718 (
1719 'VLANDescription',
1720 array ('domain_id', 'vlan_id'),
1721 'vlan_descr',
1722 $terms
1723 );
1724 foreach ($byDescr as $row)
1725 {
1726 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1727 $ret[$vlan_ck] = $vlan_ck;
1728 }
1729 }
1730 return $ret;
1731 }
1732
1733 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
1734 {
1735 $pfx = '';
1736 $query = 'select ';
1737 $qparams = array();
1738 foreach ($rcolumns as $col)
1739 {
1740 $query .= $pfx . $col;
1741 $pfx = ', ';
1742 }
1743 $pfx = '';
1744 $query .= " from ${tname} where ";
1745 foreach (explode (' ', $terms) as $term)
1746 {
1747 switch ($exactness)
1748 {
1749 case 2: // does this work as expected?
1750 $query .= $pfx . "binary ${scolumn} = ?";
1751 $qparams[] = $term;
1752 break;
1753 case 1:
1754 $query .= $pfx . "${scolumn} = ?";
1755 $qparams[] = $term;
1756 break;
1757 default:
1758 $query .= $pfx . "${scolumn} like ?";
1759 $qparams[] = "%${term}%";
1760 break;
1761 }
1762 $pfx = ' or ';
1763 }
1764 if ($ocolumn != '')
1765 $query .= " order by ${ocolumn}";
1766 $result = usePreparedSelectBlade ($query, $qparams);
1767 $ret = array();
1768 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1769 $ret[] = $row;
1770 return $ret;
1771 }
1772
1773 function getObjectSearchResults ($what)
1774 {
1775 $ret = array();
1776 global $searchfunc;
1777 foreach ($searchfunc['object'] as $method => $func)
1778 foreach ($func ($what) as $objRecord)
1779 {
1780 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1781 $ret[$objRecord['id']][$method] = $objRecord[$method];
1782 }
1783 return $ret;
1784 }
1785
1786 function getObjectAttrsSearchResults ($what)
1787 {
1788 $ret = array();
1789 foreach (array ('name', 'label', 'asset_no', 'barcode') as $column)
1790 {
1791 $tmp = getSearchResultByField
1792 (
1793 'RackObject',
1794 array ('id'),
1795 $column,
1796 $what,
1797 $column
1798 );
1799 foreach ($tmp as $row)
1800 {
1801 $ret[$row['id']]['id'] = $row['id'];
1802 $ret[$row['id']]['by_attr'][] = $column;
1803 }
1804 }
1805 return $ret;
1806 }
1807
1808 // Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1809 // which matched. A partilar object_id could be returned more, than once, if it has
1810 // multiple matching stickers. Search is only performed on "string" attributes.
1811 function getStickerSearchResults ($what, $exactness = 0)
1812 {
1813 $stickers = getSearchResultByField
1814 (
1815 'AttributeValue',
1816 array ('object_id', 'attr_id'),
1817 'string_value',
1818 $what,
1819 'object_id',
1820 $exactness
1821 );
1822 $map = getAttrMap();
1823 $ret = array();
1824 foreach ($stickers as $sticker)
1825 if ($map[$sticker['attr_id']]['type'] == 'string')
1826 {
1827 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
1828 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
1829 }
1830 return $ret;
1831 }
1832
1833 // search in port "reservation comment", "label" and "L2 address" columns
1834 function getPortSearchResults ($what)
1835 {
1836 $ret = array();
1837 $ports = getSearchResultByField
1838 (
1839 'Port',
1840 array ('object_id', 'id', 'reservation_comment'),
1841 'reservation_comment',
1842 $what,
1843 'object_id',
1844 0
1845 );
1846 foreach ($ports as $port)
1847 {
1848 $ret[$port['object_id']]['id'] = $port['object_id'];
1849 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
1850 }
1851 $ports = getSearchResultByField
1852 (
1853 'Port',
1854 array ('object_id', 'id', 'label'),
1855 'label',
1856 $what,
1857 'object_id',
1858 0
1859 );
1860 foreach ($ports as $port)
1861 {
1862 $ret[$port['object_id']]['id'] = $port['object_id'];
1863 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1864 }
1865 try
1866 {
1867 $db_l2address = l2addressForDatabase ($what);
1868 }
1869 catch (InvalidArgException $e)
1870 {
1871 return $ret;
1872 }
1873 $ports = getSearchResultByField
1874 (
1875 'Port',
1876 array ('object_id', 'id', 'l2address'),
1877 'l2address',
1878 $db_l2address,
1879 'object_id',
1880 2
1881 );
1882 foreach ($ports as $port)
1883 {
1884 $ret[$port['object_id']]['id'] = $port['object_id'];
1885 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
1886 }
1887 return $ret;
1888 }
1889
1890 // search in IPv4 allocations
1891 function getObjectIfacesSearchResults ($what)
1892 {
1893 $ret = array();
1894 $ifaces4 = getSearchResultByField
1895 (
1896 'IPv4Allocation',
1897 array ('object_id', 'name'),
1898 'name',
1899 $what,
1900 'object_id'
1901 );
1902 $ifaces6 = getSearchResultByField
1903 (
1904 'IPv6Allocation',
1905 array ('object_id', 'name'),
1906 'name',
1907 $what,
1908 'object_id'
1909 );
1910 foreach (array_merge ($ifaces4, $ifaces6) as $row)
1911 {
1912 $ret[$row['object_id']]['id'] = $row['object_id'];
1913 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1914 }
1915 return $ret;
1916 }
1917
1918 function getObjectNATSearchResults ($what)
1919 {
1920 $ret = array();
1921 $ifaces = getSearchResultByField
1922 (
1923 'IPv4NAT',
1924 array ('object_id', 'description'),
1925 'description',
1926 $what,
1927 'object_id'
1928 );
1929 foreach ($ifaces as $row)
1930 {
1931 $ret[$row['object_id']]['id'] = $row['object_id'];
1932 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1933 }
1934 return $ret;
1935 }
1936
1937 // This function returns either port ID or NULL for specified arguments.
1938 function getPortIDs ($object_id, $port_name)
1939 {
1940 $ret = array();
1941 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
1942 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1943 $ret[] = $row['id'];
1944 return $ret;
1945 }
1946
1947 // Search in "FQDN" attribute only, and return object ID, when there is exactly
1948 // one result found (and NULL in any other case).
1949 function searchByMgmtHostname ($string)
1950 {
1951 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
1952 $rows = $result->fetchAll (PDO::FETCH_NUM);
1953 if (count ($rows) != 1)
1954 return NULL;
1955 return $rows[0][0];
1956 }
1957
1958 function commitCreateUserAccount ($username, $realname, $password)
1959 {
1960 return usePreparedInsertBlade
1961 (
1962 'UserAccount',
1963 array
1964 (
1965 'user_name' => $username,
1966 'user_realname' => $realname,
1967 'user_password_hash' => $password,
1968 )
1969 );
1970 }
1971
1972 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1973 {
1974 return usePreparedUpdateBlade
1975 (
1976 'UserAccount',
1977 array
1978 (
1979 'user_name' => $new_username,
1980 'user_realname' => $new_realname,
1981 'user_password_hash' => $new_password,
1982 ),
1983 array ('user_id' => $id)
1984 );
1985 }
1986
1987 // This function returns an array of all port type pairs from PortCompat table.
1988 function getPortOIFCompat ()
1989 {
1990 $query =
1991 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1992 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1993 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1994 'ORDER BY type1name, type2name';
1995 $result = usePreparedSelectBlade ($query);
1996 return $result->fetchAll (PDO::FETCH_ASSOC);
1997 }
1998
1999 function getDictStats ()
2000 {
2001 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
2002 $result = usePreparedSelectBlade
2003 (
2004 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
2005 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
2006 );
2007 $tc = $tw = $uc = $uw = 0;
2008 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2009 {
2010 $tc++;
2011 $tw += $row['wc'];;
2012 if (in_array ($row['chapter_no'], $stock_chapters))
2013 continue;
2014 $uc++;
2015 $uw += $row['wc'];;
2016 }
2017 unset ($result);
2018 $result = usePreparedSelectBlade
2019 (
2020 "select count(object_id) as attrc from RackObject as ro left join " .
2021 "AttributeValue as av on ro.id = av.object_id group by ro.id"
2022 );
2023 $to = $ta = $so = 0;
2024 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2025 {
2026 $to++;
2027 if ($row['attrc'] != 0)
2028 {
2029 $so++;
2030 $ta += $row['attrc'];
2031 }
2032 }
2033 unset ($result);
2034 $ret = array();
2035 $ret['Total chapters in dictionary'] = $tc;
2036 $ret['Total words in dictionary'] = $tw;
2037 $ret['User chapters'] = $uc;
2038 $ret['Words in user chapters'] = $uw;
2039 $ret['Total objects'] = $to;
2040 $ret['Objects with stickers'] = $so;
2041 $ret['Total stickers attached'] = $ta;
2042 return $ret;
2043 }
2044
2045 function getIPv4Stats ()
2046 {
2047 $ret = array();
2048 $subject = array();
2049 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
2050 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
2051 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
2052 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
2053 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
2054 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
2055 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
2056 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
2057
2058 foreach ($subject as $item)
2059 {
2060 $result = usePreparedSelectBlade ($item['q']);
2061 $row = $result->fetch (PDO::FETCH_NUM);
2062 $ret[$item['txt']] = $row[0];
2063 unset ($result);
2064 }
2065 return $ret;
2066 }
2067
2068 function getIPv6Stats ()
2069 {
2070 $ret = array();
2071 $subject = array();
2072 $subject[] = array ('q' => 'select count(id) from IPv6Network', 'txt' => 'Networks');
2073 $subject[] = array ('q' => 'select count(ip) from IPv6Address', 'txt' => 'Addresses commented/reserved');
2074 $subject[] = array ('q' => 'select count(ip) from IPv6Allocation', 'txt' => 'Addresses allocated');
2075
2076 foreach ($subject as $item)
2077 {
2078 $result = usePreparedSelectBlade ($item['q']);
2079 $row = $result->fetch (PDO::FETCH_NUM);
2080 $ret[$item['txt']] = $row[0];
2081 unset ($result);
2082 }
2083 return $ret;
2084 }
2085
2086 function getRackspaceStats ()
2087 {
2088 $ret = array();
2089 $subject = array();
2090 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
2091 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
2092 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
2093 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
2094
2095 foreach ($subject as $item)
2096 {
2097 $result = usePreparedSelectBlade ($item['q']);
2098 $row = $result->fetch (PDO::FETCH_NUM);
2099 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
2100 unset ($result);
2101 }
2102 return $ret;
2103 }
2104
2105 /*
2106
2107 The following allows figuring out records in TagStorage, which refer to non-existing entities:
2108
2109 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
2110 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
2111 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
2112 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
2113 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
2114 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
2115 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
2116
2117 Accordingly, these are the records, which refer to non-existent tags:
2118
2119 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
2120
2121 */
2122
2123 function commitDeleteChapter ($chapter_no = 0)
2124 {
2125 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
2126 }
2127
2128 // This is a dictionary accessor. We perform link rendering, so the user sees
2129 // nice <select> drop-downs.
2130 function readChapter ($chapter_id = 0, $style = '')
2131 {
2132 $result = usePreparedSelectBlade
2133 (
2134 "select dict_key, dict_value from Dictionary " .
2135 "where chapter_id = ?",
2136 array ($chapter_id)
2137 );
2138 $chapter = array();
2139 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2140 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
2141 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2142 asort ($chapter);
2143 return $chapter;
2144 }
2145
2146 // Return refcounters for all given keys of the given chapter.
2147 function getChapterRefc ($chapter_id, $keylist)
2148 {
2149 $ret = array();
2150 foreach ($keylist as $key)
2151 $ret[$key] = 0;
2152 switch ($chapter_id)
2153 {
2154 case CHAP_OBJTYPE:
2155 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
2156 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
2157 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
2158 break;
2159 case CHAP_PORTTYPE:
2160 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
2161 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
2162 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
2163 "from Dictionary where chapter_id = ?";
2164 break;
2165 default:
2166 // Find the list of all assigned values of dictionary-addressed attributes, each with
2167 // chapter/word keyed reference counters.
2168 $query = "select uint_value, count(object_id) as refcnt
2169 from AttributeMap am
2170 inner join AttributeValue av on am.attr_id = av.attr_id
2171 inner join RackObject ro on ro.id = av.object_id
2172 where am.chapter_id = ? and ro.objtype_id = am.objtype_id
2173 group by uint_value";
2174 break;
2175 }
2176 $result = usePreparedSelectBlade ($query, array ($chapter_id));
2177 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2178 $ret[$row['uint_value']] = $row['refcnt'];
2179 return $ret;
2180 }
2181
2182 // Return a list of all stickers with sticker map applied. Each sticker records will
2183 // list all its ways on the map with refcnt set.
2184 function getAttrMap ()
2185 {
2186 $result = usePreparedSelectBlade
2187 (
2188 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
2189 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
2190 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
2191 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
2192 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
2193 );
2194 $ret = array();
2195 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2196 {
2197 if (!isset ($ret[$row['id']]))
2198 $ret[$row['id']] = array
2199 (
2200 'id' => $row['id'],
2201 'type' => $row['type'],
2202 'name' => $row['name'],
2203 'application' => array(),
2204 );
2205 if ($row['objtype_id'] == '')
2206 continue;
2207 $application = array
2208 (
2209 'objtype_id' => $row['objtype_id'],
2210 'refcnt' => $row['refcnt'],
2211 );
2212 if ($row['type'] == 'dict')
2213 {
2214 $application['chapter_no'] = $row['chapter_id'];
2215 $application['chapter_name'] = $row['chapter_name'];
2216 }
2217 $ret[$row['id']]['application'][] = $application;
2218 }
2219 return $ret;
2220 }
2221
2222 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2223 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2224 {
2225 if ($attr_id <= 0)
2226 throw new InvalidArgException ('$attr_id', $attr_id);
2227 if ($objtype_id <= 0)
2228 throw new InvalidArgException ('$objtype_id', $objtype_id);
2229
2230 return usePreparedInsertBlade
2231 (
2232 'AttributeMap',
2233 array
2234 (
2235 'attr_id' => $attr_id,
2236 'objtype_id' => $objtype_id,
2237 'chapter_id' => $chapter_no
2238 )
2239 );
2240 }
2241
2242 function cacheAllObjectsAttributes()
2243 {
2244 global $object_attribute_cache;
2245 $object_attribute_cache = fetchAttrsForObjects(NULL);
2246 }
2247
2248 // Fetches a list of attributes for each object in $object_set array.
2249 // If $object_set is not set, returns attributes for all objects in DB
2250 // Returns an array with object_id keys
2251 function fetchAttrsForObjects($object_set)
2252 {
2253 $ret = array();
2254 $query =
2255 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2256 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value, RO.id as object_id from " .
2257 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2258 "inner join Attribute as A on AM.attr_id = A.id " .
2259 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2260 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2261 "left join Chapter as C on AM.chapter_id = C.id";
2262 if (is_array ($object_set) && !empty ($object_set))
2263 {
2264 $query .= ' WHERE RO.id IN (';
2265 foreach ($object_set as $object_id)
2266 $query .= intval ($object_id) . ', ';
2267 $query = trim ($query, ', ') . ')';
2268 }
2269 $query .= " order by A.name, A.type";
2270
2271 $result = usePreparedSelectBlade ($query);
2272 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2273 {
2274 $object_id = $row['object_id'];
2275 $attr_id = $row['attr_id'];
2276 if (!array_key_exists ($object_id, $ret))
2277 $ret[$object_id] = array();
2278
2279 $record = array();
2280 $record['id'] = $row['attr_id'];
2281 $record['name'] = $row['attr_name'];
2282 $record['type'] = $row['attr_type'];
2283 switch ($row['attr_type'])
2284 {
2285 case 'dict':
2286 $record['chapter_id'] = $row['chapter_id'];
2287 $record['chapter_name'] = $row['chapter_name'];
2288 $record['key'] = $row['uint_value'];
2289 // fall through
2290 case 'uint':
2291 case 'float':
2292 case 'string':
2293 $record['value'] = $row[$row['attr_type'] . '_value'];
2294 $record['o_value'] = parseWikiLink ($record['value'], 'o');
2295 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2296 break;
2297 default:
2298 $record['value'] = NULL;
2299 break;
2300 }
2301 $ret[$object_id][$attr_id] = $record;
2302 }
2303 return $ret;
2304 }
2305
2306 // This function returns all optional attributes for requested object
2307 // as an array of records.
2308 // Empty array is returned, if there are no attributes found.
2309 function getAttrValues ($object_id)
2310 {
2311 global $object_attribute_cache;
2312 if (isset ($object_attribute_cache[$object_id]))
2313 return $object_attribute_cache[$object_id];
2314
2315 $ret = fetchAttrsForObjects(array($object_id));
2316 $attrs = array();
2317 if (isset ($ret[$object_id]))
2318 {
2319 $attrs = $ret[$object_id];
2320 $object_attribute_cache[$object_id] = $attrs;
2321 }
2322 return $attrs;
2323 }
2324
2325 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2326 {
2327 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2328 }
2329
2330 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2331 {
2332 if ($object_id <= 0)
2333 throw new InvalidArgException ('$objtype_id', $objtype_id);
2334 if ($attr_id <= 0)
2335 throw new InvalidArgException ('$attr_id', $attr_id);
2336 if (!strlen ($value))
2337 return commitResetAttrValue ($object_id, $attr_id);
2338 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
2339 $row = $result->fetch (PDO::FETCH_NUM);
2340 $attr_type = $row[0];
2341 unset ($result);
2342 switch ($attr_type)
2343 {
2344 case 'uint':
2345 case 'float':
2346 case 'string':
2347 $column = $attr_type . '_value';
2348 break;
2349 case 'dict':
2350 $column = 'uint_value';
2351 break;
2352 default:
2353 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
2354 }
2355 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2356 // We know $value isn't empty here.
2357 usePreparedInsertBlade
2358 (
2359 'AttributeValue',
2360 array
2361 (
2362 $column => $value,
2363 'object_id' => $object_id,
2364 'attr_id' => $attr_id,
2365 )
2366 );
2367 return TRUE;
2368 }
2369
2370 function convertPDOException ($e)
2371 {
2372 switch ($e->getCode() . '-' . $e->errorInfo[1])
2373 {
2374 case '23000-1062':
2375 $text = 'such record already exists';
2376 break;
2377 case '23000-1205':
2378 $text = 'such record already exists';
2379 break;
2380 case '23000-1451':
2381 case '23000-1452':
2382 $text = 'foreign key violation';
2383 break;
2384 case 'HY000-1205':
2385 $text = 'lock wait timeout';
2386 break;
2387 default:
2388 return $e;
2389 }
2390 return new RTDatabaseError ($text);
2391 }
2392
2393 // This is a swiss-knife blade to insert a record into a table.
2394 // The first argument is table name.
2395 // The second argument is an array of "name" => "value" pairs.
2396 function usePreparedInsertBlade ($tablename, $columns)
2397 {
2398 global $dbxlink;
2399 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2400 $query .= ') VALUES (' . questionMarks (count ($columns)) . ')';
2401 // Now the query should be as follows:
2402 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
2403 try
2404 {
2405 $prepared = $dbxlink->prepare ($query);
2406 if (!$prepared->execute (array_values ($columns)))
2407 return FALSE;
2408 return $prepared->rowCount() == 1;
2409 }
2410 catch (PDOException $e)
2411 {
2412 throw convertPDOException ($e);
2413 }
2414 }
2415
2416 // This swiss-knife blade deletes any number of records from the specified table
2417 // using the specified key names and values.
2418 function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
2419 {
2420 global $dbxlink;
2421 $conj = '';
2422 $query = "DELETE FROM ${tablename} WHERE ";
2423 foreach ($columns as $colname => $colvalue)
2424 {
2425 $query .= " ${conj} ${colname}=?";
2426 $conj = $conjunction;
2427 }
2428 try
2429 {
2430 $prepared = $dbxlink->prepare ($query);
2431 if (!$prepared->execute (array_values ($columns)))
2432 return FALSE;
2433 return $prepared->rowCount(); // FALSE !== 0
2434 }
2435 catch (PDOException $e)
2436 {
2437 throw convertPDOException ($e);
2438 }
2439 }
2440
2441 function usePreparedSelectBlade ($query, $args = array())
2442 {
2443 global $dbxlink;
2444 $prepared = $dbxlink->prepare ($query);
2445 try
2446 {
2447 if (!$prepared->execute ($args))
2448 return FALSE;
2449 return $prepared;
2450 }
2451 catch (PDOException $e)
2452 {
2453 throw convertPDOException ($e);
2454 }
2455 }
2456
2457 function usePreparedUpdateBlade ($tablename, $set_columns, $where_columns, $conjunction = 'AND')
2458 {
2459 global $dbxlink;
2460 $conj = '';
2461 $query = "UPDATE ${tablename} SET ";
2462 foreach (array_keys ($set_columns) as $colname)
2463 {
2464 $query .= "${conj}${colname}=?";
2465 $conj = ', ';
2466 }
2467 $conj = '';
2468 $query .= ' WHERE ';
2469 foreach (array_keys ($where_columns) as $colname)
2470 {
2471 $query .= "${conj} ${colname}=?";
2472 $conj = $conjunction;
2473 }
2474 try
2475 {
2476 $prepared = $dbxlink->prepare ($query);
2477 $prepared->execute (array_merge (array_values ($set_columns), array_values ($where_columns)));
2478 }
2479 catch (PDOException $e)
2480 {
2481 throw convertPDOException ($e);
2482 }
2483 }
2484
2485 // Prepare and execute the statement with parameters, then return number of
2486 // rows affected (or FALSE in case of an error).
2487 function usePreparedExecuteBlade ($query, $args = array())
2488 {
2489 global $dbxlink;
2490 try
2491 {
2492 if (!$prepared = $dbxlink->prepare ($query))
2493 return FALSE;
2494 if (!$prepared->execute ($args))
2495 return FALSE;
2496 return $prepared->rowCount();
2497 }
2498 catch (PDOException $e)
2499 {
2500 throw convertPDOException ($e);
2501 }
2502 }
2503
2504 function loadConfigCache ()
2505 {
2506 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
2507 $cache = array();
2508 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2509 $cache[$row['varname']] = $row;
2510 return $cache;
2511 }
2512
2513 function loadUserConfigCache ($username = NULL)
2514 {
2515 if (!strlen ($username))
2516 throw new InvalidArgException ('$username', $username);
2517 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
2518 $cache = array();
2519 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2520 $cache[$row['varname']] = $row;
2521 return $cache;
2522 }
2523
2524 // Database version detector. Should behave corretly on any
2525 // working dataset a user might have.
2526 function getDatabaseVersion ()
2527 {
2528 $result = usePreparedSelectBlade ('SELECT varvalue FROM Config WHERE varname = "DB_VERSION" and vartype = "string"');
2529 if ($result == NULL)
2530 {
2531 // FIXME: this code is never executed, but an exception thrown instead
2532 global $dbxlink;
2533 $errorInfo = $dbxlink->errorInfo();
2534 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2535 return '0.14.4';
2536 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2537 }
2538 $rows = $result->fetchAll (PDO::FETCH_NUM);
2539 unset ($result);
2540 if (count ($rows) != 1 || !strlen ($rows[0][0]))
2541 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2542 $ret = $rows[0][0];
2543 return $ret;
2544 }
2545
2546 // Return an array of virtual services. For each of them list real server pools
2547 // with their load balancers and other stats.
2548 function getSLBSummary ()
2549 {
2550 $result = usePreparedSelectBlade
2551 (
2552 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2553 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2554 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2555 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2556 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2557 'group by vs.id, object_id order by vs.vip, object_id'
2558 );
2559 $ret = array();
2560 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2561 {
2562 $vsid = $row['vsid'];
2563 $object_id = $row['object_id'];
2564 if (!isset ($ret[$vsid]))
2565 {
2566 $ret[$vsid] = array();
2567 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2568 $ret[$vsid][$cname] = $row[$cname];
2569 $ret[$vsid]['lblist'] = array();
2570 }
2571 // There's only one assigned RS pool possible for each LB-VS combination.
2572 $ret[$vsid]['lblist'][$row['object_id']] = array
2573 (
2574 'id' => $row['rspool_id'],
2575 'size' => $row['rscount'],
2576 'name' => $row['pool_name']
2577 );
2578 }
2579 return $ret;
2580 }
2581
2582 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2583 {
2584 return usePreparedExecuteBlade
2585 (
2586 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
2587 array
2588 (
2589 $rsip,
2590 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2591 $pool_id,
2592 $inservice == 'yes' ? 'yes' : 'no',
2593 !strlen ($rsconfig) ? NULL : $rsconfig
2594 )
2595 );
2596 }
2597
2598 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '', $prio = '')
2599 {
2600 return usePreparedInsertBlade
2601 (
2602 'IPv4LB',
2603 array
2604 (
2605 'object_id' => $object_id,
2606 'rspool_id' => $pool_id,
2607 'vs_id' => $vs_id,
2608 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2609 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig),
2610 'prio' => (!strlen ($prio) ? NULL : $prio),
2611 )
2612 );
2613 }
2614
2615 function commitDeleteVS ($id = 0)
2616 {
2617 releaseFiles ('ipv4vs', $id);
2618 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
2619 }
2620
2621 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2622 {
2623 if (long2ip (ip2long ($rsip)) !== $rsip)
2624 throw new InvalidArgException ('$rsip', $rsip);
2625 return usePreparedExecuteBlade
2626 (
2627 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2628 array
2629 (
2630 $rsip,
2631 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2632 !strlen ($rsconfig) ? NULL : $rsconfig,
2633 $rsid,
2634 )
2635 );
2636 }
2637
2638 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2639 {
2640 if (!strlen ($vip))
2641 throw new InvalidArgException ('$vip', $vip);
2642 if ($vport <= 0)
2643 throw new InvalidArgException ('$vport', $vport);
2644 if (!strlen ($proto))
2645 throw new InvalidArgException ('$proto', $proto);
2646 return usePreparedExecuteBlade
2647 (
2648 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2649 array
2650 (
2651 $vip,
2652 $vport,
2653 $proto,
2654 !strlen ($name) ? NULL : $name,
2655 !strlen ($vsconfig) ? NULL : $vsconfig,
2656 !strlen ($rsconfig) ? NULL : $rsconfig,
2657 $vsid,
2658 )
2659 );
2660 }
2661
2662 function loadThumbCache ($rack_id = 0)
2663 {
2664 $ret = NULL;
2665 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
2666 $row = $result->fetch (PDO::FETCH_ASSOC);
2667 if ($row)
2668 $ret = base64_decode ($row['thumb_data']);
2669 return $ret;
2670 }
2671
2672 // Return the list of attached RS pools for the given object. As long as we have
2673 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2674 // by vs_id, because there will be only one RS pool listed for each VS of the
2675 // current object.
2676 function getRSPoolsForObject ($object_id = 0)
2677 {
2678 $result = usePreparedSelectBlade
2679 (
2680 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2681 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig, lb.prio from ' .
2682 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2683 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2684 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2685 'where lb.object_id = ? ' .
2686 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2687 array ($object_id)
2688 );
2689 $ret = array ();
2690 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2691 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig', 'prio') as $cname)
2692 $ret[$row['vs_id']][$cname] = $row[$cname];
2693 return $ret;
2694 }
2695
2696 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2697 {
2698 if (!strlen ($name))
2699 throw new InvalidArgException ('$name', $name);
2700 if (!usePreparedInsertBlade
2701 (
2702 'IPv4RSPool',
2703 array
2704 (
2705 'name' => (!strlen ($name) ? NULL : $name),
2706 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2707 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
2708 )
2709 ))
2710 return __FUNCTION__ . ': SQL insertion failed';
2711 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2712 }
2713
2714 function commitDeleteRSPool ($pool_id = 0)
2715 {
2716 releaseFiles ('ipv4rspool', $pool_id);
2717 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2718 }
2719
2720 function getRSList ()
2721 {
2722 $result = usePreparedSelectBlade
2723 (
2724 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2725 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2726 );
2727 $ret = array ();
2728 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2729 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2730 $ret[$row['id']][$cname] = $row[$cname];
2731 return $ret;
2732 }
2733
2734 // Return the list of all currently configured load balancers with their pool count.
2735 function getLBList ()
2736 {
2737 $result = usePreparedSelectBlade
2738 (
2739 "select object_id, count(rspool_id) as poolcount " .
2740 "from IPv4LB group by object_id order by object_id"
2741 );
2742 $ret = array ();
2743 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2744 $ret[$row['object_id']] = $row['poolcount'];
2745 return $ret;
2746 }
2747
2748 // For the given object return: its vsconfig/rsconfig; the list of RS pools
2749 // attached (each with vsconfig/rsconfig in turn), each with the list of
2750 // virtual services terminating the pool. Each pool also lists all real
2751 // servers with rsconfig.
2752 function getSLBConfig ($object_id)
2753 {
2754 $ret = array();
2755 $result = usePreparedSelectBlade
2756 (
2757 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2758 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2759 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, lb.prio as prio, pool.id as pool_id, pool.name as pool_name, ' .
2760 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2761 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2762 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2763 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2764 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2765 "where lb.object_id = ? and rs.inservice = 'yes' " .
2766 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2767 array ($object_id)
2768 );
2769 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2770 {
2771 $vs_id = $row['vs_id'];
2772 if (!isset ($ret[$vs_id]))
2773 {
2774 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name', 'prio') as $c)
2775 $ret[$vs_id][$c] = $row[$c];
2776 $ret[$vs_id]['rslist'] = array();
2777 }
2778 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2779 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2780 }
2781 return $ret;
2782 }
2783
2784 function commitUpdateSLBDefConf ($data)
2785 {
2786 return saveScript('DefaultVSConfig', $data['vs']) &&
2787 saveScript('DefaultRSConfig', $data['rs']);
2788 }
2789
2790 function getSLBDefaults ($do_cache_result = FALSE) {
2791 static $ret = array();
2792
2793 if (! $do_cache_result)
2794 $ret = array();
2795 elseif (! empty ($ret))
2796 return $ret;
2797
2798 $ret['vs'] = loadScript('DefaultVSConfig');
2799 $ret['rs'] = loadScript('DefaultRSConfig');
2800 return $ret;
2801 }
2802
2803 function commitSetInService ($rs_id = 0, $inservice = '')
2804 {
2805 if (! in_array ($inservice, array ('yes', 'no')))
2806 throw new InvalidArgException ('$inservice', $inservice);
2807 return usePreparedUpdateBlade ('IPv4RS', array ('inservice' => $inservice), array ('id' => $rs_id));
2808 }
2809
2810 function executeAutoPorts ($object_id = 0, $type_id = 0)
2811 {
2812 if ($object_id == 0)
2813 throw new InvalidArgException ('$object_id', $object_id);
2814 if ($type_id == 0)
2815 throw new InvalidArgException ('$type_id', $type_id);
2816 $ret = TRUE;
2817 foreach (getAutoPorts ($type_id) as $autoport)
2818 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2819 return $ret;
2820 }
2821
2822 // Return only implicitly listed tags, the rest of the chain will be
2823 // generated/deducted later at higher levels.
2824 // Result is a chain: randomly indexed taginfo list.
2825 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2826 {
2827 $ret = array();
2828 $result = usePreparedSelectBlade
2829 (
2830 "select tt.id, tag from " .
2831 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2832 "where entity_realm = ? and entity_id = ? " .
2833 "order by tt.tag",
2834 array ($entity_realm, $entity_id)
2835 );
2836 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2837 $ret[$row['id']] = $row;
2838 return getExplicitTagsOnly ($ret);
2839 }
2840
2841 // Return a tag chain with all DB tags on it.
2842 function getTagList ()
2843 {
2844 $ret = array();
2845 $result = usePreparedSelectBlade
2846 (
2847 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2848 "from TagTree left join TagStorage on id = tag_id " .
2849 "group by id, entity_realm order by tag"
2850 );
2851 // Collation index. The resulting rows are ordered according to default collation,
2852 // which is utf8_general_ci for UTF-8.
2853 $ci = 0;
2854 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2855 {
2856 if (!isset ($ret[$row['id']]))
2857 $ret[$row['id']] = array
2858 (
2859 'id' => $row['id'],
2860 'tag' => $row['tag'],
2861 'ci' => $ci++,
2862 'parent_id' => $row['parent_id'],
2863 'refcnt' => array ('total' => 0)
2864 );
2865 if ($row['realm'])
2866 {
2867 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2868 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2869 // introduce the 'pseudo'-ream 'ipnet' which combines 'ipv4net' and 'ipv6net' realms.
2870 if ($row['realm'] == 'ipv4net' || $row['realm'] == 'ipv6net')
2871 if (isset ($ret[$row['id']]['refcnt']['ipnet']))
2872 $ret[$row['id']]['refcnt']['ipnet'] += $row['refcnt'];
2873 else
2874 $ret[$row['id']]['refcnt']['ipnet'] = $row['refcnt'];
2875 }
2876 }
2877 return $ret;
2878 }
2879
2880 // Drop the whole chain stored.
2881 function destroyTagsForEntity ($entity_realm, $entity_id)
2882 {
2883 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
2884 }
2885
2886 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2887 // FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2888 // but not now.
2889 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2890 {
2891 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
2892 }
2893
2894 // Push a record into TagStorage unconditionally.
2895 function addTagForEntity ($realm, $entity_id, $tag_id)
2896 {
2897 global $SQLSchema;
2898 if (! array_key_exists ($realm, $SQLSchema))
2899 throw new InvalidArgException ('realm', $realm);
2900 // spotEntity ($realm, $entity_id) would be a more expensive way
2901 // to validate two parameters
2902 return usePreparedInsertBlade
2903 (
2904 'TagStorage',
2905 array
2906 (
2907 'entity_realm' => $realm,
2908 'entity_id' => $entity_id,
2909 'tag_id' => $tag_id,
2910 )
2911 );
2912 }
2913
2914 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2915 // on the implicit list already). Then remove any other records, which
2916 // appear on the "implicit" side of the chain. This will make sure,
2917 // that both the tag base is still minimal and all requested tags appear on
2918 // the resulting tag chain.
2919 // Return TRUE, if any changes were committed.
2920 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2921 {
2922 // Put the current explicit sub-chain into a buffer and merge all tags from
2923 // the extra chain, which aren't there yet.
2924 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2925 foreach ($extrachain as $extratag)
2926 if (!tagOnChain ($extratag, $newchain))
2927 $newchain[] = $extratag;
2928 // Then minimize the working buffer and check if it differs from the original
2929 // chain we started with. If it is so, save the work and signal the upper layer.
2930 $newchain = getExplicitTagsOnly ($newchain);
2931 if (tagChainCmp ($oldchain, $newchain))
2932 {
2933 destroyTagsForEntity ($realm, $entity_id);
2934 foreach ($newchain as $taginfo)
2935 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2936 return TRUE;
2937 }
2938 return FALSE;
2939 }
2940
2941 // Presume, that the target record has no tags attached.
2942 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2943 {
2944 if (!count ($tagidlist))
2945 return '';
2946 if (!$last_insert_id)
2947 $last_insert_id = lastInsertID();
2948 $errcount = 0;
2949 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
2950 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
2951 $errcount++;
2952 if (!$errcount)
2953 return '';
2954 else
2955 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2956 }
2957
2958 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2959 {
2960 // $range is in x.x.x.x/x format, split into ip/mask vars
2961 $rangeArray = explode('/', $range);
2962 if (count ($rangeArray) != 2)
2963 return "Invalid IPv4 prefix '${range}'";
2964 $ip = $rangeArray[0];
2965 $mask = $rangeArray[1];
2966
2967 if (!strlen ($ip) or !strlen ($mask))
2968 return "Invalid IPv4 prefix '${range}'";
2969 $ipL = ip2long($ip);
2970 $maskL = ip2long($mask);
2971 if ($ipL == -1 || $ipL === FALSE)
2972 return 'Bad IPv4 address';
2973 if ($mask < 32 && $mask > 0)
2974 $maskL = $mask;
2975 else
2976 {
2977 $maskB = decbin($maskL);
2978 if (strlen($maskB)!=32)
2979 return 'Invalid netmask';
2980 $ones=0;
2981 $zeroes=FALSE;
2982 foreach( str_split ($maskB) as $digit)
2983 {
2984 if ($digit == '0')
2985 $zeroes = TRUE;
2986 if ($digit == '1')
2987 {
2988 $ones++;
2989 if ($zeroes == TRUE)
2990 return 'Invalid netmask';
2991 }
2992 }
2993 $maskL = $ones;
2994 }
2995 $binmask = binMaskFromDec($maskL);
2996 $ipL = $ipL & $binmask;
2997 $result = usePreparedInsertBlade
2998 (
2999 'IPv4Network',
3000 array
3001 (
3002 'ip' => sprintf ('%u', $ipL),
3003 'mask' => $maskL,
3004 'name' => $name
3005 )
3006 );
3007 if ($result != TRUE)
3008 return "Could not add ${range} (already exists?).";
3009
3010 if ($is_bcast and $maskL < 31)
3011 {
3012 $network_addr = long2ip ($ipL);
3013 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3014 updateV4Address ($network_addr, 'network', 'yes');
3015 updateV4Address ($broadcast_addr, 'broadcast', 'yes');
3016 }
3017 return produceTagsForLastRecord ('ipv4net', $taglist);
3018 }
3019
3020 function createIPv6Prefix ($range = '', $name = '', $taglist = array())
3021 {
3022 // $range is in aaa0:b::c:d/x format, split into ip/mask vars
3023 $rangeArray = explode ('/', $range);
3024 if (count ($rangeArray) != 2)
3025 return "Invalid IPv6 prefix '${range}'";
3026 $ip = $rangeArray[0];
3027 $mask = $rangeArray[1];
3028 $address = new IPv6Address;
3029 if (!strlen ($ip) or !strlen ($mask) or ! $address->parse ($ip))
3030 return "Invalid IPv6 prefix '${range}'";
3031 $network_addr = $address->get_first_subnet_address ($mask);
3032 $broadcast_addr = $address->get_last_subnet_address ($mask);
3033 if (! $network_addr || ! $broadcast_addr)
3034 return 'Invalid netmask';
3035 $result = usePreparedInsertBlade
3036 (
3037 'IPv6Network',
3038 array
3039 (
3040 'ip' => $network_addr,
3041 'last_ip' => $broadcast_addr,
3042 'mask' => $mask,
3043 'name' => $name
3044 )
3045 );
3046 if ($result != TRUE)
3047 return "Could not add ${range} (already exists?).";
3048
3049 return produceTagsForLastRecord ('ipv6net', $taglist);
3050 }
3051
3052 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
3053 function destroyIPv4Prefix ($id = 0)
3054 {
3055 releaseFiles ('ipv4net', $id);
3056 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
3057 return __FUNCTION__ . ': SQL query #1 failed';
3058 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
3059 return __FUNCTION__ . ': SQL query #2 failed';
3060 return '';
3061 }
3062
3063 // FIXME: This function doesn't wipe relevant records from IPv6Address table.
3064 function destroyIPv6Prefix ($id = 0)
3065 {
3066 releaseFiles ('ipv6net', $id);
3067 if (FALSE === usePreparedDeleteBlade ('IPv6Network', array ('id' => $id)))
3068 return __FUNCTION__ . ': SQL query #1 failed';
3069 if (FALSE === destroyTagsForEntity ('ipv6net', $id))
3070 return __FUNCTION__ . ': SQL query #2 failed';
3071 return '';
3072 }
3073
3074 function loadScript ($name)
3075 {
3076 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
3077 $row = $result->fetch (PDO::FETCH_NUM);
3078 if ($row !== FALSE)
3079 return $row[0];
3080 else
3081 return NULL;
3082 }
3083
3084 function saveScript ($name = '', $text)
3085 {
3086 if (!strlen ($name))
3087 throw new InvalidArgException ('$name', $name);
3088 return usePreparedExecuteBlade
3089 (
3090 'INSERT INTO Script (script_name, script_text) VALUES (?, ?) ' .
3091 'ON DUPLICATE KEY UPDATE script_text=?',
3092 array ($name, $text, $text)
3093 );
3094 }
3095
3096 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3097 {
3098 if (NULL === getIPv4AddressNetworkId ($localip))
3099 return "$localip: Non existant ip";
3100 if (NULL === getIPv4AddressNetworkId ($remoteip))
3101 return "$remoteip: Non existant ip";
3102 if ( ($localport <= 0) or ($localport >= 65536) )
3103 return "$localport: invaild port";
3104 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3105 return "$remoteport: invaild port";
3106
3107 $result = usePreparedExecuteBlade
3108 (
3109 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
3110 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
3111 array
3112 (
3113 $object_id,
3114 $localip,
3115 $remoteip,
3116 $localport,
3117 $remoteport,
3118 $proto,
3119 $description,
3120 )
3121 );
3122 return $result !== FALSE ? '' : (__FUNCTION__ . '(): failed to insert the rule');
3123 }
3124
3125 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3126 {
3127 return usePreparedExecuteBlade
3128 (
3129 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
3130 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
3131 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
3132 );
3133 }
3134
3135 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3136 {
3137 return usePreparedExecuteBlade
3138 (
3139 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
3140 'AND localport=? AND remoteport=? AND proto=?',
3141 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
3142 );
3143 }
3144
3145 function getNATv4ForObject ($object_id)
3146 {
3147 $ret = array();
3148 $ret['out'] = array();
3149 $ret['in'] = array();
3150 $result = usePreparedSelectBlade
3151 (
3152 "select ".
3153 "proto, ".
3154 "INET_NTOA(localip) as localip, ".
3155 "localport, ".
3156 "INET_NTOA(remoteip) as remoteip, ".
3157 "remoteport, ".
3158 "ipa1.name as local_addr_name, " .
3159 "ipa2.name as remote_addr_name, " .
3160 "description ".
3161 "from IPv4NAT ".
3162 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3163 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
3164 "where object_id=? ".
3165 "order by localip, localport, proto, remoteip, remoteport",
3166 array ($object_id)
3167 );
3168 $count=0;
3169 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3170 {
3171 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3172 $ret['out'][$count][$cname] = $row[$cname];
3173 $count++;
3174 }
3175 unset ($result);
3176
3177 $result = usePreparedSelectBlade
3178 (
3179 "select ".
3180 "proto, ".
3181 "INET_NTOA(localip) as localip, ".
3182 "localport, ".
3183 "INET_NTOA(remoteip) as remoteip, ".
3184 "remoteport, ".
3185 "IPv4NAT.object_id as object_id, ".
3186 "RackObject.name as object_name, ".
3187 "description ".
3188 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3189 "where IPv4Allocation.object_id=? ".
3190 "order by remoteip, remoteport, proto, localip, localport",
3191 array ($object_id)
3192 );
3193 $count=0;
3194 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3195 {
3196 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3197 $ret['in'][$count][$cname] = $row[$cname];
3198 $count++;
3199 }
3200 return $ret;
3201 }
3202
3203 // Return a list of files, which are not linked to the specified record. This list
3204 // will be used by printSelect().
3205 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3206 {
3207 $query = usePreparedSelectBlade
3208 (
3209 'SELECT id, name FROM File ' .
3210 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
3211 'ORDER BY name, id',
3212 array ($entity_type, $entity_id)
3213 );
3214 $ret=array();
3215 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3216 $ret[$row['id']] = $row['name'];
3217 return $ret;
3218 }
3219
3220 // FIXME: return a standard cell list, so upper layer can iterate over
3221 // it conveniently.
3222 function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3223 {
3224 $query = usePreparedSelectBlade
3225 (
3226 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3227 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3228 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3229 array ($entity_type, $entity_id)
3230 );
3231 $ret = array();
3232 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3233 $ret[$row['file_id']] = array (
3234 'id' => $row['file_id'],
3235 'link_id' => $row['link_id'],
3236 'name' => $row['name'],
3237 'type' => $row['type'],
3238 'size' => $row['size'],
3239 'ctime' => $row['ctime'],
3240 'mtime' => $row['mtime'],
3241 'atime' => $row['atime'],
3242 'comment' => $row['comment'],
3243 );
3244 return $ret;
3245 }
3246
3247 function getFile ($file_id)
3248 {
3249 $query = usePreparedSelectBlade
3250 (
3251 'SELECT id, name, type, size, ctime, mtime, atime, contents, comment ' .
3252 'FROM File WHERE id = ?',
3253 array ($file_id)
3254 );
3255 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3256 // FIXME: isn't this repeating the code already in spotEntity()?
3257 throw new EntityNotFoundException ('file', $file_id);
3258 else
3259 {
3260 $ret = array();
3261 $ret['id'] = $row['id'];
3262 $ret['name'] = $row['name'];
3263 $ret['type'] = $row['type'];
3264 $ret['size'] = $row['size'];
3265 $ret['ctime'] = $row['ctime'];
3266 $ret['mtime'] = $row['mtime'];
3267 $ret['atime'] = $row['atime'];
3268 $ret['contents'] = $row['contents'];
3269 $ret['comment'] = $row['comment'];
3270 unset ($query);
3271
3272 // Someone accessed this file, update atime
3273 usePreparedExecuteBlade ('UPDATE File SET atime = NOW() WHERE id = ?', array ($file_id));
3274 }
3275 return $ret;
3276 }
3277
3278 function getFileCache ($file_id)
3279 {
3280 $query = usePreparedSelectBlade
3281 (
3282 'SELECT File.thumbnail FROM File ' .
3283 'WHERE File.id = ? and File.thumbnail IS NOT NULL',
3284 array ($file_id)
3285 );
3286 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3287 return FALSE;
3288 $ret = $row['thumbnail'];
3289 $query->CloseCursor();
3290 usePreparedExecuteBlade ('UPDATE File SET atime = NOW() WHERE id = ?', array ($file_id));
3291 return $ret;
3292 }
3293
3294 function commitAddFileCache ($file_id, $contents)
3295 {
3296 global $dbxlink;
3297 $query = $dbxlink->prepare('UPDATE File SET thumbnail = ? WHERE id = ?');
3298 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3299 $query->bindParam(2, $file_id);
3300 try
3301 {
3302 return $query->execute();
3303 }
3304 catch (PDOException $e)
3305 {
3306 throw convertPDOException ($e);
3307 }
3308 }
3309
3310 function getFileLinks ($file_id)
3311 {
3312 $query = usePreparedSelectBlade
3313 (
3314 'SELECT id, file_id, entity_type, entity_id FROM FileLink ' .
3315 'WHERE file_id = ? ORDER BY entity_type, entity_id',
3316 array ($file_id)
3317 );
3318 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
3319 $ret = array();
3320 foreach ($rows as $row)
3321 {
3322 // get info of the parent
3323 switch ($row['entity_type'])
3324 {
3325 case 'ipv4net': case 'ipv6net':
3326 $page = $row['entity_type'];
3327 $id_name = 'id';
3328 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3329 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3330 break;
3331 case 'ipv4rspool':
3332 $page = 'ipv4rspool';
3333 $id_name = 'pool_id';
3334 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3335 $name = $parent['name'];
3336 break;
3337 case 'ipv4vs':
3338 $page = 'ipv4vs';
3339 $id_name = 'vs_id';
3340 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3341 $name = $parent['name'];
3342 break;
3343 case 'object':
3344 $page = 'object';
3345 $id_name = 'object_id';
3346 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3347 $name = $parent['dname'];
3348 break;
3349 case 'rack':
3350 $page = 'rack';
3351 $id_name = 'rack_id';
3352 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3353 $name = $parent['name'];
3354 break;
3355 case 'user':
3356 $page = 'user';
3357 $id_name = 'user_id';
3358 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3359 $name = $parent['user_name'];
3360 break;
3361 }
3362
3363 // name needs to have some value for hrefs to work
3364 if (!strlen ($name))
3365 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3366