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