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