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