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