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