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