90bf310b3543305b5f0d067ebb0418a4fc577b95
[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 InvalidArgException ('realm', $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 InvalidArgException ('realm', $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 return usePreparedExecuteBlade
1193 (
1194 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1195 array ($ip, $object_id, $name, $type)
1196 );
1197 }
1198
1199 // Return the id of the smallest IPv4 network containing the given IPv4 address
1200 // or NULL, if nothing was found. When finding the covering network for
1201 // another network, it is important to filter out matched records with longer
1202 // masks (they aren't going to be the right pick).
1203 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1204 {
1205 // N.B. To perform the same for IPv6 address and networks, some pre-requisites
1206 // are necessary and a different query. IPv6 addresses are 128 bit long, which
1207 // is too much for both PHP and MySQL data types. These values must be split
1208 // into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1209 // Then each network must have its 128-bit netmask split same way and either
1210 // stored right in its record or JOINed from decoder and accessible as m_u32_0,
1211 // m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1212 // covering the given address would look as follows:
1213 // $query = 'select id from IPv6Network as n where ' .
1214 // "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1215 // "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1216 // "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1217 // "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1218 // "mask < ${masklen} " .
1219 // 'order by mask desc limit 1';
1220
1221 $query = 'select id from IPv4Network where ' .
1222 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1223 "and mask < ? " .
1224 'order by mask desc limit 1';
1225 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
1226 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1227 return $row['id'];
1228 return NULL;
1229 }
1230
1231 function updateIPv4Network_real ($id = 0, $name = '', $comment = '')
1232 {
1233 return usePreparedExecuteBlade ('UPDATE IPv4Network SET name = ?, comment = ? WHERE id = ?', array ($name, $comment, $id));
1234 }
1235
1236 // This function is actually used not only to update, but also to create records,
1237 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1238 // (MySQL 4.0 workaround).
1239 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1240 {
1241 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
1242 // INSERT may appear not necessary.
1243 if ($name == '' and $reserved == 'no')
1244 return '';
1245 $ret = usePreparedExecuteBlade
1246 (
1247 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1248 array ($name, $reserved, $ip)
1249 );
1250 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
1251 }
1252
1253 function updateBond ($ip='', $object_id=0, $name='', $type='')
1254 {
1255 return usePreparedExecuteBlade
1256 (
1257 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1258 array ($name, $type, $ip, $object_id)
1259 );
1260 }
1261
1262 function unbindIpFromObject ($ip='', $object_id=0)
1263 {
1264 return usePreparedExecuteBlade
1265 (
1266 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1267 array ($ip, $object_id)
1268 );
1269 }
1270
1271 function getIPv4PrefixSearchResult ($terms)
1272 {
1273 $byname = getSearchResultByField
1274 (
1275 'IPv4Network',
1276 array ('id'),
1277 'name',
1278 $terms,
1279 'ip'
1280 );
1281 $ret = array();
1282 foreach ($byname as $row)
1283 $ret[] = spotEntity ('ipv4net', $row['id']);
1284 return $ret;
1285 }
1286
1287 function getIPv4AddressSearchResult ($terms)
1288 {
1289 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1290 $or = '';
1291 $qparams = array();
1292 foreach (explode (' ', $terms) as $term)
1293 {
1294 $query .= $or . "name like ?";
1295 $or = ' or ';
1296 $qparams[] = "%${term}%";
1297 }
1298 $result = usePreparedSelectBlade ($query, $qparams);
1299 $ret = array();
1300 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1301 $ret[] = $row;
1302 return $ret;
1303 }
1304
1305 function getIPv4RSPoolSearchResult ($terms)
1306 {
1307 $byname = getSearchResultByField
1308 (
1309 'IPv4RSPool',
1310 array ('id'),
1311 'name',
1312 $terms,
1313 'name'
1314 );
1315 $ret = array();
1316 foreach ($byname as $row)
1317 $ret[] = spotEntity ('ipv4rspool', $row['id']);
1318 return $ret;
1319 }
1320
1321 function getIPv4VServiceSearchResult ($terms)
1322 {
1323 $byname = getSearchResultByField
1324 (
1325 'IPv4VS',
1326 array ('id'),
1327 'name',
1328 $terms,
1329 'vip'
1330 );
1331 $ret = array();
1332 foreach ($byname as $row)
1333 $ret[] = spotEntity ('ipv4vs', $row['id']);
1334 return $ret;
1335 }
1336
1337 function getAccountSearchResult ($terms)
1338 {
1339 $byUsername = getSearchResultByField
1340 (
1341 'UserAccount',
1342 array ('user_id', 'user_name', 'user_realname'),
1343 'user_name',
1344 $terms,
1345 'user_name'
1346 );
1347 $byRealname = getSearchResultByField
1348 (
1349 'UserAccount',
1350 array ('user_id', 'user_name', 'user_realname'),
1351 'user_realname',
1352 $terms,
1353 'user_name'
1354 );
1355 // Filter out dupes.
1356 foreach ($byUsername as $res1)
1357 foreach (array_keys ($byRealname) as $key2)
1358 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1359 {
1360 unset ($byRealname[$key2]);
1361 continue 2;
1362 }
1363 $ret = array_merge ($byUsername, $byRealname);
1364 // Set realm, so it's renderable.
1365 foreach (array_keys ($ret) as $key)
1366 $ret[$key]['realm'] = 'user';
1367 return $ret;
1368 }
1369
1370 function getFileSearchResult ($terms)
1371 {
1372 $byName = getSearchResultByField
1373 (
1374 'File',
1375 array ('id'),
1376 'name',
1377 $terms,
1378 'name'
1379 );
1380 $byComment = getSearchResultByField
1381 (
1382 'File',
1383 array ('id'),
1384 'comment',
1385 $terms,
1386 'name'
1387 );
1388 // Filter out dupes.
1389 foreach ($byName as $res1)
1390 foreach (array_keys ($byComment) as $key2)
1391 if ($res1['id'] == $byComment[$key2]['id'])
1392 {
1393 unset ($byComment[$key2]);
1394 continue 2;
1395 }
1396 $ret = array();
1397 foreach (array_merge ($byName, $byComment) as $row)
1398 $ret[] = spotEntity ('file', $row['id']);
1399 return $ret;
1400 }
1401
1402 function getRackSearchResult ($terms)
1403 {
1404 $byName = getSearchResultByField
1405 (
1406 'Rack',
1407 array ('id'),
1408 'name',
1409 $terms,
1410 'name'
1411 );
1412 $byComment = getSearchResultByField
1413 (
1414 'Rack',
1415 array ('id'),
1416 'comment',
1417 $terms,
1418 'name'
1419 );
1420 // Filter out dupes.
1421 foreach ($byName as $res1)
1422 foreach (array_keys ($byComment) as $key2)
1423 if ($res1['id'] == $byComment[$key2]['id'])
1424 {
1425 unset ($byComment[$key2]);
1426 continue 2;
1427 }
1428 $ret = array();
1429 foreach (array_merge ($byName, $byComment) as $row)
1430 $ret[] = spotEntity ('rack', $row['id']);
1431 return $ret;
1432 }
1433
1434 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
1435 {
1436 $pfx = '';
1437 $query = 'select ';
1438 $qparams = array();
1439 foreach ($rcolumns as $col)
1440 {
1441 $query .= $pfx . $col;
1442 $pfx = ', ';
1443 }
1444 $pfx = '';
1445 $query .= " from ${tname} where ";
1446 foreach (explode (' ', $terms) as $term)
1447 {
1448 switch ($exactness)
1449 {
1450 case 2: // does this work as expected?
1451 $query .= $pfx . "binary ${scolumn} = ?";
1452 $qparams[] = $term;
1453 break;
1454 case 1:
1455 $query .= $pfx . "${scolumn} = ?";
1456 $qparams[] = $term;
1457 break;
1458 default:
1459 $query .= $pfx . "${scolumn} like ?";
1460 $qparams[] = "%${term}%";
1461 break;
1462 }
1463 $pfx = ' or ';
1464 }
1465 if ($ocolumn != '')
1466 $query .= " order by ${ocolumn}";
1467 $result = usePreparedSelectBlade ($query, $qparams);
1468 $ret = array();
1469 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1470 $ret[] = $row;
1471 return $ret;
1472 }
1473
1474 function getObjectSearchResults ($what)
1475 {
1476 $ret = array();
1477 global $searchfunc;
1478 foreach ($searchfunc['object'] as $method => $func)
1479 foreach ($func ($what) as $objRecord)
1480 {
1481 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1482 $ret[$objRecord['id']][$method] = $objRecord[$method];
1483 }
1484 return $ret;
1485 }
1486
1487 function getObjectAttrsSearchResults ($what)
1488 {
1489 $ret = array();
1490 foreach (array ('name', 'label', 'asset_no', 'barcode') as $column)
1491 {
1492 $tmp = getSearchResultByField
1493 (
1494 'RackObject',
1495 array ('id'),
1496 $column,
1497 $what,
1498 $column
1499 );
1500 foreach ($tmp as $row)
1501 {
1502 $ret[$row['id']]['id'] = $row['id'];
1503 $ret[$row['id']]['by_attr'][] = $column;
1504 }
1505 }
1506 return $ret;
1507 }
1508
1509 // Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1510 // which matched. A partilar object_id could be returned more, than once, if it has
1511 // multiple matching stickers. Search is only performed on "string" attributes.
1512 function getStickerSearchResults ($what, $exactness = 0)
1513 {
1514 $stickers = getSearchResultByField
1515 (
1516 'AttributeValue',
1517 array ('object_id', 'attr_id'),
1518 'string_value',
1519 $what,
1520 'object_id',
1521 $exactness
1522 );
1523 $map = getAttrMap();
1524 $ret = array();
1525 foreach ($stickers as $sticker)
1526 if ($map[$sticker['attr_id']]['type'] == 'string')
1527 {
1528 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
1529 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
1530 }
1531 return $ret;
1532 }
1533
1534 // search in port "reservation comment", "label" and "L2 address" columns
1535 function getPortSearchResults ($what)
1536 {
1537 $ret = array();
1538 $ports = getSearchResultByField
1539 (
1540 'Port',
1541 array ('object_id', 'id', 'reservation_comment'),
1542 'reservation_comment',
1543 $what,
1544 'object_id',
1545 0
1546 );
1547 foreach ($ports as $port)
1548 {
1549 $ret[$port['object_id']]['id'] = $port['object_id'];
1550 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
1551 }
1552 $ports = getSearchResultByField
1553 (
1554 'Port',
1555 array ('object_id', 'id', 'label'),
1556 'label',
1557 $what,
1558 'object_id',
1559 0
1560 );
1561 foreach ($ports as $port)
1562 {
1563 $ret[$port['object_id']]['id'] = $port['object_id'];
1564 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1565 }
1566 if (NULL === ($db_l2address = l2addressForDatabase ($what)))
1567 return $ret;
1568 $ports = getSearchResultByField
1569 (
1570 'Port',
1571 array ('object_id', 'id', 'l2address'),
1572 'l2address',
1573 $db_l2address,
1574 'object_id',
1575 2
1576 );
1577 foreach ($ports as $port)
1578 {
1579 $ret[$port['object_id']]['id'] = $port['object_id'];
1580 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
1581 }
1582 return $ret;
1583 }
1584
1585 // search in IPv4 allocations
1586 function getObjectIfacesSearchResults ($what)
1587 {
1588 $ret = array();
1589 $ifaces = getSearchResultByField
1590 (
1591 'IPv4Allocation',
1592 array ('object_id', 'name'),
1593 'name',
1594 $what,
1595 'object_id'
1596 );
1597 foreach ($ifaces as $row)
1598 {
1599 $ret[$row['object_id']]['id'] = $row['object_id'];
1600 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1601 }
1602 return $ret;
1603 }
1604
1605 function getObjectNATSearchResults ($what)
1606 {
1607 $ret = array();
1608 $ifaces = getSearchResultByField
1609 (
1610 'IPv4NAT',
1611 array ('object_id', 'description'),
1612 'description',
1613 $what,
1614 'object_id'
1615 );
1616 foreach ($ifaces as $row)
1617 {
1618 $ret[$row['object_id']]['id'] = $row['object_id'];
1619 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1620 }
1621 return $ret;
1622 }
1623
1624 // This function returns either port ID or NULL for specified arguments.
1625 function getPortIDs ($object_id, $port_name)
1626 {
1627 $ret = array();
1628 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
1629 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1630 $ret[] = $row['id'];
1631 return $ret;
1632 }
1633
1634 // Search in "FQDN" attribute only, and return object ID, when there is exactly
1635 // one result found (and NULL in any other case).
1636 function searchByMgmtHostname ($string)
1637 {
1638 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
1639 $rows = $result->fetchAll (PDO::FETCH_NUM);
1640 if (count ($rows) != 1)
1641 return NULL;
1642 return $rows[0][0];
1643 }
1644
1645 function commitCreateUserAccount ($username, $realname, $password)
1646 {
1647 return usePreparedInsertBlade
1648 (
1649 'UserAccount',
1650 array
1651 (
1652 'user_name' => $username,
1653 'user_realname' => $realname,
1654 'user_password_hash' => $password,
1655 )
1656 );
1657 }
1658
1659 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1660 {
1661 return usePreparedExecuteBlade
1662 (
1663 'UPDATE UserAccount SET user_name=?, user_realname=?, user_password_hash=? ' .
1664 'WHERE user_id=?',
1665 array ($new_username, $new_realname, $new_password, $id)
1666 );
1667 }
1668
1669 // This function returns an array of all port type pairs from PortCompat table.
1670 function getPortOIFCompat ()
1671 {
1672 $query =
1673 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1674 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1675 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1676 'ORDER BY type1name, type2name';
1677 $result = usePreparedSelectBlade ($query);
1678 return $result->fetchAll (PDO::FETCH_ASSOC);
1679 }
1680
1681 // Add a pair to the PortCompat table.
1682 function commitSupplementPOIFC ($type1, $type2)
1683 {
1684 if ($type1 <= 0)
1685 throw new InvalidArgException ('type1', $type1);
1686 if ($type2 <= 0)
1687 throw new InvalidArgException ('type2', $type2);
1688 return usePreparedInsertBlade
1689 (
1690 'PortCompat',
1691 array ('type1' => $type1, 'type2' => $type2)
1692 );
1693 }
1694
1695 // Remove a pair from the PortCompat table.
1696 function commitReducePOIFC ($type1, $type2)
1697 {
1698 return usePreparedDeleteBlade ('PortCompat', array ('type1' => $type1, 'type2' => $type2));
1699 }
1700
1701 function getDictStats ()
1702 {
1703 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
1704 $result = usePreparedSelectBlade
1705 (
1706 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
1707 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
1708 );
1709 $tc = $tw = $uc = $uw = 0;
1710 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1711 {
1712 $tc++;
1713 $tw += $row['wc'];;
1714 if (in_array ($row['chapter_no'], $stock_chapters))
1715 continue;
1716 $uc++;
1717 $uw += $row['wc'];;
1718 }
1719 $result->closeCursor();
1720 unset ($result);
1721 $result = usePreparedSelectBlade
1722 (
1723 "select count(object_id) as attrc from RackObject as ro left join " .
1724 "AttributeValue as av on ro.id = av.object_id group by ro.id"
1725 );
1726 $to = $ta = $so = 0;
1727 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1728 {
1729 $to++;
1730 if ($row['attrc'] != 0)
1731 {
1732 $so++;
1733 $ta += $row['attrc'];
1734 }
1735 }
1736 $result->closeCursor();
1737 $ret = array();
1738 $ret['Total chapters in dictionary'] = $tc;
1739 $ret['Total words in dictionary'] = $tw;
1740 $ret['User chapters'] = $uc;
1741 $ret['Words in user chapters'] = $uw;
1742 $ret['Total objects'] = $to;
1743 $ret['Objects with stickers'] = $so;
1744 $ret['Total stickers attached'] = $ta;
1745 return $ret;
1746 }
1747
1748 function getIPv4Stats ()
1749 {
1750 $ret = array();
1751 $subject = array();
1752 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1753 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1754 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1755 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1756 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1757 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1758 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1759 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
1760
1761 foreach ($subject as $item)
1762 {
1763 $result = usePreparedSelectBlade ($item['q']);
1764 $row = $result->fetch (PDO::FETCH_NUM);
1765 $ret[$item['txt']] = $row[0];
1766 $result->closeCursor();
1767 unset ($result);
1768 }
1769 return $ret;
1770 }
1771
1772 function getRackspaceStats ()
1773 {
1774 $ret = array();
1775 $subject = array();
1776 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
1777 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1778 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1779 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1780
1781 foreach ($subject as $item)
1782 {
1783 $result = usePreparedSelectBlade ($item['q']);
1784 $row = $result->fetch (PDO::FETCH_NUM);
1785 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
1786 $result->closeCursor();
1787 unset ($result);
1788 }
1789 return $ret;
1790 }
1791
1792 /*
1793
1794 The following allows figuring out records in TagStorage, which refer to non-existing entities:
1795
1796 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1797 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1798 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1799 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1800 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1801 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1802 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
1803
1804 Accordingly, these are the records, which refer to non-existent tags:
1805
1806 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1807
1808 */
1809
1810 // chapter_no is a must, see at @commitReduceDictionary() why
1811 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1812 {
1813 return usePreparedExecuteBlade
1814 (
1815 'UPDATE Dictionary SET dict_value=? WHERE chapter_id=? AND dict_key=?',
1816 array ($dict_value, $chapter_no, $dict_key)
1817 );
1818 }
1819
1820 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1821 {
1822 if ($chapter_no <= 0)
1823 throw new InvalidArgException ('$chapter_no', $chapter_no);
1824 if (!strlen ($dict_value))
1825 throw new InvalidArgException ('$dict_value', $dict_value);
1826 return usePreparedInsertBlade
1827 (
1828 'Dictionary',
1829 array ('chapter_id' => $chapter_no, 'dict_value' => $dict_value)
1830 );
1831 }
1832
1833 // Technically dict_key is enough to delete, but including chapter_id into
1834 // WHERE clause makes sure, that the action actually happends for the same
1835 // chapter, which authorization was granted for.
1836 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1837 {
1838 return usePreparedDeleteBlade ('Dictionary', array ('chapter_id' => $chapter_no, 'dict_key' => $dict_key));
1839 }
1840
1841 function commitAddChapter ($chapter_name = '')
1842 {
1843 if (!strlen ($chapter_name))
1844 throw new InvalidArgException ('$chapter_name', $chapter_name);
1845 return usePreparedInsertBlade
1846 (
1847 'Chapter',
1848 array ('name' => $chapter_name)
1849 );
1850 }
1851
1852 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1853 {
1854 if (!strlen ($chapter_name))
1855 throw new InvalidArgException ('$chapter_name', $chapter_name);
1856 return usePreparedExecuteBlade
1857 (
1858 'UPDATE Chapter SET name=? WHERE id=? AND sticky="no"',
1859 array ($chapter_name, $chapter_no)
1860 );
1861 }
1862
1863 function commitDeleteChapter ($chapter_no = 0)
1864 {
1865 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
1866 }
1867
1868 // This is a dictionary accessor. We perform link rendering, so the user sees
1869 // nice <select> drop-downs.
1870 function readChapter ($chapter_id = 0, $style = '')
1871 {
1872 $result = usePreparedSelectBlade
1873 (
1874 "select dict_key, dict_value from Dictionary " .
1875 "where chapter_id = ?",
1876 array ($chapter_id)
1877 );
1878 $chapter = array();
1879 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1880 $chapter[$row['dict_key']] = $style == '' ? $row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
1881 $result->closeCursor();
1882 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1883 asort ($chapter);
1884 return $chapter;
1885 }
1886
1887 // Return refcounters for all given keys of the given chapter.
1888 function getChapterRefc ($chapter_id, $keylist)
1889 {
1890 $ret = array();
1891 foreach ($keylist as $key)
1892 $ret[$key] = 0;
1893 switch ($chapter_id)
1894 {
1895 case CHAP_OBJTYPE:
1896 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
1897 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
1898 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
1899 break;
1900 case CHAP_PORTTYPE:
1901 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
1902 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
1903 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
1904 "from Dictionary where chapter_id = ?";
1905 break;
1906 default:
1907 // Find the list of all assigned values of dictionary-addressed attributes, each with
1908 // chapter/word keyed reference counters.
1909 $query = "select uint_value, count(object_id) as refcnt " .
1910 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1911 "inner join AttributeValue as av on a.id = av.attr_id " .
1912 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
1913 "where a.type = 'dict' and am.chapter_id = ? group by uint_value";
1914 break;
1915 }
1916 $result = usePreparedSelectBlade ($query, array ($chapter_id));
1917 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1918 $ret[$row['uint_value']] = $row['refcnt'];
1919 return $ret;
1920 }
1921
1922 // Return a list of all stickers with sticker map applied. Each sticker records will
1923 // list all its ways on the map with refcnt set.
1924 function getAttrMap ()
1925 {
1926 $result = usePreparedSelectBlade
1927 (
1928 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
1929 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
1930 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
1931 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
1932 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
1933 );
1934 $ret = array();
1935 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1936 {
1937 if (!isset ($ret[$row['id']]))
1938 $ret[$row['id']] = array
1939 (
1940 'id' => $row['id'],
1941 'type' => $row['type'],
1942 'name' => $row['name'],
1943 'application' => array(),
1944 );
1945 if ($row['objtype_id'] == '')
1946 continue;
1947 $application = array
1948 (
1949 'objtype_id' => $row['objtype_id'],
1950 'refcnt' => $row['refcnt'],
1951 );
1952 if ($row['type'] == 'dict')
1953 {
1954 $application['chapter_no'] = $row['chapter_id'];
1955 $application['chapter_name'] = $row['chapter_name'];
1956 }
1957 $ret[$row['id']]['application'][] = $application;
1958 }
1959 return $ret;
1960 }
1961
1962 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1963 {
1964 return usePreparedExecuteBlade ('UPDATE Attribute SET name=? WHERE id=?', array ($attr_name, $attr_id));
1965 }
1966
1967 function commitAddAttribute ($attr_name = '', $attr_type = '')
1968 {
1969 if (!strlen ($attr_name))
1970 throw new InvalidArgException ('$attr_name', $attr_name);
1971 switch ($attr_type)
1972 {
1973 case 'uint':
1974 case 'float':
1975 case 'string':
1976 case 'dict':
1977 break;
1978 default:
1979 throw new InvalidArgException ('$attr_type', $attr_type, 'Attribute type not supported');
1980 }
1981 return usePreparedInsertBlade
1982 (
1983 'Attribute',
1984 array ('name' => $attr_name, 'type' => $attr_type)
1985 );
1986 }
1987
1988 function commitDeleteAttribute ($attr_id = 0)
1989 {
1990 return usePreparedDeleteBlade ('Attribute', array ('id' => $attr_id));
1991 }
1992
1993 // FIXME: don't store garbage in chapter_no for non-dictionary types.
1994 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1995 {
1996 if ($attr_id <= 0)
1997 throw new InvalidArgException ('$attr_id', $attr_id);
1998 if ($objtype_id <= 0)
1999 throw new InvalidArgException ('$objtype_id', $objtype_id);
2000
2001 return usePreparedInsertBlade
2002 (
2003 'AttributeMap',
2004 array
2005 (
2006 'attr_id' => $attr_id,
2007 'objtype_id' => $objtype_id,
2008 'chapter_id' => $chapter_no
2009 )
2010 );
2011 }
2012
2013 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2014 {
2015 return usePreparedDeleteBlade ('AttributeMap', array ('attr_id' => $attr_id, 'objtype_id' => $objtype_id));
2016 }
2017
2018 // This function returns all optional attributes for requested object
2019 // as an array of records. NULL is returned on error and empty array
2020 // is returned, if there are no attributes found.
2021 function getAttrValues ($object_id)
2022 {
2023 $ret = array();
2024 $result = usePreparedSelectBlade
2025 (
2026 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2027 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2028 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2029 "inner join Attribute as A on AM.attr_id = A.id " .
2030 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2031 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2032 "left join Chapter as C on AM.chapter_id = C.id " .
2033 "where RO.id = ? order by A.name, A.type",
2034 array ($object_id)
2035 );
2036 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2037 {
2038 $record = array();
2039 $record['id'] = $row['attr_id'];
2040 $record['name'] = $row['attr_name'];
2041 $record['type'] = $row['attr_type'];
2042 switch ($row['attr_type'])
2043 {
2044 case 'dict':
2045 $record['chapter_id'] = $row['chapter_id'];
2046 $record['chapter_name'] = $row['chapter_name'];
2047 $record['key'] = $row['uint_value'];
2048 // fall through
2049 case 'uint':
2050 case 'float':
2051 case 'string':
2052 $record['value'] = $row[$row['attr_type'] . '_value'];
2053 $record['o_value'] = parseWikiLink ($record['value'], 'o');
2054 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2055 break;
2056 default:
2057 $record['value'] = NULL;
2058 break;
2059 }
2060 $ret[$row['attr_id']] = $record;
2061 }
2062 $result->closeCursor();
2063 return $ret;
2064 }
2065
2066 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2067 {
2068 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2069 }
2070
2071 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2072 {
2073 if ($object_id <= 0)
2074 throw new InvalidArgException ('$objtype_id', $objtype_id);
2075 if ($attr_id <= 0)
2076 throw new InvalidArgException ('$attr_id', $attr_id);
2077 if (!strlen ($value))
2078 return commitResetAttrValue ($object_id, $attr_id);
2079 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
2080 $row = $result->fetch (PDO::FETCH_NUM);
2081 $attr_type = $row[0];
2082 unset ($result);
2083 switch ($attr_type)
2084 {
2085 case 'uint':
2086 case 'float':
2087 case 'string':
2088 $column = $attr_type . '_value';
2089 break;
2090 case 'dict':
2091 $column = 'uint_value';
2092 break;
2093 default:
2094 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
2095 }
2096 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2097 // We know $value isn't empty here.
2098 usePreparedInsertBlade
2099 (
2100 'AttributeValue',
2101 array
2102 (
2103 $column => $value,
2104 'object_id' => $object_id,
2105 'attr_id' => $attr_id,
2106 )
2107 );
2108 return TRUE;
2109 }
2110
2111 function commitUseupPort ($port_id = 0)
2112 {
2113 return usePreparedExecuteBlade ('UPDATE Port SET reservation_comment=NULL WHERE id=?', array ($port_id));
2114 }
2115
2116 function convertPDOException ($e)
2117 {
2118 switch ($e->getCode() . '-' . $e->errorInfo[1])
2119 {
2120 case '23000-1062':
2121 $text = 'such record already exists';
2122 break;
2123 case '23000-1205':
2124 $text = 'such record already exists';
2125 break;
2126 case '23000-1451':
2127 case '23000-1452':
2128 $text = 'foreign key violation';
2129 break;
2130 case 'HY000-1205':
2131 $text = 'lock wait timeout';
2132 break;
2133 default:
2134 return $e;
2135 }
2136 return new RTDatabaseError ($text);
2137 }
2138
2139 // This is a swiss-knife blade to insert a record into a table.
2140 // The first argument is table name.
2141 // The second argument is an array of "name" => "value" pairs.
2142 function usePreparedInsertBlade ($tablename, $columns)
2143 {
2144 global $dbxlink;
2145 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2146 $query .= ') VALUES (' . questionMarks (count ($columns)) . ')';
2147 // Now the query should be as follows:
2148 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
2149 try
2150 {
2151 $prepared = $dbxlink->prepare ($query);
2152 if (!$prepared->execute (array_values ($columns)))
2153 return FALSE;
2154 return $prepared->rowCount() == 1;
2155 }
2156 catch (PDOException $e)
2157 {
2158 throw convertPDOException ($e);
2159 }
2160 }
2161
2162 // This swiss-knife blade deletes any number of records from the specified table
2163 // using the specified key names and values.
2164 function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
2165 {
2166 global $dbxlink;
2167 $conj = '';
2168 $query = "DELETE FROM ${tablename} WHERE ";
2169 foreach ($columns as $colname => $colvalue)
2170 {
2171 $query .= " ${conj} ${colname}=?";
2172 $conj = $conjunction;
2173 }
2174 try
2175 {
2176 $prepared = $dbxlink->prepare ($query);
2177 if (!$prepared->execute (array_values ($columns)))
2178 return FALSE;
2179 return $prepared->rowCount(); // FALSE !== 0
2180 }
2181 catch (PDOException $e)
2182 {
2183 throw convertPDOException ($e);
2184 }
2185 }
2186
2187 function usePreparedSelectBlade ($query, $args = array())
2188 {
2189 global $dbxlink;
2190 $prepared = $dbxlink->prepare ($query);
2191 try
2192 {
2193 if (!$prepared->execute ($args))
2194 return FALSE;
2195 return $prepared;
2196 }
2197 catch (PDOException $e)
2198 {
2199 throw convertPDOException ($e);
2200 }
2201 }
2202
2203 // Prepare and execute the statement with parameters, then return number of
2204 // rows affected (or FALSE in case of an error).
2205 function usePreparedExecuteBlade ($query, $args = array())
2206 {
2207 global $dbxlink;
2208 try
2209 {
2210 if (!$prepared = $dbxlink->prepare ($query))
2211 return FALSE;
2212 if (!$prepared->execute ($args))
2213 return FALSE;
2214 return $prepared->rowCount();
2215 }
2216 catch (PDOException $e)
2217 {
2218 throw convertPDOException ($e);
2219 }
2220 }
2221
2222 function loadConfigCache ()
2223 {
2224 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
2225 $cache = array();
2226 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2227 $cache[$row['varname']] = $row;
2228 return $cache;
2229 }
2230
2231 function loadUserConfigCache ($username = NULL)
2232 {
2233 if (!strlen ($username))
2234 throw new InvalidArgException ('$username', $username);
2235 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
2236 $cache = array();
2237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2238 $cache[$row['varname']] = $row;
2239 return $cache;
2240 }
2241
2242 function deleteUserConfigVar ($username = NULL, $varname = NULL)
2243 {
2244 usePreparedDeleteBlade ('UserConfig', array ('varname' => $varname, 'user' => $username));
2245 }
2246
2247 function storeUserConfigVar ($username = NULL, $varname = NULL, $varvalue = NULL)
2248 {
2249 if (!strlen ($username))
2250 throw new InvalidArgException ('$username', $username);
2251 if (!strlen ($varname))
2252 throw new InvalidArgException ('$varname', $varname);
2253 if ($varvalue === NULL)
2254 throw new InvalidArgException ('$varvalue', $varvalue);
2255 return usePreparedExecuteBlade
2256 (
2257 'REPLACE UserConfig SET varvalue=?, varname=?, user=?',
2258 array ($varvalue, $varname, $username)
2259 );
2260 }
2261
2262 // setConfigVar() is expected to perform all necessary filtering
2263 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2264 {
2265 if ($varvalue === NULL)
2266 throw new InvalidArgException ('$varvalue', $varvalue);
2267 return usePreparedExecuteBlade
2268 (
2269 'UPDATE Config SET varvalue=? WHERE varname=?',
2270 array ($varvalue, $varname)
2271 );
2272 }
2273
2274 // Database version detector. Should behave corretly on any
2275 // working dataset a user might have.
2276 function getDatabaseVersion ()
2277 {
2278 $result = usePreparedSelectBlade ('SELECT varvalue FROM Config WHERE varname = "DB_VERSION" and vartype = "string"');
2279 if ($result == NULL)
2280 {
2281 global $dbxlink;
2282 $errorInfo = $dbxlink->errorInfo();
2283 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2284 return '0.14.4';
2285 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2286 }
2287 $rows = $result->fetchAll (PDO::FETCH_NUM);
2288 if (count ($rows) != 1 || !strlen ($rows[0][0]))
2289 {
2290 $result->closeCursor();
2291 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2292 }
2293 $ret = $rows[0][0];
2294 $result->closeCursor();
2295 return $ret;
2296 }
2297
2298 // Return an array of virtual services. For each of them list real server pools
2299 // with their load balancers and other stats.
2300 function getSLBSummary ()
2301 {
2302 $result = usePreparedSelectBlade
2303 (
2304 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2305 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2306 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2307 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2308 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2309 'group by vs.id, object_id order by vs.vip, object_id'
2310 );
2311 $ret = array();
2312 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2313 {
2314 $vsid = $row['vsid'];
2315 $object_id = $row['object_id'];
2316 if (!isset ($ret[$vsid]))
2317 {
2318 $ret[$vsid] = array();
2319 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2320 $ret[$vsid][$cname] = $row[$cname];
2321 $ret[$vsid]['lblist'] = array();
2322 }
2323 // There's only one assigned RS pool possible for each LB-VS combination.
2324 $ret[$vsid]['lblist'][$row['object_id']] = array
2325 (
2326 'id' => $row['rspool_id'],
2327 'size' => $row['rscount'],
2328 'name' => $row['pool_name']
2329 );
2330 }
2331 return $ret;
2332 }
2333
2334 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2335 {
2336 return usePreparedExecuteBlade
2337 (
2338 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
2339 array
2340 (
2341 $rsip,
2342 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2343 $pool_id,
2344 $inservice == 'yes' ? 'yes' : 'no',
2345 !strlen ($rsconfig) ? NULL : $rsconfig
2346 )
2347 );
2348 }
2349
2350 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2351 {
2352 if (!strlen ($vip))
2353 throw new InvalidArgException ('$vip', $vip);
2354 if ($vport <= 0)
2355 throw new InvalidArgException ('$vport', $vport);
2356 if (!strlen ($proto))
2357 throw new InvalidArgException ('$proto', $proto);
2358 if (FALSE === usePreparedExecuteBlade
2359 (
2360 'INSERT INTO IPv4VS (vip, vport, proto, name, vsconfig, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?, ?)',
2361 array
2362 (
2363 $vip,
2364 $vport,
2365 $proto,
2366 !strlen ($name) ? NULL : $name,
2367 !strlen ($vsconfig) ? NULL : $vsconfig,
2368 !strlen ($rsconfig) ? NULL : $rsconfig,
2369 )
2370 ))
2371 return __FUNCTION__ . ': SQL insertion failed';
2372 return produceTagsForLastRecord ('ipv4vs', $taglist);
2373 }
2374
2375 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2376 {
2377 return usePreparedInsertBlade
2378 (
2379 'IPv4LB',
2380 array
2381 (
2382 'object_id' => $object_id,
2383 'rspool_id' => $pool_id,
2384 'vs_id' => $vs_id,
2385 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2386 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
2387 )
2388 );
2389 }
2390
2391 function commitDeleteRS ($id = 0)
2392 {
2393 return usePreparedDeleteBlade ('IPv4RS', array ('id' => $id));
2394 }
2395
2396 function commitDeleteVS ($id = 0)
2397 {
2398 releaseFiles ('ipv4vs', $id);
2399 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
2400 }
2401
2402 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2403 {
2404 return usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id, 'rspool_id' => $pool_id, 'vs_id' => $vs_id));
2405 }
2406
2407 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2408 {
2409 if (long2ip (ip2long ($rsip)) !== $rsip)
2410 throw new InvalidArgException ('$rsip', $rsip);
2411 return usePreparedExecuteBlade
2412 (
2413 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2414 array
2415 (
2416 $rsip,
2417 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2418 !strlen ($rsconfig) ? NULL : $rsconfig,
2419 $rsid,
2420 )
2421 );
2422 }
2423
2424 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2425 {
2426 return usePreparedExecuteBlade
2427 (
2428 'UPDATE IPv4LB SET vsconfig=?, rsconfig=? WHERE object_id=? AND rspool_id=? AND vs_id=?',
2429 array
2430 (
2431 !strlen ($vsconfig) ? NULL : $vsconfig,
2432 !strlen ($rsconfig) ? NULL : $rsconfig,
2433 $object_id,
2434 $pool_id,
2435 $vs_id,
2436 )
2437 );
2438 }
2439
2440 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2441 {
2442 if (!strlen ($vip))
2443 throw new InvalidArgException ('$vip', $vip);
2444 if ($vport <= 0)
2445 throw new InvalidArgException ('$vport', $vport);
2446 if (!strlen ($proto))
2447 throw new InvalidArgException ('$proto', $proto);
2448 return usePreparedExecuteBlade
2449 (
2450 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2451 array
2452 (
2453 $vip,
2454 $vport,
2455 $proto,
2456 !strlen ($name) ? NULL : $name,
2457 !strlen ($vsconfig) ? NULL : $vsconfig,
2458 !strlen ($rsconfig) ? NULL : $rsconfig,
2459 $vsid,
2460 )
2461 );
2462 }
2463
2464 function loadThumbCache ($rack_id = 0)
2465 {
2466 $ret = NULL;
2467 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
2468 $row = $result->fetch (PDO::FETCH_ASSOC);
2469 if ($row)
2470 $ret = base64_decode ($row['thumb_data']);
2471 return $ret;
2472 }
2473
2474 function saveThumbCache ($rack_id = 0, $cache = NULL)
2475 {
2476 if ($cache == NULL)
2477 throw new InvalidArgException ('$cache', $cache);
2478 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=? WHERE id=?', array (base64_encode ($cache), $rack_id));
2479 }
2480
2481 function resetThumbCache ($rack_id = 0)
2482 {
2483 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=NULL WHERE id=?', array ($rack_id));
2484 }
2485
2486 // Return the list of attached RS pools for the given object. As long as we have
2487 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2488 // by vs_id, because there will be only one RS pool listed for each VS of the
2489 // current object.
2490 function getRSPoolsForObject ($object_id = 0)
2491 {
2492 $result = usePreparedSelectBlade
2493 (
2494 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2495 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2496 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2497 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2498 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2499 'where lb.object_id = ? ' .
2500 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2501 array ($object_id)
2502 );
2503 $ret = array ();
2504 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2505 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2506 $ret[$row['vs_id']][$cname] = $row[$cname];
2507 return $ret;
2508 }
2509
2510 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2511 {
2512 if (!strlen ($name))
2513 throw new InvalidArgException ('$name', $name);
2514 if (!usePreparedInsertBlade
2515 (
2516 'IPv4RSPool',
2517 array
2518 (
2519 'name' => (!strlen ($name) ? NULL : $name),
2520 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2521 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
2522 )
2523 ))
2524 return __FUNCTION__ . ': SQL insertion failed';
2525 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2526 }
2527
2528 function commitDeleteRSPool ($pool_id = 0)
2529 {
2530 releaseFiles ('ipv4rspool', $pool_id);
2531 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2532 }
2533
2534 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2535 {
2536 return usePreparedExecuteBlade
2537 (
2538 'UPDATE IPv4RSPool SET name=?, vsconfig=?, rsconfig=? WHERE id=?',
2539 array
2540 (
2541 !strlen ($name) ? NULL : $name,
2542 !strlen ($vsconfig) ? NULL : $vsconfig,
2543 !strlen ($rsconfig) ? NULL : $rsconfig,
2544 $pool_id,
2545 )
2546 );
2547 }
2548
2549 function getRSList ()
2550 {
2551 $result = usePreparedSelectBlade
2552 (
2553 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2554 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2555 );
2556 $ret = array ();
2557 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2558 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2559 $ret[$row['id']][$cname] = $row[$cname];
2560 return $ret;
2561 }
2562
2563 // Return the list of all currently configured load balancers with their pool count.
2564 function getLBList ()
2565 {
2566 $result = usePreparedSelectBlade
2567 (
2568 "select object_id, count(rspool_id) as poolcount " .
2569 "from IPv4LB group by object_id order by object_id"
2570 );
2571 $ret = array ();
2572 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2573 $ret[$row['object_id']] = $row['poolcount'];
2574 return $ret;
2575 }
2576
2577 // For the given object return: its vsconfig/rsconfig; the list of RS pools
2578 // attached (each with vsconfig/rsconfig in turn), each with the list of
2579 // virtual services terminating the pool. Each pool also lists all real
2580 // servers with rsconfig.
2581 function getSLBConfig ($object_id)
2582 {
2583 $ret = array();
2584 $result = usePreparedSelectBlade
2585 (
2586 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2587 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2588 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2589 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2590 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2591 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2592 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2593 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2594 "where lb.object_id = ? and rs.inservice = 'yes' " .
2595 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2596 array ($object_id)
2597 );
2598 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2599 {
2600 $vs_id = $row['vs_id'];
2601 if (!isset ($ret[$vs_id]))
2602 {
2603 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)
2604 $ret[$vs_id][$c] = $row[$c];
2605 $ret[$vs_id]['rslist'] = array();
2606 }
2607 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2608 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2609 }
2610 return $ret;
2611 }
2612
2613 function commitSetInService ($rs_id = 0, $inservice = '')
2614 {
2615 if (!strlen ($inservice))
2616 throw new InvalidArgException ('$inservice', $inservice);
2617 return usePreparedExecuteBlade ('UPDATE IPv4RS SET inservice=? WHERE id=?', array ($inservice, $rs_id));
2618 }
2619
2620 function executeAutoPorts ($object_id = 0, $type_id = 0)
2621 {
2622 if ($object_id == 0)
2623 throw new InvalidArgException ('$object_id', $object_id);
2624 if ($type_id == 0)
2625 throw new InvalidArgException ('$type_id', $type_id);
2626 $ret = TRUE;
2627 foreach (getAutoPorts ($type_id) as $autoport)
2628 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2629 return $ret;
2630 }
2631
2632 // Return only implicitly listed tags, the rest of the chain will be
2633 // generated/deducted later at higher levels.
2634 // Result is a chain: randomly indexed taginfo list.
2635 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2636 {
2637 $ret = array();
2638 $result = usePreparedSelectBlade
2639 (
2640 "select tt.id, tag from " .
2641 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2642 "where entity_realm = ? and entity_id = ? " .
2643 "order by tt.tag",
2644 array ($entity_realm, $entity_id)
2645 );
2646 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2647 $ret[$row['id']] = $row;
2648 return getExplicitTagsOnly ($ret);
2649 }
2650
2651 // Return a tag chain with all DB tags on it.
2652 function getTagList ()
2653 {
2654 $ret = array();
2655 $result = usePreparedSelectBlade
2656 (
2657 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2658 "from TagTree left join TagStorage on id = tag_id " .
2659 "group by id, entity_realm order by tag"
2660 );
2661 // Collation index. The resulting rows are ordered according to default collation,
2662 // which is utf8_general_ci for UTF-8.
2663 $ci = 0;
2664 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2665 {
2666 if (!isset ($ret[$row['id']]))
2667 $ret[$row['id']] = array
2668 (
2669 'id' => $row['id'],
2670 'tag' => $row['tag'],
2671 'ci' => $ci++,
2672 'parent_id' => $row['parent_id'],
2673 'refcnt' => array ('total' => 0)
2674 );
2675 if ($row['realm'])
2676 {
2677 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2678 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
2679 }
2680 }
2681 return $ret;
2682 }
2683
2684 function commitCreateTag ($tagname = '', $parent_id = 0)
2685 {
2686 if ($tagname == '')
2687 throw new InvalidArgException ('tagname', $tagname);
2688 return usePreparedInsertBlade
2689 (
2690 'TagTree',
2691 array
2692 (
2693 'tag' => $tagname,
2694 'parent_id' => $parent_id
2695 )
2696 );
2697 }
2698
2699 function commitDestroyTag ($tagid = 0)
2700 {
2701 if (usePreparedDeleteBlade ('TagTree', array ('id' => $tagid)))
2702 return '';
2703 return 'usePreparedDeleteBlade() failed in ' . __FUNCTION__;
2704 }
2705
2706 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2707 {
2708 return usePreparedExecuteBlade
2709 (
2710 'UPDATE TagTree SET tag=?, parent_id=? WHERE id=?',
2711 array
2712 (
2713 $tag_name,
2714 $parent_id == 0 ? NULL : $parent_id,
2715 $tag_id,
2716 )
2717 );
2718 }
2719
2720 // Drop the whole chain stored.
2721 function destroyTagsForEntity ($entity_realm, $entity_id)
2722 {
2723 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
2724 }
2725
2726 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2727 // FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2728 // but not now.
2729 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2730 {
2731 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
2732 }
2733
2734 // Push a record into TagStorage unconditionally.
2735 function addTagForEntity ($realm = '', $entity_id, $tag_id)
2736 {
2737 if (!in_array ($realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2738 return FALSE;
2739 return usePreparedInsertBlade
2740 (
2741 'TagStorage',
2742 array
2743 (
2744 'entity_realm' => $realm,
2745 'entity_id' => $entity_id,
2746 'tag_id' => $tag_id,
2747 )
2748 );
2749 }
2750
2751 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2752 // on the implicit list already). Then remove any other records, which
2753 // appear on the "implicit" side of the chain. This will make sure,
2754 // that both the tag base is still minimal and all requested tags appear on
2755 // the resulting tag chain.
2756 // Return TRUE, if any changes were committed.
2757 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2758 {
2759 // Put the current explicit sub-chain into a buffer and merge all tags from
2760 // the extra chain, which aren't there yet.
2761 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2762 foreach ($extrachain as $extratag)
2763 if (!tagOnChain ($extratag, $newchain))
2764 $newchain[] = $extratag;
2765 // Then minimize the working buffer and check if it differs from the original
2766 // chain we started with. If it is so, save the work and signal the upper layer.
2767 $newchain = getExplicitTagsOnly ($newchain);
2768 if (tagChainCmp ($oldchain, $newchain))
2769 {
2770 destroyTagsForEntity ($realm, $entity_id);
2771 foreach ($newchain as $taginfo)
2772 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2773 return TRUE;
2774 }
2775 return FALSE;
2776 }
2777
2778 // Presume, that the target record has no tags attached.
2779 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2780 {
2781 if (!count ($tagidlist))
2782 return '';
2783 if (!$last_insert_id)
2784 $last_insert_id = lastInsertID();
2785 $errcount = 0;
2786 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
2787 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
2788 $errcount++;
2789 if (!$errcount)
2790 return '';
2791 else
2792 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2793 }
2794
2795 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2796 {
2797 // $range is in x.x.x.x/x format, split into ip/mask vars
2798 $rangeArray = explode('/', $range);
2799 if (count ($rangeArray) != 2)
2800 return "Invalid IPv4 prefix '${range}'";
2801 $ip = $rangeArray[0];
2802 $mask = $rangeArray[1];
2803
2804 if (!strlen ($ip) or !strlen ($mask))
2805 return "Invalid IPv4 prefix '${range}'";
2806 $ipL = ip2long($ip);
2807 $maskL = ip2long($mask);
2808 if ($ipL == -1 || $ipL === FALSE)
2809 return 'Bad IPv4 address';
2810 if ($mask < 32 && $mask > 0)
2811 $maskL = $mask;
2812 else
2813 {
2814 $maskB = decbin($maskL);
2815 if (strlen($maskB)!=32)
2816 return 'Invalid netmask';
2817 $ones=0;
2818 $zeroes=FALSE;
2819 foreach( str_split ($maskB) as $digit)
2820 {
2821 if ($digit == '0')
2822 $zeroes = TRUE;
2823 if ($digit == '1')
2824 {
2825 $ones++;
2826 if ($zeroes == TRUE)
2827 return 'Invalid netmask';
2828 }
2829 }
2830 $maskL = $ones;
2831 }
2832 $binmask = binMaskFromDec($maskL);
2833 $ipL = $ipL & $binmask;
2834 $result = usePreparedInsertBlade
2835 (
2836 'IPv4Network',
2837 array
2838 (
2839 'ip' => sprintf ('%u', $ipL),
2840 'mask' => $maskL,
2841 'name' => $name
2842 )
2843 );
2844 if ($result != TRUE)
2845 return "Could not add ${range} (already exists?).";
2846
2847 if ($is_bcast and $maskL < 31)
2848 {
2849 $network_addr = long2ip ($ipL);
2850 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
2851 updateAddress ($network_addr, 'network', 'yes');
2852 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2853 }
2854 return produceTagsForLastRecord ('ipv4net', $taglist);
2855 }
2856
2857 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
2858 function destroyIPv4Prefix ($id = 0)
2859 {
2860 releaseFiles ('ipv4net', $id);
2861 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
2862 return __FUNCTION__ . ': SQL query #1 failed';
2863 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
2864 return __FUNCTION__ . ': SQL query #2 failed';
2865 return '';
2866 }
2867
2868 function loadScript ($name)
2869 {
2870 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
2871 $row = $result->fetch (PDO::FETCH_NUM);
2872 if ($row !== FALSE)
2873 return $row[0];
2874 else
2875 return NULL;
2876 }
2877
2878 function saveScript ($name = '', $text)
2879 {
2880 if (!strlen ($name))
2881 throw new InvalidArgException ('$name', $name);
2882 return usePreparedExecuteBlade
2883 (
2884 'INSERT INTO Script (script_name, script_text) VALUES (?, ?) ' .
2885 'ON DUPLICATE KEY UPDATE script_text=?',
2886 array ($name, $text, $text)
2887 );
2888 }
2889
2890 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2891 {
2892 if (NULL === getIPv4AddressNetworkId ($localip))
2893 return "$localip: Non existant ip";
2894 if (NULL === getIPv4AddressNetworkId ($remoteip))
2895 return "$remoteip: Non existant ip";
2896 if ( ($localport <= 0) or ($localport >= 65536) )
2897 return "$localport: invaild port";
2898 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
2899 return "$remoteport: invaild port";
2900
2901 $result = usePreparedExecuteBlade
2902 (
2903 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
2904 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
2905 array
2906 (
2907 $object_id,
2908 $localip,
2909 $remoteip,
2910 $localport,
2911 $remoteport,
2912 $proto,
2913 $description,
2914 )
2915 );
2916 return $result !== FALSE ? '' : (__FUNCTION__ . '(): failed to insert the rule');
2917 }
2918
2919 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
2920 {
2921 return usePreparedExecuteBlade
2922 (
2923 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
2924 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
2925 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2926 );
2927 }
2928
2929 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2930 {
2931 return usePreparedExecuteBlade
2932 (
2933 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
2934 'AND localport=? AND remoteport=? AND proto=?',
2935 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2936 );
2937 }
2938
2939 function getNATv4ForObject ($object_id)
2940 {
2941 $ret = array();
2942 $ret['out'] = array();
2943 $ret['in'] = array();
2944 $result = usePreparedSelectBlade
2945 (
2946 "select ".
2947 "proto, ".
2948 "INET_NTOA(localip) as localip, ".
2949 "localport, ".
2950 "INET_NTOA(remoteip) as remoteip, ".
2951 "remoteport, ".
2952 "ipa1.name as local_addr_name, " .
2953 "ipa2.name as remote_addr_name, " .
2954 "description ".
2955 "from IPv4NAT ".
2956 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
2957 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
2958 "where object_id=? ".
2959 "order by localip, localport, proto, remoteip, remoteport",
2960 array ($object_id)
2961 );
2962 $count=0;
2963 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2964 {
2965 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
2966 $ret['out'][$count][$cname] = $row[$cname];
2967 $count++;
2968 }
2969 unset ($result);
2970
2971 $result = usePreparedSelectBlade
2972 (
2973 "select ".
2974 "proto, ".
2975 "INET_NTOA(localip) as localip, ".
2976 "localport, ".
2977 "INET_NTOA(remoteip) as remoteip, ".
2978 "remoteport, ".
2979 "IPv4NAT.object_id as object_id, ".
2980 "RackObject.name as object_name, ".
2981 "description ".
2982 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
2983 "where IPv4Allocation.object_id=? ".
2984 "order by remoteip, remoteport, proto, localip, localport",
2985 array ($object_id)
2986 );
2987 $count=0;
2988 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2989 {
2990 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
2991 $ret['in'][$count][$cname] = $row[$cname];
2992 $count++;
2993 }
2994 return $ret;
2995 }
2996
2997 // Return a list of files, which are not linked to the specified record. This list
2998 // will be used by printSelect().
2999 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3000 {
3001 $query = usePreparedSelectBlade
3002 (
3003 'SELECT id, name FROM File ' .
3004 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
3005 'ORDER BY name, id',
3006 array ($entity_type, $entity_id)
3007 );
3008 $ret=array();
3009 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3010 $ret[$row['id']] = $row['name'];
3011 return $ret;
3012 }
3013
3014 // FIXME: return a standard cell list, so upper layer can iterate over
3015 // it conveniently.
3016 function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3017 {
3018 $query = usePreparedSelectBlade
3019 (
3020 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3021 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3022 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3023 array ($entity_type, $entity_id)
3024 );
3025 $ret = array();
3026 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3027 $ret[$row['file_id']] = array (
3028 'id' => $row['file_id'],
3029 'link_id' => $row['link_id'],
3030 'name' => $row['name'],
3031 'type' => $row['type'],
3032 'size' => $row['size'],
3033 'ctime' => $row['ctime'],
3034 'mtime' => $row['mtime'],
3035 'atime' => $row['atime'],
3036 'comment' => $row['comment'],
3037 );
3038 return $ret;
3039 }
3040
3041 function getFile ($file_id = 0)
3042 {
3043 $query = usePreparedSelectBlade
3044 (
3045 'SELECT id, name, type, size, ctime, mtime, atime, contents, comment ' .
3046 'FROM File WHERE id = ?',
3047 array ($file_id)
3048 );
3049 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3050 {
3051 showWarning ('Query succeeded, but returned no data', __FUNCTION__);
3052 $ret = NULL;
3053 }
3054 else
3055 {
3056 $ret = array();
3057 $ret['id'] = $row['id'];
3058 $ret['name'] = $row['name'];
3059 $ret['type'] = $row['type'];
3060 $ret['size'] = $row['size'];
3061 $ret['ctime'] = $row['ctime'];
3062 $ret['mtime'] = $row['mtime'];
3063 $ret['atime'] = $row['atime'];
3064 $ret['contents'] = $row['contents'];
3065 $ret['comment'] = $row['comment'];
3066 $query->closeCursor();
3067
3068 // Someone accessed this file, update atime
3069 usePreparedExecuteBlade ('UPDATE File SET atime = ? WHERE id = ?', array (date ('YmdHis'), $file_id));
3070 }
3071 return $ret;
3072 }
3073
3074 function getFileLinks ($file_id = 0)
3075 {
3076 $query = usePreparedSelectBlade
3077 (
3078 'SELECT id, file_id, entity_type, entity_id FROM FileLink ' .
3079 'WHERE file_id = ? ORDER BY entity_type, entity_id',
3080 array ($file_id)
3081 );
3082 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
3083 $ret = array();
3084 foreach ($rows as $row)
3085 {
3086 // get info of the parent
3087 switch ($row['entity_type'])
3088 {
3089 case 'ipv4net':
3090 $page = 'ipv4net';
3091 $id_name = 'id';
3092 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3093 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3094 break;
3095 case 'ipv4rspool':
3096 $page = 'ipv4rspool';
3097 $id_name = 'pool_id';
3098 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3099 $name = $parent['name'];
3100 break;
3101 case 'ipv4vs':
3102 $page = 'ipv4vs';
3103 $id_name = 'vs_id';
3104 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3105 $name = $parent['name'];
3106 break;
3107 case 'object':
3108 $page = 'object';
3109 $id_name = 'object_id';
3110 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3111 $name = $parent['dname'];
3112 break;
3113 case 'rack':
3114 $page = 'rack';
3115 $id_name = 'rack_id';
3116 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3117 $name = $parent['name'];
3118 break;
3119 case 'user':
3120 $page = 'user';
3121 $id_name = 'user_id';
3122 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3123 $name = $parent['user_name'];
3124 break;
3125 }
3126
3127 // name needs to have some value for hrefs to work
3128 if (!strlen ($name))
3129 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3130
3131 $ret[$row['id']] = array(
3132 'page' => $page,
3133 'id_name' => $id_name,
3134 'entity_type' => $row['entity_type'],
3135 'entity_id' => $row['entity_id'],
3136 'name' => $name
3137 );
3138 }
3139 return $ret;
3140 }
3141
3142 function getFileStats ()
3143 {
3144 $result = usePreparedSelectBlade ('SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type');
3145 $ret = array();
3146 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3147 if ($row['count'] > 0)
3148 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3149 unset ($result);
3150
3151 // Find number of files without any linkage
3152 $result = usePreparedSelectBlade
3153 (
3154 'SELECT COUNT(*) ' .
3155 'FROM File ' .
3156 'WHERE id NOT IN (SELECT file_id FROM FileLink)'
3157 );
3158 $ret["Unattached files"] = $result->fetchColumn ();
3159 unset ($result);
3160
3161 // Find total number of files
3162 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM File');
3163 $ret["Total files"] = $result->fetchColumn ();
3164
3165 return $ret;
3166 }
3167
3168 function commitAddFile ($name, $type, $size, $contents, $comment)
3169 {
3170 $now = date('YmdHis');
3171
3172 global $dbxlink;
3173 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3174 $query->bindParam(1, $name);
3175 $query->bindParam(2, $type);
3176 $query->bindParam(3, $size);
3177 $query->bindParam(4, $now);
3178 $query->bindParam(5, $now);
3179 $query->bindParam(6, $now);
3180 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3181 $query->bindParam(8, $comment);
3182 try
3183 {
3184 return $query->execute();
3185 }
3186 catch (PDOException $e)
3187 {
3188 throw convertPDOException ($e);
3189 }
3190 }
3191
3192 function commitLinkFile ($file_id, $entity_type, $entity_id)
3193 {
3194 return usePreparedExecuteBlade
3195 (
3196 'INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)',
3197 array ($file_id, $entity_type, $entity_id)
3198 );
3199 }
3200
3201 function commitReplaceFile ($file_id = 0, $contents)
3202 {
3203 global $dbxlink;
3204 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3205 $query->bindParam(1, $contents, PDO::PARAM_LOB);
3206 $query->bindParam(2, $file_id);
3207
3208 try
3209 {
3210 return $query->execute();
3211 }
3212 catch (PDOException $e)
3213 {
3214 throw convertPDOException ($e);
3215 }
3216 }
3217
3218 function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
3219 {
3220 if (!strlen ($new_name))
3221 throw new InvalidArgException ('$new_name', $new_name);
3222 if (!strlen ($new_type))
3223 throw new InvalidArgException ('$new_type', $new_type);
3224 return usePreparedExecuteBlade
3225 (
3226 'UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?',
3227 array ($new_name, $new_type, $new_comment, $file_id)
3228 );
3229 }
3230
3231 function commitUnlinkFile ($link_id)
3232 {
3233 if (usePreparedDeleteBlade ('FileLink', array ('id' => $link_id)) === FALSE)
3234 return __FUNCTION__ . '(): query failed';
3235 return '';
3236 }
3237
3238 function commitDeleteFile ($file_id)
3239 {
3240 destroyTagsForEntity ('file', $file_id);
3241 if (usePreparedDeleteBlade ('File', array ('id' => $file_id)) === FALSE)
3242 return __FUNCTION__ . '(): query failed';
3243 return '';
3244 }
3245
3246 function getChapterList ()
3247 {
3248 $ret = array();
3249 $result = usePreparedSelectBlade
3250 (
3251 'SELECT id, sticky, name, count(chapter_id) as wordc ' .
3252 'FROM Chapter LEFT JOIN Dictionary ON Chapter.id = chapter_id ' .
3253 'GROUP BY id ORDER BY name'
3254 );
3255 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3256 $ret[$row['id']] = $row;
3257 return $ret;
3258 }
3259
3260 // Return file id by file name.
3261 function findFileByName ($filename)
3262 {
3263 $query = usePreparedSelectBlade ('SELECT id FROM File WHERE name = ?', array ($filename));
3264 if (($row = $query->fetch (PDO::FETCH_ASSOC)))
3265 return $row['id'];
3266
3267 return NULL;
3268 }
3269
3270 function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3271 {
3272 global $dbxlink;
3273 $dbxlink->beginTransaction();
3274 $result = usePreparedSelectBlade
3275 (
3276 'SELECT TIMESTAMPDIFF(SECOND, first_success, now()) AS success_age, ' .
3277 'TIMESTAMPDIFF(SECOND, last_retry, now()) AS retry_age, displayed_name, memberof ' .
3278 'FROM LDAPCache WHERE presented_username = ? AND successful_hash = ? ' .
3279 'HAVING success_age < ? FOR UPDATE',
3280 array ($form_username, $password_hash, $expiry)
3281 );
3282 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3283 {
3284 $row['memberof'] = unserialize (base64_decode ($row['memberof']));
3285 return $row;
3286 }
3287 return NULL;
3288 }
3289
3290 function releaseLDAPCache ()
3291 {
3292 global $dbxlink;
3293 $dbxlink->commit();
3294 }
3295
3296 // This actually changes only last_retry.
3297 function touchLDAPCacheRecord ($form_username)
3298 {
3299 return usePreparedExecuteBlade ('UPDATE LDAPCache SET last_retry=NOW() WHERE presented_username=?', array ($form_username));
3300 }
3301
3302 function replaceLDAPCacheRecord ($form_username, $password_hash, $dname, $memberof)
3303 {
3304 deleteLDAPCacheRecord ($form_username);
3305 usePreparedInsertBlade ('LDAPCache',
3306 array
3307 (
3308 'presented_username' => $form_username,
3309 'successful_hash' => $password_hash,
3310 'displayed_name' => $dname,
3311 'memberof' => base64_encode (serialize ($memberof)),
3312 )
3313 );
3314 }
3315
3316 function deleteLDAPCacheRecord ($form_username)
3317 {
3318 return usePreparedDeleteBlade ('LDAPCache', array ('presented_username' => $form_username));
3319 }
3320
3321 // Age all records older, than cache_expiry seconds, and all records made in future.
3322 // Calling this function w/o argument purges the whole LDAP cache.
3323 function discardLDAPCache ($maxage = 0)
3324 {
3325 return usePreparedExecuteBlade ('DELETE from LDAPCache WHERE TIMESTAMPDIFF(SECOND, first_success, NOW()) >= ? or NOW() < first_success', array ($maxage));
3326 }
3327
3328 function getUserIDByUsername ($username)
3329 {
3330 $result = usePreparedSelectBlade ('SELECT user_id FROM UserAccount WHeRE user_name = ?', array ($username));
3331 if ($row = $result->fetch (PDO::FETCH_ASSOC))
3332 return $row['user_id'];
3333 return NULL;
3334 }
3335
3336 // Return TRUE, if the given address is assigned to a port of any object
3337 // except the current object. Using this function as a constraint makes
3338 // it possible to reuse L2 addresses within one object, yet keeping them
3339 // universally unique on the other hand.
3340 function alreadyUsedL2Address ($address, $my_object_id)
3341 {
3342 $result = usePreparedSelectBlade
3343 (
3344 'SELECT COUNT(*) FROM Port WHERE BINARY l2address = ? AND object_id != ?',
3345 array ($address, $my_object_id)
3346 );
3347 $row = $result->fetch (PDO::FETCH_NUM);
3348 return $row[0] != 0;
3349 }
3350
3351 function getPortInterfaceCompat()
3352 {
3353 $result = usePreparedSelectBlade
3354 (
3355 'SELECT iif_id, iif_name, oif_id, dict_value AS oif_name ' .
3356 'FROM PortInterfaceCompat INNER JOIN PortInnerInterface ON id = iif_id ' .
3357 'INNER JOIN Dictionary ON dict_key = oif_id ' .
3358 'ORDER BY iif_name, oif_name'
3359 );
3360 return $result->fetchAll (PDO::FETCH_ASSOC);
3361 }
3362
3363 // Return a set of options for a plain SELECT. These options include the current
3364 // OIF of the given port and all OIFs of its permanent IIF.
3365 function getExistingPortTypeOptions ($port_id)
3366 {
3367 $result = usePreparedSelectBlade
3368 (
3369 'SELECT oif_id, dict_value AS oif_name ' .
3370 'FROM PortInterfaceCompat INNER JOIN Dictionary ON oif_id = dict_key ' .
3371 'WHERE iif_id = (SELECT iif_id FROM Port WHERE id = ?) ' .
3372 'ORDER BY oif_name',
3373 array ($port_id)
3374 );
3375 $ret = array();
3376 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3377 $ret[$row['oif_id']] = $row['oif_name'];
3378 return $ret;
3379 }
3380
3381 function getPortIIFOptions()
3382 {
3383 $ret = array();
3384 $result = usePreparedSelectBlade ('SELECT id, iif_name FROM PortInnerInterface ORDER BY iif_name');
3385 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3386 $ret[$row['id']] = $row['iif_name'];
3387 return $ret;
3388 }
3389
3390 function commitSupplementPIC ($iif_id, $oif_id)
3391 {
3392 return usePreparedInsertBlade
3393 (
3394 'PortInterfaceCompat',
3395 array ('iif_id' => $iif_