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