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