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