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