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