59aad04b846d1958f6cafb6b77201892169ae2b8
[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 if (!$prepared->execute (array_values ($columns)))
2179 return FALSE;
2180 return $prepared->rowCount() == 1;
2181 }
2182
2183 // This swiss-knife blade deletes one record from the specified table
2184 // using the specified key name and value.
2185 function useDeleteBlade ($tablename, $keyname, $keyvalue)
2186 {
2187 global $dbxlink;
2188 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
2189 }
2190
2191 // Prepared version of above, but note the difference in returned value.
2192 function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
2193 {
2194 global $dbxlink;
2195 $conj = '';
2196 $query = "DELETE FROM ${tablename} WHERE ";
2197 foreach ($columns as $colname => $colvalue)
2198 {
2199 $query .= " ${conj} ${colname}=?";
2200 $conj = $conjunction;
2201 }
2202 $prepared = $dbxlink->prepare ($query);
2203 if (!$prepared->execute (array_values ($columns)))
2204 return FALSE;
2205 return $prepared->rowCount(); // FALSE !== 0
2206 }
2207
2208 function useSelectBlade ($query)
2209 {
2210 global $dbxlink;
2211 $result = $dbxlink->query ($query);
2212 return $result;
2213 }
2214
2215 function usePreparedSelectBlade ($query, $args = array())
2216 {
2217 global $dbxlink;
2218 $prepared = $dbxlink->prepare ($query);
2219 if (!$prepared->execute ($args))
2220 return FALSE;
2221 return $prepared;
2222 }
2223
2224 function loadConfigCache ()
2225 {
2226 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
2227 $cache = array();
2228 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2229 $cache[$row['varname']] = $row;
2230 return $cache;
2231 }
2232
2233 function loadUserConfigCache ($username = NULL)
2234 {
2235 if (!strlen ($username))
2236 throw new InvalidArgException ('$username', $username);
2237 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
2238 $cache = array();
2239 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2240 $cache[$row['varname']] = $row;
2241 return $cache;
2242 }
2243
2244 function deleteUserConfigVar ($username = NULL, $varname = NULL)
2245 {
2246 usePreparedDeleteBlade ('UserConfig', array ('varname' => $varname, 'user' => $username));
2247 }
2248
2249 function storeUserConfigVar ($username = NULL, $varname = NULL, $varvalue = NULL)
2250 {
2251 global $dbxlink;
2252 if (!strlen ($username))
2253 throw new InvalidArgException ('$username', $username);
2254 if (!strlen ($varname))
2255 throw new InvalidArgException ('$varname', $varname);
2256 if ($varvalue === NULL)
2257 throw new InvalidArgException ('$varvalue', $varvalue);
2258 $query = "replace UserConfig set varvalue='${varvalue}', varname='${varname}', user='${username}'";
2259 $result = $dbxlink->query ($query);
2260 $result->closeCursor();
2261 }
2262
2263 // setConfigVar() is expected to perform all necessary filtering
2264 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2265 {
2266 global $dbxlink;
2267 if (!strlen ($varname))
2268 throw new InvalidArgException ('$varname', $varname);
2269 if ($varvalue === NULL)
2270 throw new InvalidArgException ('$varvalue', $varvalue);
2271 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2272 $result = $dbxlink->query ($query);
2273 $result->closeCursor();
2274 }
2275
2276 // Database version detector. Should behave corretly on any
2277 // working dataset a user might have.
2278 function getDatabaseVersion ()
2279 {
2280 global $dbxlink;
2281 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2282 $result = $dbxlink->query ($query);
2283 if ($result == NULL)
2284 {
2285 $errorInfo = $dbxlink->errorInfo();
2286 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2287 return '0.14.4';
2288 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2289 }
2290 $rows = $result->fetchAll (PDO::FETCH_NUM);
2291 if (count ($rows) != 1 || !strlen ($rows[0][0]))
2292 {
2293 $result->closeCursor();
2294 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2295 }
2296 $ret = $rows[0][0];
2297 $result->closeCursor();
2298 return $ret;
2299 }
2300
2301 // Return an array of virtual services. For each of them list real server pools
2302 // with their load balancers and other stats.
2303 function getSLBSummary ()
2304 {
2305 $result = usePreparedSelectBlade
2306 (
2307 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2308 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2309 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2310 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2311 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2312 'group by vs.id, object_id order by vs.vip, object_id'
2313 );
2314 $ret = array();
2315 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2316 {
2317 $vsid = $row['vsid'];
2318 $object_id = $row['object_id'];
2319 if (!isset ($ret[$vsid]))
2320 {
2321 $ret[$vsid] = array();
2322 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2323 $ret[$vsid][$cname] = $row[$cname];
2324 $ret[$vsid]['lblist'] = array();
2325 }
2326 // There's only one assigned RS pool possible for each LB-VS combination.
2327 $ret[$vsid]['lblist'][$row['object_id']] = array
2328 (
2329 'id' => $row['rspool_id'],
2330 'size' => $row['rscount'],
2331 'name' => $row['pool_name']
2332 );
2333 }
2334 return $ret;
2335 }
2336
2337 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2338 {
2339 if ($pool_id <= 0)
2340 throw new InvalidArgException ('$pool_id', $pool_id);
2341 if (!strlen ($rsport) or $rsport === 0)
2342 $rsport = 'NULL';
2343 return useInsertBlade
2344 (
2345 'IPv4RS',
2346 array
2347 (
2348 'rsip' => "inet_aton('${rsip}')",
2349 'rsport' => $rsport,
2350 'rspool_id' => $pool_id,
2351 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2352 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2353 )
2354 );
2355 }
2356
2357 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2358 {
2359 if (!strlen ($vip))
2360 throw new InvalidArgException ('$vip', $vip);
2361 if ($vport <= 0)
2362 throw new InvalidArgException ('$vport', $vport);
2363 if (!strlen ($proto))
2364 throw new InvalidArgException ('$proto', $proto);
2365 if (!useInsertBlade
2366 (
2367 'IPv4VS',
2368 array
2369 (
2370 'vip' => "inet_aton('${vip}')",
2371 'vport' => $vport,
2372 'proto' => "'${proto}'",
2373 'name' => (!strlen ($name) ? 'NULL' : "'${name}'"),
2374 'vsconfig' => (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2375 'rsconfig' => (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2376 )
2377 ))
2378 return __FUNCTION__ . ': SQL insertion failed';
2379 return produceTagsForLastRecord ('ipv4vs', $taglist);
2380 }
2381
2382 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2383 {
2384 return usePreparedInsertBlade
2385 (
2386 'IPv4LB',
2387 array
2388 (
2389 'object_id' => $object_id,
2390 'rspool_id' => $pool_id,
2391 'vs_id' => $vs_id,
2392 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2393 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
2394 )
2395 );
2396 }
2397
2398 function commitDeleteRS ($id = 0)
2399 {
2400 return usePreparedDeleteBlade ('IPv4RS', array ('id' => $id));
2401 }
2402
2403 function commitDeleteVS ($id = 0)
2404 {
2405 releaseFiles ('ipv4vs', $id);
2406 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
2407 }
2408
2409 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2410 {
2411 return usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id, 'rspool_id' => $pool_id, 'vs_id' => $vs_id));
2412 }
2413
2414 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2415 {
2416 if (long2ip (ip2long ($rsip)) !== $rsip)
2417 throw new InvalidArgException ('$rsip', $rsip);
2418 if (!strlen ($rsport) or $rsport === 0)
2419 $rsport = 'NULL';
2420 global $dbxlink;
2421 $query =
2422 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2423 (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2424 " where id = ${rsid} limit 1";
2425 $result = $dbxlink->query ($query);
2426 return TRUE;
2427 }
2428
2429 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2430 {
2431 global $dbxlink;
2432 $query =
2433 "update IPv4LB set vsconfig = " .
2434 (!strlen ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2435 ', rsconfig = ' .
2436 (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2437 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2438 "and vs_id = ${vs_id} limit 1";
2439 $result = $dbxlink->exec ($query);
2440 return TRUE;
2441 }
2442
2443 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2444 {
2445 if (!strlen ($vip))
2446 throw new InvalidArgException ('$vip', $vip);
2447 if ($vport <= 0)
2448 throw new InvalidArgException ('$vport', $vport);
2449 if (!strlen ($proto))
2450 throw new InvalidArgException ('$proto', $proto);
2451 global $dbxlink;
2452 $query = "update IPv4VS set " .
2453 "vip = inet_aton('${vip}'), " .
2454 "vport = ${vport}, " .
2455 "proto = '${proto}', " .
2456 'name = ' . (!strlen ($name) ? 'NULL,' : "'${name}', ") .
2457 'vsconfig = ' . (!strlen ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2458 'rsconfig = ' . (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2459 " where id = ${vsid} limit 1";
2460 $result = $dbxlink->exec ($query);
2461 return TRUE;
2462 }
2463
2464 function loadThumbCache ($rack_id = 0)
2465 {
2466 $ret = NULL;
2467 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
2468 $row = $result->fetch (PDO::FETCH_ASSOC);
2469 if ($row)
2470 $ret = base64_decode ($row['thumb_data']);
2471 return $ret;
2472 }
2473
2474 function saveThumbCache ($rack_id = 0, $cache = NULL)
2475 {
2476 global $dbxlink;
2477 if ($cache == NULL)
2478 throw new InvalidArgException ('$cache', $cache);
2479 $data = base64_encode ($cache);
2480 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2481 $result = $dbxlink->exec ($query);
2482 }
2483
2484 function resetThumbCache ($rack_id = 0)
2485 {
2486 global $dbxlink;
2487 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2488 $result = $dbxlink->exec ($query);
2489 }
2490
2491 // Return the list of attached RS pools for the given object. As long as we have
2492 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2493 // by vs_id, because there will be only one RS pool listed for each VS of the
2494 // current object.
2495 function getRSPoolsForObject ($object_id = 0)
2496 {
2497 $result = usePreparedSelectBlade
2498 (
2499 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2500 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2501 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2502 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2503 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2504 'where lb.object_id = ? ' .
2505 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2506 array ($object_id)
2507 );
2508 $ret = array ();
2509 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2510 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2511 $ret[$row['vs_id']][$cname] = $row[$cname];
2512 return $ret;
2513 }
2514
2515 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2516 {
2517 if (!strlen ($name))
2518 throw new InvalidArgException ('$name', $name);
2519 if (!usePreparedInsertBlade
2520 (
2521 'IPv4RSPool',
2522 array
2523 (
2524 'name' => (!strlen ($name) ? NULL : $name),
2525 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2526 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
2527 )
2528 ))
2529 return __FUNCTION__ . ': SQL insertion failed';
2530 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2531 }
2532
2533 function commitDeleteRSPool ($pool_id = 0)
2534 {
2535 releaseFiles ('ipv4rspool', $pool_id);
2536 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2537 }
2538
2539 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2540 {
2541 global $dbxlink;
2542 $query = "update IPv4RSPool set " .
2543 'name = ' . (!strlen ($name) ? 'NULL,' : "'${name}', ") .
2544 'vsconfig = ' . (!strlen ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2545 'rsconfig = ' . (!strlen ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2546 " where id = ${pool_id} limit 1";
2547 $result = $dbxlink->exec ($query);
2548 if ($result != 1)
2549 return FALSE;
2550 else
2551 return TRUE;
2552 }
2553
2554 function getRSList ()
2555 {
2556 $result = usePreparedSelectBlade
2557 (
2558 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2559 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2560 );
2561 $ret = array ();
2562 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2563 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2564 $ret[$row['id']][$cname] = $row[$cname];
2565 return $ret;
2566 }
2567
2568 // Return the list of all currently configured load balancers with their pool count.
2569 function getLBList ()
2570 {
2571 $result = usePreparedSelectBlade
2572 (
2573 "select object_id, count(rspool_id) as poolcount " .
2574 "from IPv4LB group by object_id order by object_id"
2575 );
2576 $ret = array ();
2577 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2578 $ret[$row['object_id']] = $row['poolcount'];
2579 return $ret;
2580 }
2581
2582 // For the given object return: its vsconfig/rsconfig; the list of RS pools
2583 // attached (each with vsconfig/rsconfig in turn), each with the list of
2584 // virtual services terminating the pool. Each pool also lists all real
2585 // servers with rsconfig.
2586 function getSLBConfig ($object_id)
2587 {
2588 $ret = array();
2589 $result = usePreparedSelectBlade
2590 (
2591 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2592 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2593 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2594 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2595 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2596 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2597 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2598 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2599 "where lb.object_id = ? and rs.inservice = 'yes' " .
2600 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2601 array ($object_id)
2602 );
2603 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2604 {
2605 $vs_id = $row['vs_id'];
2606 if (!isset ($ret[$vs_id]))
2607 {
2608 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)
2609 $ret[$vs_id][$c] = $row[$c];
2610 $ret[$vs_id]['rslist'] = array();
2611 }
2612 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2613 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2614 }
2615 return $ret;
2616 }
2617
2618 function commitSetInService ($rs_id = 0, $inservice = '')
2619 {
2620 if (!strlen ($inservice))
2621 throw new InvalidArgException ('$inservice', $inservice);
2622 if ($rs_id <= 0)
2623 throw new InvalidArgException ('$rs_id', $rs_id);
2624 global $dbxlink;
2625 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
2626 $result = $dbxlink->exec ($query);
2627 if ($result != 1)
2628 return FALSE;
2629 else
2630 return TRUE;
2631 }
2632
2633 function executeAutoPorts ($object_id = 0, $type_id = 0)
2634 {
2635 if ($object_id == 0)
2636 throw new InvalidArgException ('$object_id', $object_id);
2637 if ($type_id == 0)
2638 throw new InvalidArgException ('$type_id', $type_id);
2639 $ret = TRUE;
2640 foreach (getAutoPorts ($type_id) as $autoport)
2641 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2642 return $ret;
2643 }
2644
2645 // Return only implicitly listed tags, the rest of the chain will be
2646 // generated/deducted later at higher levels.
2647 // Result is a chain: randomly indexed taginfo list.
2648 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2649 {
2650 $ret = array();
2651 $result = usePreparedSelectBlade
2652 (
2653 "select tt.id, tag from " .
2654 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2655 "where entity_realm = ? and entity_id = ? " .
2656 "order by tt.tag",
2657 array ($entity_realm, $entity_id)
2658 );
2659 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2660 $ret[$row['id']] = $row;
2661 return getExplicitTagsOnly ($ret);
2662 }
2663
2664 // Return a tag chain with all DB tags on it.
2665 function getTagList ()
2666 {
2667 $ret = array();
2668 $result = usePreparedSelectBlade
2669 (
2670 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2671 "from TagTree left join TagStorage on id = tag_id " .
2672 "group by id, entity_realm order by tag"
2673 );
2674 // Collation index. The resulting rows are ordered according to default collation,
2675 // which is utf8_general_ci for UTF-8.
2676 $ci = 0;
2677 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2678 {
2679 if (!isset ($ret[$row['id']]))
2680 $ret[$row['id']] = array
2681 (
2682 'id' => $row['id'],
2683 'tag' => $row['tag'],
2684 'ci' => $ci++,
2685 'parent_id' => $row['parent_id'],
2686 'refcnt' => array ('total' => 0)
2687 );
2688 if ($row['realm'])
2689 {
2690 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2691 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2692 }
2693 }
2694 return $ret;
2695 }
2696
2697 function commitCreateTag ($tagname = '', $parent_id = 0)
2698 {
2699 if ($tagname == '' or $parent_id === 0)
2700 return "Invalid args to " . __FUNCTION__;
2701 $result = usePreparedInsertBlade
2702 (
2703 'TagTree',
2704 array
2705 (
2706 'tag' => $tagname,
2707 'parent_id' => $parent_id
2708 )
2709 );
2710 if ($result)
2711 return '';
2712 global $dbxlink;
2713 if ($dbxlink->errorCode() == 23000) // integrity constraint violation
2714 {
2715 $ei = $dbxlink->errorInfo();
2716 if ($ei[1] == 1062)
2717 return 'tag name must be unique';
2718 if ($ei[1] == 1452)
2719 return "parent tag id ${parent_id} does not exist";
2720 }
2721 return "SQL query failed in " . __FUNCTION__;
2722 }
2723
2724 function commitDestroyTag ($tagid = 0)
2725 {
2726 if (usePreparedDeleteBlade ('TagTree', array ('id' => $tagid)))
2727 return '';
2728 return 'usePreparedDeleteBlade() failed in ' . __FUNCTION__;
2729 }
2730
2731 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2732 {
2733 if ($parent_id == 0)
2734 $parent_id = 'NULL';
2735 global $dbxlink;
2736 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2737 "where id = ${tag_id} limit 1";
2738 $result = $dbxlink->exec ($query);
2739 if ($result !== FALSE)
2740 return '';
2741 if ($dbxlink->errorCode() == 23000)
2742 {
2743 $ei = $dbxlink->errorInfo();
2744 if ($ei[1] == 1062)
2745 return 'tag name must be unique';
2746 if ($ei[1] == 1452)
2747 return "parent tag id ${parent_id} does not exist";
2748 }
2749 return 'SQL query failed in ' . __FUNCTION__;
2750 }
2751
2752 // Drop the whole chain stored.
2753 function destroyTagsForEntity ($entity_realm, $entity_id)
2754 {
2755 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
2756 }
2757
2758 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2759 // FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2760 // but not now.
2761 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2762 {
2763 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
2764 }
2765
2766 // Push a record into TagStorage unconditionally.
2767 function addTagForEntity ($realm = '', $entity_id, $tag_id)
2768 {
2769 if (!in_array ($realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2770 return FALSE;
2771 return usePreparedInsertBlade
2772 (
2773 'TagStorage',
2774 array
2775 (
2776 'entity_realm' => $realm,
2777 'entity_id' => $entity_id,
2778 'tag_id' => $tag_id,
2779 )
2780 );
2781 }
2782
2783 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2784 // on the implicit list already). Then remove any other records, which
2785 // appear on the "implicit" side of the chain. This will make sure,
2786 // that both the tag base is still minimal and all requested tags appear on
2787 // the resulting tag chain.
2788 // Return TRUE, if any changes were committed.
2789 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2790 {
2791 // Put the current explicit sub-chain into a buffer and merge all tags from
2792 // the extra chain, which aren't there yet.
2793 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2794 foreach ($extrachain as $extratag)
2795 if (!tagOnChain ($extratag, $newchain))
2796 $newchain[] = $extratag;
2797 // Then minimize the working buffer and check if it differs from the original
2798 // chain we started with. If it is so, save the work and signal the upper layer.
2799 $newchain = getExplicitTagsOnly ($newchain);
2800 if (tagChainCmp ($oldchain, $newchain))
2801 {
2802 destroyTagsForEntity ($realm, $entity_id);
2803 foreach ($newchain as $taginfo)
2804 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2805 return TRUE;
2806 }
2807 return FALSE;
2808 }
2809
2810 // Presume, that the target record has no tags attached.
2811 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2812 {
2813 if (!count ($tagidlist))
2814 return '';
2815 if (!$last_insert_id)
2816 $last_insert_id = lastInsertID();
2817 $errcount = 0;
2818 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
2819 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
2820 $errcount++;
2821 if (!$errcount)
2822 return '';
2823 else
2824 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2825 }
2826
2827 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2828 {
2829 // $range is in x.x.x.x/x format, split into ip/mask vars
2830 $rangeArray = explode('/', $range);
2831 if (count ($rangeArray) != 2)
2832 return "Invalid IPv4 prefix '${range}'";
2833 $ip = $rangeArray[0];
2834 $mask = $rangeArray[1];
2835
2836 if (!strlen ($ip) or !strlen ($mask))
2837 return "Invalid IPv4 prefix '${range}'";
2838 $ipL = ip2long($ip);
2839 $maskL = ip2long($mask);
2840 if ($ipL == -1 || $ipL === FALSE)
2841 return 'Bad IPv4 address';
2842 if ($mask < 32 && $mask > 0)
2843 $maskL = $mask;
2844 else
2845 {
2846 $maskB = decbin($maskL);
2847 if (strlen($maskB)!=32)
2848 return 'Invalid netmask';
2849 $ones=0;
2850 $zeroes=FALSE;
2851 foreach( str_split ($maskB) as $digit)
2852 {
2853 if ($digit == '0')
2854 $zeroes = TRUE;
2855 if ($digit == '1')
2856 {
2857 $ones++;
2858 if ($zeroes == TRUE)
2859 return 'Invalid netmask';
2860 }
2861 }
2862 $maskL = $ones;
2863 }
2864 $binmask = binMaskFromDec($maskL);
2865 $ipL = $ipL & $binmask;
2866 $result = usePreparedInsertBlade
2867 (
2868 'IPv4Network',
2869 array
2870 (
2871 'ip' => sprintf ('%u', $ipL),
2872 'mask' => $maskL,
2873 'name' => $name
2874 )
2875 );
2876 if ($result != TRUE)
2877 return "Could not add ${range} (already exists?).";
2878
2879 if ($is_bcast and $maskL < 31)
2880 {
2881 $network_addr = long2ip ($ipL);
2882 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2883 updateAddress ($network_addr, 'network', 'yes');
2884 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2885 }
2886 return produceTagsForLastRecord ('ipv4net', $taglist);
2887 }
2888
2889 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
2890 function destroyIPv4Prefix ($id = 0)
2891 {
2892 releaseFiles ('ipv4net', $id);
2893 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
2894 return __FUNCTION__ . ': SQL query #1 failed';
2895 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
2896 return __FUNCTION__ . ': SQL query #2 failed';
2897 return '';
2898 }
2899
2900 function loadScript ($name)
2901 {
2902 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
2903 $row = $result->fetch (PDO::FETCH_NUM);
2904 if ($row !== FALSE)
2905 return $row[0];
2906 else
2907 return NULL;
2908 }
2909
2910 function saveScript ($name = '', $text)
2911 {
2912 if (!strlen ($name))
2913 throw new InvalidArgException ('$name', $name);
2914 // delete regardless of existence
2915 usePreparedDeleteBlade ('Script', array ('script_name' => $name));
2916 return usePreparedInsertBlade
2917 (
2918 'Script',
2919 array
2920 (
2921 'script_name' => $name,
2922 'script_text' => $text,
2923 )
2924 );
2925 }
2926
2927 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2928 {
2929 if (NULL === getIPv4AddressNetworkId ($localip))
2930 return "$localip: Non existant ip";
2931 if (NULL === getIPv4AddressNetworkId ($remoteip))
2932 return "$remoteip: Non existant ip";
2933 if ( ($localport <= 0) or ($localport >= 65536) )
2934 return "$localport: invaild port";
2935 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
2936 return "$remoteport: invaild port";
2937
2938 $result = useInsertBlade
2939 (
2940 'IPv4NAT',
2941 array
2942 (
2943 'object_id' => $object_id,
2944 'localip' => "INET_ATON('${localip}')",
2945 'remoteip' => "INET_ATON('$remoteip')",
2946 'localport' => $localport,
2947 'remoteport' => $remoteport,
2948 'proto' => "'${proto}'",
2949 'description' => "'${description}'",
2950 )
2951 );
2952 if ($result)
2953 return '';
2954 else
2955 return __FUNCTION__ . ': Failed to insert the rule.';
2956 }
2957
2958 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
2959 {
2960 global $dbxlink;
2961
2962 $query =
2963 "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'";
2964 $result = $dbxlink->exec ($query);
2965 return '';
2966 }
2967
2968 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2969 {
2970 global $dbxlink;
2971
2972 $query =
2973 "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'";
2974 $result = $dbxlink->exec ($query);
2975 return '';
2976 }
2977
2978 function getNATv4ForObject ($object_id)
2979 {
2980 $ret = array();
2981 $ret['out'] = array();
2982 $ret['in'] = array();
2983 $result = usePreparedSelectBlade
2984 (
2985 "select ".
2986 "proto, ".
2987 "INET_NTOA(localip) as localip, ".
2988 "localport, ".
2989 "INET_NTOA(remoteip) as remoteip, ".
2990 "remoteport, ".
2991 "ipa1.name as local_addr_name, " .
2992 "ipa2.name as remote_addr_name, " .
2993 "description ".
2994 "from IPv4NAT ".
2995 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
2996 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
2997 "where object_id=? ".
2998 "order by localip, localport, proto, remoteip, remoteport",
2999 array ($object_id)
3000 );
3001 $count=0;
3002 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3003 {
3004 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3005 $ret['out'][$count][$cname] = $row[$cname];
3006 $count++;
3007 }
3008 unset ($result);
3009
3010 $result = usePreparedSelectBlade
3011 (
3012 "select ".
3013 "proto, ".
3014 "INET_NTOA(localip) as localip, ".
3015 "localport, ".
3016 "INET_NTOA(remoteip) as remoteip, ".
3017 "remoteport, ".
3018 "IPv4NAT.object_id as object_id, ".
3019 "RackObject.name as object_name, ".
3020 "description ".
3021 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3022 "where IPv4Allocation.object_id=? ".
3023 "order by remoteip, remoteport, proto, localip, localport",
3024 array ($object_id)
3025 );
3026 $count=0;
3027 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3028 {
3029 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3030 $ret['in'][$count][$cname] = $row[$cname];
3031 $count++;
3032 }
3033 return $ret;
3034 }
3035
3036 // Return a list of files, which are not linked to the specified record. This list
3037 // will be used by printSelect().
3038 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3039 {
3040 $query = usePreparedSelectBlade
3041 (
3042 'SELECT id, name FROM File ' .
3043 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
3044 'ORDER BY name, id',
3045 array ($entity_type, $entity_id)
3046 );
3047 $ret=array();
3048 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3049 $ret[$row['id']] = $row['name'];
3050 return $ret;
3051 }
3052
3053 // FIXME: return a standard cell list, so upper layer can iterate over
3054 // it conveniently.
3055 function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3056 {
3057 $query = usePreparedSelectBlade
3058 (
3059 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3060 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3061 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3062 array ($entity_type, $entity_id)
3063 );
3064 $ret = array();
3065 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3066 $ret[$row['file_id']] = array (
3067 'id' => $row['file_id'],
3068 'link_id' => $row['link_id'],
3069 'name' => $row['name'],
3070 'type' => $row['type'],
3071 'size' => $row['size'],
3072 'ctime' => $row['ctime'],
3073 'mtime' => $row['mtime'],
3074 'atime' => $row['atime'],
3075 'comment' => $row['comment'],
3076 );
3077 return $ret;
3078 }
3079
3080 function getFile ($file_id = 0)
3081 {
3082 global $dbxlink;
3083 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3084 $query->bindParam(1, $file_id);
3085 $query->execute();
3086 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3087 {
3088 showWarning ('Query succeeded, but returned no data', __FUNCTION__);
3089 $ret = NULL;
3090 }
3091 else
3092 {
3093 $ret = array();
3094 $ret['id'] = $row['id'];
3095 $ret['name'] = $row['name'];
3096 $ret['type'] = $row['type'];
3097 $ret['size'] = $row['size'];
3098 $ret['ctime'] = $row['ctime'];
3099 $ret['mtime'] = $row['mtime'];
3100 $ret['atime'] = $row['atime'];
3101 $ret['contents'] = $row['contents'];
3102 $ret['comment'] = $row['comment'];
3103 $query->closeCursor();
3104
3105 // Someone accessed this file, update atime
3106 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3107 $q_atime->bindParam(1, date('YmdHis'));
3108 $q_atime->bindParam(2, $file_id);
3109 $q_atime->execute();
3110 }
3111 return $ret;
3112 }
3113
3114 function getFileLinks ($file_id = 0)
3115 {
3116 global $dbxlink;
3117 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ? ORDER BY entity_type, entity_id');
3118 $query->bindParam(1, $file_id);
3119 $query->execute();
3120 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
3121 $ret = array();
3122 foreach ($rows as $row)
3123 {
3124 // get info of the parent
3125 switch ($row['entity_type'])
3126 {
3127 case 'ipv4net':
3128 $page = 'ipv4net';
3129 $id_name = 'id';
3130 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3131 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3132 break;
3133 case 'ipv4rspool':
3134 $page = 'ipv4rspool';
3135 $id_name = 'pool_id';
3136 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3137 $name = $parent['name'];
3138 break;
3139 case 'ipv4vs':
3140 $page = 'ipv4vs';
3141 $id_name = 'vs_id';
3142 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3143 $name = $parent['name'];
3144 break;
3145 case 'object':
3146 $page = 'object';
3147 $id_name = 'object_id';
3148 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3149 $name = $parent['dname'];
3150 break;
3151 case 'rack':
3152 $page = 'rack';
3153 $id_name = 'rack_id';
3154 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3155 $name = $parent['name'];
3156 break;
3157 case 'user':
3158 $page = 'user';
3159 $id_name = 'user_id';
3160 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3161 $name = $parent['user_name'];
3162 break;
3163 }
3164
3165 // name needs to have some value for hrefs to work
3166 if (!strlen ($name))
3167 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3168
3169 $ret[$row['id']] = array(
3170 'page' => $page,
3171 'id_name' => $id_name,
3172 'entity_type' => $row['entity_type'],
3173 'entity_id' => $row['entity_id'],
3174 'name' => $name
3175 );
3176 }
3177 return $ret;
3178 }
3179
3180 function getFileStats ()
3181 {
3182 $result = usePreparedSelectBlade ('SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type');
3183 $ret = array();
3184 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3185 if ($row['count'] > 0)
3186 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3187 unset ($result);
3188
3189 // Find number of files without any linkage
3190 $result = usePreparedSelectBlade
3191 (
3192 'SELECT COUNT(*) ' .
3193 'FROM File ' .
3194 'WHERE id NOT IN (SELECT file_id FROM FileLink)'
3195 );
3196 $ret["Unattached files"] = $result->fetchColumn ();
3197 unset ($result);
3198
3199 // Find total number of files
3200 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM File');
3201 $ret["Total files"] = $result->fetchColumn ();
3202
3203 return $ret;
3204 }
3205
3206 function commitAddFile ($name, $type, $size, $contents, $comment)
3207 {
3208 $now = date('YmdHis');
3209
3210 global $dbxlink;
3211 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3212 $query->bindParam(1, $name);
3213 $query->bindParam(2, $type);
3214 $query->bindParam(3, $size);
3215 $query->bindParam(4, $now);
3216 $query->bindParam(5, $now);
3217 $query->bindParam(6, $now);
3218 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3219 $query->bindParam(8, $comment);
3220
3221 $result = $query->execute();
3222
3223
3224 if ($result)
3225 return '';
3226 elseif ($query->errorCode() == 23000)
3227 return "commitAddFile: File named '${name}' already exists";
3228 else
3229 return 'commitAddFile: SQL query failed';
3230 }
3231
3232 function commitLinkFile ($file_id, $entity_type, $entity_id)
3233 {
3234 global $dbxlink;
3235 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3236 $query->bindParam(1, $file_id);
3237 $query->bindParam(2, $entity_type);
3238 $query->bindParam(3, $entity_id);
3239
3240 $result = $query->execute();
3241
3242 if ($result)
3243 return '';
3244 else
3245 return 'commitLinkFile: SQL query failed';
3246 }
3247
3248 function commitReplaceFile ($file_id = 0, $contents)
3249 {
3250 global $dbxlink;
3251 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3252 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3253 $query->bindParam(2, $file_id);
3254
3255 $result = $query->execute();
3256 return '';
3257 }
3258
3259 function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
3260 {
3261 if (!strlen ($new_name))
3262 throw new InvalidArgException ('$new_name', $new_name);
3263 if (!strlen ($new_type))
3264 throw new InvalidArgException ('$new_type', $new_type);
3265 global $dbxlink;
3266 $query = $dbxlink->prepare('UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?');
3267 $query->bindParam(1, $new_name);
3268 $query->bindParam(2, $new_type);
3269 $query->bindParam(3, $new_comment);
3270 $query->bindParam(4, $file_id);
3271
3272 $result = $query->execute();
3273 if (!$result)
3274 return 'SQL query failed in ' . __FUNCTION__;
3275 return '';
3276 }
3277
3278 function commitUnlinkFile ($link_id)
3279 {
3280 if (usePreparedDeleteBlade ('FileLink', array ('id' => $link_id)) === FALSE)
3281 return __FUNCTION__ . ': useDeleteBlade() failed';
3282 return '';
3283 }
3284
3285 function commitDeleteFile ($file_id)
3286 {
3287 destroyTagsForEntity ('file', $file_id);
3288 if (usePreparedDeleteBlade ('File', array ('id' => $file_id)) === FALSE)
3289 return __FUNCTION__ . ': useDeleteBlade() failed';
3290 return '';
3291 }
3292
3293 function getChapterList ()
3294 {
3295 $ret = array();
3296 $result = usePreparedSelectBlade
3297 (
3298 'SELECT id, sticky, name, count(chapter_id) as wordc ' .
3299 'FROM Chapter LEFT JOIN Dictionary ON Chapter.id = chapter_id ' .
3300 'GROUP BY id ORDER BY name'
3301 );
3302 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3303 $ret[$row['id']] = $row;
3304 return $ret;
3305 }
3306
3307 // Return file id by file name.
3308 function findFileByName ($filename)
3309 {
3310 global $dbxlink;
3311 $query = $dbxlink->prepare('SELECT id FROM File WHERE name = ?');
3312 $query->bindParam(1, $filename);
3313 $query->execute();
3314 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
3315 return $row['id'];
3316
3317 return NULL;
3318 }
3319
3320 function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3321 {
3322 global $dbxlink;
3323 $dbxlink->beginTransaction();
3324 $result = usePreparedSelectBlade
3325 (
3326 'SELECT TIMESTAMPDIFF(SECOND, first_success, now()) AS success_age, ' .
3327 'TIMESTAMPDIFF(SECOND, last_retry, now()) AS retry_age, displayed_name, memberof ' .
3328 'FROM LDAPCache WHERE presented_username = ? AND successful_hash = ? ' .
3329 'HAVING success_age < ? FOR UPDATE',
3330 array ($form_username, $password_hash, $expiry)
3331 );
3332 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3333 {
3334 $row['memberof'] = unserialize (base64_decode ($row