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