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