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