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