4 * This file is a library of database access functions for RackTables.
12 'table' => 'RackObject',
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)',
31 'ordcolumns' => array ('RackObject.name'),
35 'table' => 'UserAccount',
38 'user_id' => 'user_id',
39 'user_name' => 'user_name',
40 'user_password_hash' => 'user_password_hash',
41 'user_realname' => 'user_realname',
43 'keycolumn' => 'user_id',
44 'ordcolumns' => array ('UserAccount.user_name'),
48 'table' => 'IPv4Network',
52 'ip' => 'INET_NTOA(IPv4Network.ip)',
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)',
60 'ordcolumns' => array ('IPv4Network.ip', 'IPv4Network.mask'),
74 'comment' => 'comment',
77 'ordcolumns' => array ('File.name'),
85 'vip' => 'INET_NTOA(vip)',
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)',
95 'ordcolumns' => array ('IPv4VS.vip', 'IPv4VS.proto', 'IPv4VS.vport'),
99 'table' => 'IPv4RSPool',
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',
110 'ordcolumns' => array ('IPv4RSPool.name', 'IPv4RSPool.id'),
119 'height' => 'height',
120 'comment' => 'comment',
121 'row_id' => 'row_id',
122 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
125 'ordcolumns' => array ('row_name', 'Rack.name'),
126 'pidcolumn' => 'row_id',
134 'by_sticker' => 'getStickerSearchResults',
135 'by_port' => 'getPortSearchResults',
136 'by_attr' => 'getObjectAttrsSearchResults',
137 'by_iface' => 'getObjectIfacesSearchResults',
138 'by_nat' => 'getObjectNATSearchResults',
142 $tablemap_8021q = array
146 'pvm' => 'PortVLANMode',
147 'pav' => 'PortAllowedVLAN',
148 'pnv' => 'PortNativeVLAN',
152 'pvm' => 'CachedPVM',
153 'pav' => 'CachedPAV',
154 'pnv' => 'CachedPNV',
158 function escapeString ($value, $do_db_escape = FALSE)
160 $ret = htmlspecialchars ($value, ENT_QUOTES
, 'UTF-8');
164 $ret = substr ($dbxlink->quote ($ret), 1, -1);
169 // Return detailed information about one rack row.
170 function getRackRowInfo ($rackrow_id)
173 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
174 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
175 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
176 "where RackRow.id = ? " .
177 "group by RackRow.id";
178 $result = usePreparedSelectBlade ($query, array ($rackrow_id));
179 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
182 throw new EntityNotFoundException ('rackrow', $rackrow_id);
185 function getRackRows ()
187 $result = usePreparedSelectBlade ('SELECT id, name FROM RackRow ORDER BY name');
189 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
190 $rows[$row['id']] = $row['name'];
194 function commitAddRow($rackrow_name)
196 return usePreparedInsertBlade ('RackRow', array ('name' => $rackrow_name));
199 function commitUpdateRow ($rackrow_id, $rackrow_name)
201 return usePreparedExecuteBlade ('UPDATE RackRow SET name = ? WHERE id = ?', array ($rackrow_name, $rackrow_id));
204 function commitDeleteRow($rackrow_id)
206 return usePreparedDeleteBlade ('RackRow', array ('id' => $rackrow_id));
209 // Return a simple object list w/o related information, so that the returned value
210 // can be directly used by printSelect(). An optional argument is the name of config
211 // option with constraint in RackCode.
212 function getNarrowObjectList ($varname = '')
214 $wideList = listCells ('object');
215 if (strlen ($varname) and strlen (getConfigVar ($varname)))
218 if (!isset ($parseCache[$varname]))
219 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
220 if ($parseCache[$varname]['result'] != 'ACK')
222 $wideList = filterCellList ($wideList, $parseCache[$varname]['load']);
225 foreach ($wideList as $cell)
226 $ret[$cell['id']] = $cell['dname'];
230 // For a given realm return a list of entity records, each with
231 // enough information for judgeCell() to execute.
232 function listCells ($realm, $parent_id = 0)
237 if (isset ($entityCache['complete'][$realm]))
238 return $entityCache['complete'][$realm];
241 if (!isset ($SQLSchema[$realm]))
242 throw new RealmNotFoundException ($realm);
243 $SQLinfo = $SQLSchema[$realm];
244 $qparams = array ($realm);
245 $query = 'SELECT tag_id';
246 foreach ($SQLinfo['columns'] as $alias => $expression)
247 // Automatically prepend table name to each single column, but leave all others intact.
248 $query .= ', ' . ($alias == $expression ?
"${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
249 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
250 if (isset ($SQLinfo['pidcolumn']) and $parent_id)
252 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ?";
253 $qparams[] = $parent_id;
255 $query .= " ORDER BY ";
256 foreach ($SQLinfo['ordcolumns'] as $oc)
259 $result = usePreparedSelectBlade ($query, $qparams);
262 // Index returned result by the value of key column.
263 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
265 $entity_id = $row[$SQLinfo['keycolumn']];
266 // Init the first record anyway, but store tag only if there is one.
267 if (!isset ($ret[$entity_id]))
269 $ret[$entity_id] = array ('realm' => $realm);
270 foreach (array_keys ($SQLinfo['columns']) as $alias)
271 $ret[$entity_id][$alias] = $row[$alias];
272 $ret[$entity_id]['etags'] = array();
273 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
274 $ret[$entity_id]['etags'][] = array
276 'id' => $row['tag_id'],
277 'tag' => $taglist[$row['tag_id']]['tag'],
278 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
281 elseif (isset ($taglist[$row['tag_id']]))
282 // Meeting existing key later is always more tags on existing list.
283 $ret[$entity_id]['etags'][] = array
285 'id' => $row['tag_id'],
286 'tag' => $taglist[$row['tag_id']]['tag'],
287 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
290 // Add necessary finish to the list before returning it. Maintain caches.
292 unset ($entityCache['partial'][$realm]);
293 foreach (array_keys ($ret) as $entity_id)
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]);
301 setDisplayedName ($ret[$entity_id]);
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']));
314 $entityCache['complete'][$realm][$entity_id] = $ret[$entity_id];
316 $entityCache['partial'][$realm][$entity_id] = $ret[$entity_id];
321 // Very much like listCells(), but return only one record requested (or NULL,
322 // if it does not exist).
323 function spotEntity ($realm, $id)
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];
331 throw new EntityNotFoundException ($realm, $id);
332 elseif (isset ($entityCache['partial'][$realm][$id]))
333 return $entityCache['partial'][$realm][$id];
335 if (!isset ($SQLSchema[$realm]))
336 throw new RealmNotFoundException ($realm);
337 $SQLinfo = $SQLSchema[$realm];
338 $query = 'SELECT tag_id';
339 foreach ($SQLinfo['columns'] as $alias => $expression)
340 // Automatically prepend table name to each single column, but leave all others intact.
341 $query .= ', ' . ($alias == $expression ?
"${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
342 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
343 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ?";
344 $query .= " ORDER BY tag_id";
345 $result = usePreparedSelectBlade ($query, array ($realm, $id));
348 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
349 if (!isset ($ret['realm']))
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
358 'id' => $row['tag_id'],
359 'tag' => $taglist[$row['tag_id']]['tag'],
360 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
363 elseif (isset ($taglist[$row['tag_id']]))
364 $ret['etags'][] = array
366 'id' => $row['tag_id'],
367 'tag' => $taglist[$row['tag_id']]['tag'],
368 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
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);
379 setDisplayedName ($ret);
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']));
391 $entityCache['partial'][$realm][$id] = $ret;
395 // This function can be used with array_walk().
396 function amplifyCell (&$record, $dummy = NULL)
398 switch ($record['realm'])
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']);
408 $record['links'] = getFileLinks ($record['id']);
411 $record['lblist'] = array();
412 $query = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
413 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
414 "where rspool_id = ? order by object_id, vip, vport";
415 $result = usePreparedSelectBlade ($query, array ($record['id']));
416 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
417 $record['lblist'][$row['object_id']][$row['vs_id']] = array
419 'rsconfig' => $row['rsconfig'],
420 'vsconfig' => $row['vsconfig'],
423 $record['rslist'] = array();
424 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
425 "IPv4RS where rspool_id = ? order by IPv4RS.rsip, rsport";
426 $result = usePreparedSelectBlade ($query, array ($record['id']));
427 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
428 $record['rslist'][$row['id']] = array
430 'inservice' => $row['inservice'],
431 'rsip' => $row['rsip'],
432 'rsport' => $row['rsport'],
433 'rsconfig' => $row['rsconfig'],
438 // Get the detailed composition of a particular virtual service, namely the list
439 // of all pools, each shown with the list of objects servicing it. VS/RS configs
440 // will be returned as well.
441 $record['rspool'] = array();
442 $query = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
443 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
444 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
445 "where vs_id = ? order by pool.name, object_id";
446 $result = usePreparedSelectBlade ($query, array ($record['id']));
447 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
449 if (!isset ($record['rspool'][$row['id']]))
450 $record['rspool'][$row['id']] = array
452 'name' => $row['name'],
453 'vsconfig' => $row['vsconfig'],
454 'rsconfig' => $row['rsconfig'],
457 if ($row['object_id'] == NULL)
459 $record['rspool'][$row['id']]['lblist'][$row['object_id']] = array
461 'vsconfig' => $row['lb_vsconfig'],
462 'rsconfig' => $row['lb_rsconfig'],
468 $record['mountedObjects'] = array();
469 // start with default rackspace
470 for ($i = $record['height']; $i > 0; $i--)
471 for ($locidx = 0; $locidx < 3; $locidx++
)
472 $record[$i][$locidx]['state'] = 'F';
475 "select unit_no, atom, state, object_id " .
476 "from RackSpace where rack_id = ? and " .
477 "unit_no between 1 and ? order by unit_no";
478 $result = usePreparedSelectBlade ($query, array ($record['id'], $record['height']));
480 $mounted_objects = array();
481 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
483 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
484 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
485 if ($row['state'] == 'T' and $row['object_id'] != NULL)
486 $mounted_objects[$row['object_id']] = TRUE;
488 $record['mountedObjects'] = array_keys ($mounted_objects);
492 $record['8021q'] = getIPv4Network8021QBindings ($record['id']);
498 function getObjectPortsAndLinks ($object_id)
500 $query = "SELECT id, name, label, l2address, iif_id, (SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name, " .
501 "type AS oif_id, (SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, reservation_comment " .
502 "FROM Port WHERE object_id = ?";
503 // list and decode all ports of the current object
504 $result = usePreparedSelectBlade ($query, array ($object_id));
506 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
508 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
509 $row['remote_id'] = NULL;
510 $row['remote_name'] = NULL;
511 $row['remote_object_id'] = NULL;
515 // now find and decode remote ends for all locally terminated connections
516 // FIXME: can't this data be extracted in one pass with sub-queries?
517 foreach (array_keys ($ret) as $tmpkey)
519 $portid = $ret[$tmpkey]['id'];
521 $query = "select porta, portb from Link where porta = ? or portb = ?";
522 $result = usePreparedSelectBlade ($query, array ($portid, $portid));
523 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
525 if ($portid != $row['porta'])
526 $remote_id = $row['porta'];
527 elseif ($portid != $row['portb'])
528 $remote_id = $row['portb'];
531 if ($remote_id) // there's a remote end here
533 $query = "SELECT name, object_id FROM Port WHERE id = ?";
534 $result = usePreparedSelectBlade ($query, array ($remote_id));
535 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
537 $ret[$tmpkey]['remote_name'] = $row['name'];
538 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
540 $ret[$tmpkey]['remote_id'] = $remote_id;
544 usort ($ret, 'sortByName');
548 function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
550 if ($row_id <= 0 or $height <= 0 or !strlen ($name))
552 $result = usePreparedInsertBlade
560 'comment' => $comment
563 $last_insert_id = lastInsertID();
564 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', $last_insert_id);
567 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
569 // Maintain UNIQUE INDEX for common names and asset tags by
570 // filtering out empty strings (not NULLs).
571 $result1 = usePreparedInsertBlade
576 'name' => !strlen ($new_name) ?
NULL : $new_name,
577 'label' => $new_label,
578 'barcode' => !strlen ($new_barcode) ?
NULL : $new_barcode,
579 'objtype_id' => $new_type_id,
580 'asset_no' => !strlen ($new_asset_no) ?
NULL : $new_asset_no,
583 $last_insert_id = lastInsertID();
584 // Do AutoPorts magic
585 executeAutoPorts ($last_insert_id, $new_type_id);
587 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
589 recordHistory ('RackObject', $last_insert_id);
591 return $last_insert_id;
594 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
596 if ($new_type_id == 0)
597 throw new InvalidArgException ('$new_type_id', $new_type_id);
598 $ret = FALSE !== usePreparedExecuteBlade
600 'UPDATE RackObject SET name=?, label=?, barcode=?, objtype_id=?, has_problems=?, ' .
601 'asset_no=?, comment=? WHERE id=?',
604 !strlen ($new_name) ?
NULL : $new_name,
606 !strlen ($new_barcode) ?
NULL : $new_barcode,
609 !strlen ($new_asset_no) ?
NULL : $new_asset_no,
614 return $ret and recordHistory ('RackObject', $object_id);
617 // Remove file links related to the entity, but leave the entity and file(s) intact.
618 function releaseFiles ($entity_realm, $entity_id)
620 usePreparedDeleteBlade ('FileLink', array ('entity_type' => $entity_realm, 'entity_id' => $entity_id));
623 // There are times when you want to delete all traces of an object
624 function commitDeleteObject ($object_id = 0)
626 releaseFiles ('object', $object_id);
627 destroyTagsForEntity ('object', $object_id);
628 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
629 usePreparedDeleteBlade ('IPv4Allocation', array ('object_id' => $object_id));
630 usePreparedDeleteBlade ('IPv4NAT', array ('object_id' => $object_id));
631 usePreparedExecuteBlade ('DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
632 usePreparedExecuteBlade ('DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
633 usePreparedDeleteBlade ('RackObject', array ('id' => $object_id));
637 function commitDeleteRack($rack_id)
639 releaseFiles ('rack', $rack_id);
640 destroyTagsForEntity ('rack', $rack_id);
641 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
642 usePreparedDeleteBlade ('RackHistory', array ('id' => $rack_id));
643 usePreparedDeleteBlade ('Rack', array ('id' => $rack_id));
647 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
649 // Can't shrink a rack if rows being deleted contain mounted objects
650 $check_result = usePreparedSelectBlade ('SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = ? AND unit_no > ?', array ($rack_id, $new_height));
651 $check_row = $check_result->fetch (PDO
::FETCH_ASSOC
);
652 unset ($check_result);
653 if ($check_row['count'] > 0)
654 throw new InvalidArgException ('new_height', $new_height, 'Cannot shrink rack, objects are still mounted there');
656 usePreparedExecuteBlade
658 'UPDATE Rack SET name=?, height=?, comment=?, row_id=? WHERE id=?',
668 return recordHistory ('Rack', $rack_id);
671 // This function accepts rack data returned by amplifyCell(), validates and applies changes
672 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
673 // correspond to current rack ID.
674 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
675 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
676 // The function returns the modified rack upon success.
677 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
680 $rack_id = $rackData['id'];
681 $rack_name = $rackData['name'];
682 $rackchanged = FALSE;
683 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
685 for ($locidx = 0; $locidx < 3; $locidx++
)
687 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
690 $state = $rackData[$unit_no][$locidx]['state'];
691 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
692 $newstate = $checked_state;
694 $newstate = $unchecked_state;
695 if ($state == $newstate)
699 $atom = $loclist[$locidx];
700 // The only changes allowed are those introduced by checkbox grid.
703 !($state == $checked_state && $newstate == $unchecked_state) &&
704 !($state == $unchecked_state && $newstate == $checked_state)
706 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
707 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
708 // anyway and then looking for probable need of INSERT.
709 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom));
710 if ($newstate != 'F')
711 usePreparedInsertBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom, 'state' => $newstate));
712 if ($newstate == 'T' and $object_id != 0)
714 // At this point we already have a record in RackSpace.
715 $r = usePreparedExecuteBlade
717 'UPDATE RackSpace SET object_id=? ' .
718 'WHERE rack_id=? AND unit_no=? AND atom=?',
719 array ($object_id, $rack_id, $unit_no, $atom)
722 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
723 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
729 resetThumbCache ($rack_id);
730 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
733 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
736 // This function builds a list of rack-unit-atom records, which are assigned to
737 // the requested object.
738 function getMoleculeForObject ($object_id)
740 $result = usePreparedSelectBlade
742 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
743 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
746 return $result->fetchAll (PDO
::FETCH_ASSOC
);
749 // This function builds a list of rack-unit-atom records for requested molecule.
750 function getMolecule ($mid = 0)
752 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
753 return $result->fetchAll (PDO
::FETCH_ASSOC
);
756 // returns exactly what is's named after
757 function lastInsertID ()
759 $result = usePreparedSelectBlade ('select last_insert_id()');
760 $row = $result->fetch (PDO
::FETCH_NUM
);
764 // This function creates a new record in Molecule and number of linked
765 // R-U-A records in Atom.
766 function createMolecule ($molData)
768 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
769 $molecule_id = lastInsertID();
770 foreach ($molData as $rua)
771 usePreparedInsertBlade
776 'molecule_id' => $molecule_id,
777 'rack_id' => $rua['rack_id'],
778 'unit_no' => $rua['unit_no'],
779 'atom' => $rua['atom'],
785 // History logger. This function assumes certain table naming convention and
787 // 1. History table name equals to dictionary table name plus 'History'.
788 // 2. History table must have the same row set (w/o keys) plus one row named
789 // 'ctime' of type 'timestamp'.
790 function recordHistory ($tableName, $orig_id)
792 global $remote_username;
793 return FALSE !== usePreparedExecuteBlade
795 "INSERT INTO ${tableName}History SELECT *, CURRENT_TIMESTAMP(), ? " .
796 "FROM ${tableName} WHERE id=?",
797 array ($remote_username, $orig_id)
801 function getRackspaceHistory ()
803 $result = usePreparedSelectBlade
805 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
806 "MountOperation ORDER BY ctime DESC"
808 return $result->fetchAll (PDO
::FETCH_ASSOC
);
811 // This function is used in renderRackspaceHistory()
812 function getOperationMolecules ($op_id = 0)
814 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
815 // We expect one row.
816 $row = $result->fetch (PDO
::FETCH_ASSOC
);
817 return array ($row['old_molecule_id'], $row['new_molecule_id']);
820 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
822 $result = usePreparedSelectBlade ('SELECT DISTINCT rack_id FROM RackSpace WHERE object_id = ? ORDER BY rack_id', array ($object_id));
823 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
826 foreach ($rows as $row)
828 if (!$fetch_rackdata)
830 $ret[$row[0]] = $row[0];
833 $rackData = spotEntity ('rack', $row[0]);
834 amplifyCell ($rackData);
835 $ret[$row[0]] = $rackData;
840 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
842 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
843 return "Invalid L2 address ${port_l2address}";
845 $dbxlink->exec ('LOCK TABLES Port WRITE');
846 if (alreadyUsedL2Address ($db_l2address, $object_id))
848 $dbxlink->exec ('UNLOCK TABLES');
849 return "address ${db_l2address} belongs to another object";
854 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
855 $iif_id = $matches[1];
856 $oif_id = $matches[2];
858 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
860 $oif_id = $matches[1];
863 $dbxlink->exec ('UNLOCK TABLES');
864 return "invalid port type id '${port_type_id}'";
866 $result = usePreparedInsertBlade
871 'name' => $port_name,
872 'object_id' => $object_id,
873 'label' => $port_label,
876 'l2address' => ($db_l2address === '') ?
NULL : $db_l2address,
879 $dbxlink->exec ('UNLOCK TABLES');
883 return 'SQL query failed';
886 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
887 // string value. In case it is omitted, we just assign it its current value.
888 // It would be nice to simplify this semantics later.
889 function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment)
891 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
892 return "Invalid L2 address ${port_l2address}";
894 $dbxlink->exec ('LOCK TABLES Port WRITE');
895 if (alreadyUsedL2Address ($db_l2address, $object_id))
897 $dbxlink->exec ('UNLOCK TABLES');
898 return "address ${db_l2address} belongs to another object";
900 $result = usePreparedExecuteBlade
902 'UPDATE Port SET name=?, type=?, label=?, reservation_comment=?, ' .
903 'l2address=? WHERE id=? AND object_id=?',
909 mb_strlen ($port_reservation_comment) ?
$port_reservation_comment : NULL,
910 ($db_l2address === '') ?
NULL : $db_l2address,
915 $dbxlink->exec ('UNLOCK TABLES');
918 $errorInfo = $dbxlink->errorInfo();
919 // We could update nothing.
920 if ($errorInfo[0] == '00000')
922 return $errorInfo[2];
925 function delObjectPort ($port_id)
927 if (usePreparedDeleteBlade ('Port', array ('id' => $port_id)) != TRUE)
928 return __FUNCTION__
. ': usePreparedDeleteBlade() failed';
932 function getAllIPv4Allocations ()
934 $result = usePreparedSelectBlade
936 "select object_id as object_id, ".
937 "RackObject.name as object_name, ".
938 "IPv4Allocation.name as name, ".
939 "INET_NTOA(ip) as ip ".
940 "from IPv4Allocation join RackObject on id=object_id "
943 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
948 function linkPorts ($porta, $portb)
950 if ($porta == $portb)
951 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
958 $ret = FALSE !== usePreparedInsertBlade ('Link', array ('porta' => $porta, 'portb' => $portb));
959 $ret = $ret and FALSE !== usePreparedExecuteBlade
961 'UPDATE Port SET reservation_comment=NULL WHERE id IN(?, ?)',
962 array ($porta, $portb)
964 return $ret ?
'' : 'query failed';
967 function unlinkPort ($port_id)
969 usePreparedDeleteBlade ('Link', array ('porta' => $port_id, 'portb' => $port_id), 'OR');
973 // Return all IPv4 addresses allocated to the objects. Attach detailed
974 // info about address to each alocation records. Index result by dotted-quad
976 function getObjectIPv4Allocations ($object_id = 0)
979 $result = usePreparedSelectBlade
981 'SELECT name AS osif, type, inet_ntoa(ip) AS dottedquad FROM IPv4Allocation ' .
982 'WHERE object_id = ? ORDER BY ip',
985 // don't spawn a sub-query with unfetched buffer, it may fail
986 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
987 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
989 foreach (array_keys ($ret) as $dottedquad)
990 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
994 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
995 function constructIPv4Address ($dottedquad = NULL)
1003 'rslist' => array(),
1004 'allocs' => array(),
1007 if ($dottedquad != NULL)
1008 $ret['ip'] = $dottedquad;
1012 // Check the range requested for meaningful IPv4 records, build them
1013 // into a list and return. Return an empty list if nothing matched.
1014 // Both arguments are expected in signed int32 form. The resulting list
1015 // is keyed by uint32 form of each IP address, items aren't sorted.
1016 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
1017 function scanIPv4Space ($pairlist)
1020 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
1022 // FIXME: this is a copy-and-paste prototype
1031 foreach ($pairlist as $tmp)
1033 $db_first = sprintf ('%u', 0x00000000 +
$tmp['i32_first']);
1034 $db_last = sprintf ('%u', 0x00000000 +
$tmp['i32_last']);
1035 $whereexpr1 .= $or . "ip between ? and ?";
1036 $whereexpr2 .= $or . "ip between ? and ?";
1037 $whereexpr3 .= $or . "vip between ? and ?";
1038 $whereexpr4 .= $or . "rsip between ? and ?";
1039 $whereexpr5a .= $or . "remoteip between ? and ?";
1040 $whereexpr5b .= $or . "localip between ? and ?";
1042 $qparams[] = $db_first;
1043 $qparams[] = $db_last;
1049 $whereexpr5a .= ')';
1050 $whereexpr5b .= ')';
1052 // 1. collect labels and reservations
1053 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
1054 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1055 $result = usePreparedSelectBlade ($query, $qparams);
1056 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1058 $ip_bin = ip2long ($row['ip']);
1059 if (!isset ($ret[$ip_bin]))
1060 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1061 $ret[$ip_bin]['name'] = $row['name'];
1062 $ret[$ip_bin]['reserved'] = $row['reserved'];
1066 // 2. check for allocations
1068 "select INET_NTOA(ip) as ip, object_id, name, type " .
1069 "from IPv4Allocation where ${whereexpr2} order by type";
1070 $result = usePreparedSelectBlade ($query, $qparams);
1071 // release DBX early to avoid issues with nested spotEntity() calls
1072 $allRows = $result->fetchAll (PDO
::FETCH_ASSOC
);
1074 foreach ($allRows as $row)
1076 $ip_bin = ip2long ($row['ip']);
1077 if (!isset ($ret[$ip_bin]))
1078 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1079 $oinfo = spotEntity ('object', $row['object_id']);
1080 $ret[$ip_bin]['allocs'][] = array
1082 'type' => $row['type'],
1083 'name' => $row['name'],
1084 'object_id' => $row['object_id'],
1085 'object_name' => $oinfo['dname'],
1089 // 3. look for virtual services and related LB
1090 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, object_id " .
1091 "from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1092 "where ${whereexpr3} order by vport, proto, object_id";
1093 $result = usePreparedSelectBlade ($query, $qparams);
1094 $allRows = $result->fetchAll (PDO
::FETCH_ASSOC
);
1096 foreach ($allRows as $row)
1098 $ip_bin = ip2long ($row['ip']);
1099 if (!isset ($ret[$ip_bin]))
1100 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1101 $oinfo = spotEntity ('object', $row['object_id']);
1102 $ret[$ip_bin]['lblist'][] = array
1104 'vport' => $row['vport'],
1105 'proto' => $row['proto'],
1106 'vs_id' => $row['vs_id'],
1107 'name' => $row['name'],
1108 'vip' => $row['ip'],
1109 'object_id' => $row['object_id'],
1110 'object_name' => $oinfo['dname'],
1114 // 4. don't forget about real servers along with pools
1115 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1116 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
1117 "where ${whereexpr4} " .
1118 "order by ip, rsport, rspool_id";
1119 $result = usePreparedSelectBlade ($query, $qparams);
1120 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1122 $ip_bin = ip2long ($row['ip']);
1123 if (!isset ($ret[$ip_bin]))
1124 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1126 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1127 $tmp[$cname] = $row[$cname];
1128 $ret[$ip_bin]['rslist'][] = $tmp;
1132 // 5. add NAT rules, part 1
1136 "INET_NTOA(localip) as localip, " .
1138 "INET_NTOA(remoteip) as remoteip, " .
1142 "where ${whereexpr5a} " .
1143 "order by localip, localport, remoteip, remoteport, proto";
1144 $result = usePreparedSelectBlade ($query, $qparams);
1145 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1147 $remoteip_bin = ip2long ($row['remoteip']);
1148 if (!isset ($ret[$remoteip_bin]))
1149 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1150 $ret[$remoteip_bin]['inpf'][] = $row;
1153 // 5. add NAT rules, part 2
1157 "INET_NTOA(localip) as localip, " .
1159 "INET_NTOA(remoteip) as remoteip, " .
1163 "where ${whereexpr5b} " .
1164 "order by localip, localport, remoteip, remoteport, proto";
1165 $result = usePreparedSelectBlade ($query, $qparams);
1166 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1168 $localip_bin = ip2long ($row['localip']);
1169 if (!isset ($ret[$localip_bin]))
1170 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1171 $ret[$localip_bin]['outpf'][] = $row;
1177 function getIPv4Address ($dottedquad = '')
1179 if ($dottedquad == '')
1180 throw new InvalidArgException ('$dottedquad', $dottedquad);
1181 $i32 = ip2long ($dottedquad); // signed 32 bit
1182 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1183 if (!isset ($scanres[$i32]))
1184 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1185 return constructIPv4Address ($dottedquad);
1186 markupIPv4AddrList ($scanres);
1187 return $scanres[$i32];
1190 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1192 $result = usePreparedExecuteBlade
1194 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1195 array ($ip, $object_id, $name, $type)
1197 return $result ?
'' : (__FUNCTION__
. '(): query failed');
1200 // Return the id of the smallest IPv4 network containing the given IPv4 address
1201 // or NULL, if nothing was found. When finding the covering network for
1202 // another network, it is important to filter out matched records with longer
1203 // masks (they aren't going to be the right pick).
1204 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1206 // N.B. To perform the same for IPv6 address and networks, some pre-requisites
1207 // are necessary and a different query. IPv6 addresses are 128 bit long, which
1208 // is too much for both PHP and MySQL data types. These values must be split
1209 // into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1210 // Then each network must have its 128-bit netmask split same way and either
1211 // stored right in its record or JOINed from decoder and accessible as m_u32_0,
1212 // m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1213 // covering the given address would look as follows:
1214 // $query = 'select id from IPv6Network as n where ' .
1215 // "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1216 // "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1217 // "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1218 // "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1219 // "mask < ${masklen} " .
1220 // 'order by mask desc limit 1';
1222 $query = 'select id from IPv4Network where ' .
1223 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1225 'order by mask desc limit 1';
1226 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
1227 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1232 function updateIPv4Network_real ($id = 0, $name = '', $comment = '')
1234 return usePreparedExecuteBlade ('UPDATE IPv4Network SET name = ?, comment = ? WHERE id = ?', array ($name, $comment, $id));
1237 // This function is actually used not only to update, but also to create records,
1238 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1239 // (MySQL 4.0 workaround).
1240 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1242 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
1243 // INSERT may appear not necessary.
1244 if ($name == '' and $reserved == 'no')
1246 $ret = usePreparedExecuteBlade
1248 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1249 array ($name, $reserved, $ip)
1251 return $ret !== FALSE ?
'' : (__FUNCTION__
. 'query failed');
1254 function updateBond ($ip='', $object_id=0, $name='', $type='')
1256 return usePreparedExecuteBlade
1258 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1259 array ($name, $type, $ip, $object_id)
1263 function unbindIpFromObject ($ip='', $object_id=0)
1265 return usePreparedExecuteBlade
1267 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1268 array ($ip, $object_id)
1272 function getIPv4PrefixSearchResult ($terms)
1274 $byname = getSearchResultByField
1283 foreach ($byname as $row)
1284 $ret[] = spotEntity ('ipv4net', $row['id']);
1288 function getIPv4AddressSearchResult ($terms)
1290 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1293 foreach (explode (' ', $terms) as $term)
1295 $query .= $or . "name like ?";
1297 $qparams[] = "%${term}%";
1299 $result = usePreparedSelectBlade ($query, $qparams);
1301 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1306 function getIPv4RSPoolSearchResult ($terms)
1308 $byname = getSearchResultByField
1317 foreach ($byname as $row)
1318 $ret[] = spotEntity ('ipv4rspool', $row['id']);
1322 function getIPv4VServiceSearchResult ($terms)
1324 $byname = getSearchResultByField
1333 foreach ($byname as $row)
1334 $ret[] = spotEntity ('ipv4vs', $row['id']);
1338 function getAccountSearchResult ($terms)
1340 $byUsername = getSearchResultByField
1343 array ('user_id', 'user_name', 'user_realname'),
1348 $byRealname = getSearchResultByField
1351 array ('user_id', 'user_name', 'user_realname'),
1356 // Filter out dupes.
1357 foreach ($byUsername as $res1)
1358 foreach (array_keys ($byRealname) as $key2)
1359 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1361 unset ($byRealname[$key2]);
1364 $ret = array_merge ($byUsername, $byRealname);
1365 // Set realm, so it's renderable.
1366 foreach (array_keys ($ret) as $key)
1367 $ret[$key]['realm'] = 'user';
1371 function getFileSearchResult ($terms)
1373 $byName = getSearchResultByField
1381 $byComment = getSearchResultByField
1389 // Filter out dupes.
1390 foreach ($byName as $res1)
1391 foreach (array_keys ($byComment) as $key2)
1392 if ($res1['id'] == $byComment[$key2]['id'])
1394 unset ($byComment[$key2]);
1398 foreach (array_merge ($byName, $byComment) as $row)
1399 $ret[] = spotEntity ('file', $row['id']);
1403 function getRackSearchResult ($terms)
1405 $byName = getSearchResultByField
1413 $byComment = getSearchResultByField
1421 // Filter out dupes.
1422 foreach ($byName as $res1)
1423 foreach (array_keys ($byComment) as $key2)
1424 if ($res1['id'] == $byComment[$key2]['id'])
1426 unset ($byComment[$key2]);
1430 foreach (array_merge ($byName, $byComment) as $row)
1431 $ret[] = spotEntity ('rack', $row['id']);
1435 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
1440 foreach ($rcolumns as $col)
1442 $query .= $pfx . $col;
1446 $query .= " from ${tname} where ";
1447 foreach (explode (' ', $terms) as $term)
1451 case 2: // does this work as expected?
1452 $query .= $pfx . "binary ${scolumn} = ?";
1456 $query .= $pfx . "${scolumn} = ?";
1460 $query .= $pfx . "${scolumn} like ?";
1461 $qparams[] = "%${term}%";
1467 $query .= " order by ${ocolumn}";
1468 $result = usePreparedSelectBlade ($query, $qparams);
1470 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1475 function getObjectSearchResults ($what)
1479 foreach ($searchfunc['object'] as $method => $func)
1480 foreach ($func ($what) as $objRecord)
1482 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1483 $ret[$objRecord['id']][$method] = $objRecord[$method];
1488 function getObjectAttrsSearchResults ($what)
1491 foreach (array ('name', 'label', 'asset_no', 'barcode') as $column)
1493 $tmp = getSearchResultByField
1501 foreach ($tmp as $row)
1503 $ret[$row['id']]['id'] = $row['id'];
1504 $ret[$row['id']]['by_attr'][] = $column;
1510 // Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1511 // which matched. A partilar object_id could be returned more, than once, if it has
1512 // multiple matching stickers. Search is only performed on "string" attributes.
1513 function getStickerSearchResults ($what, $exactness = 0)
1515 $stickers = getSearchResultByField
1518 array ('object_id', 'attr_id'),
1524 $map = getAttrMap();
1526 foreach ($stickers as $sticker)
1527 if ($map[$sticker['attr_id']]['type'] == 'string')
1529 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
1530 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
1535 // search in port "reservation comment", "label" and "L2 address" columns
1536 function getPortSearchResults ($what)
1539 $ports = getSearchResultByField
1542 array ('object_id', 'id', 'reservation_comment'),
1543 'reservation_comment',
1548 foreach ($ports as $port)
1550 $ret[$port['object_id']]['id'] = $port['object_id'];
1551 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
1553 $ports = getSearchResultByField
1556 array ('object_id', 'id', 'label'),
1562 foreach ($ports as $port)
1564 $ret[$port['object_id']]['id'] = $port['object_id'];
1565 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
1567 if (NULL === ($db_l2address = l2addressForDatabase ($what)))
1569 $ports = getSearchResultByField
1572 array ('object_id', 'id', 'l2address'),
1578 foreach ($ports as $port)
1580 $ret[$port['object_id']]['id'] = $port['object_id'];
1581 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
1586 // search in IPv4 allocations
1587 function getObjectIfacesSearchResults ($what)
1590 $ifaces = getSearchResultByField
1593 array ('object_id', 'name'),
1598 foreach ($ifaces as $row)
1600 $ret[$row['object_id']]['id'] = $row['object_id'];
1601 $ret[$row['object_id']]['by_iface'][] = $row['name'];
1606 function getObjectNATSearchResults ($what)
1609 $ifaces = getSearchResultByField
1612 array ('object_id', 'description'),
1617 foreach ($ifaces as $row)
1619 $ret[$row['object_id']]['id'] = $row['object_id'];
1620 $ret[$row['object_id']]['by_nat'][] = $row['description'];
1625 // This function returns either port ID or NULL for specified arguments.
1626 function getPortIDs ($object_id, $port_name)
1629 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
1630 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1631 $ret[] = $row['id'];
1635 // Search in "FQDN" attribute only, and return object ID, when there is exactly
1636 // one result found (and NULL in any other case).
1637 function searchByMgmtHostname ($string)
1639 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
1640 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
1641 if (count ($rows) != 1)
1646 function commitCreateUserAccount ($username, $realname, $password)
1648 return usePreparedInsertBlade
1653 'user_name' => $username,
1654 'user_realname' => $realname,
1655 'user_password_hash' => $password,
1660 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1662 return usePreparedExecuteBlade
1664 'UPDATE UserAccount SET user_name=?, user_realname=?, user_password_hash=? ' .
1666 array ($new_username, $new_realname, $new_password, $id)
1670 // This function returns an array of all port type pairs from PortCompat table.
1671 function getPortOIFCompat ()
1674 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1675 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1676 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1677 'ORDER BY type1name, type2name';
1678 $result = usePreparedSelectBlade ($query);
1679 return $result->fetchAll (PDO
::FETCH_ASSOC
);
1682 // Add a pair to the PortCompat table.
1683 function commitSupplementPOIFC ($type1, $type2)
1686 throw new InvalidArgException ('type1', $type1);
1688 throw new InvalidArgException ('type2', $type2);
1689 return usePreparedInsertBlade
1692 array ('type1' => $type1, 'type2' => $type2)
1696 // Remove a pair from the PortCompat table.
1697 function commitReducePOIFC ($type1, $type2)
1699 return usePreparedDeleteBlade ('PortCompat', array ('type1' => $type1, 'type2' => $type2));
1702 function getDictStats ()
1704 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28);
1705 $result = usePreparedSelectBlade
1707 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
1708 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
1710 $tc = $tw = $uc = $uw = 0;
1711 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1715 if (in_array ($row['chapter_no'], $stock_chapters))
1720 $result->closeCursor();
1722 $result = usePreparedSelectBlade
1724 "select count(object_id) as attrc from RackObject as ro left join " .
1725 "AttributeValue as av on ro.id = av.object_id group by ro.id"
1727 $to = $ta = $so = 0;
1728 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1731 if ($row['attrc'] != 0)
1734 $ta +
= $row['attrc'];
1737 $result->closeCursor();
1739 $ret['Total chapters in dictionary'] = $tc;
1740 $ret['Total words in dictionary'] = $tw;
1741 $ret['User chapters'] = $uc;
1742 $ret['Words in user chapters'] = $uw;
1743 $ret['Total objects'] = $to;
1744 $ret['Objects with stickers'] = $so;
1745 $ret['Total stickers attached'] = $ta;
1749 function getIPv4Stats ()
1753 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1754 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1755 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1756 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1757 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1758 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1759 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1760 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
1762 foreach ($subject as $item)
1764 $result = usePreparedSelectBlade ($item['q']);
1765 $row = $result->fetch (PDO
::FETCH_NUM
);
1766 $ret[$item['txt']] = $row[0];
1767 $result->closeCursor();
1773 function getRackspaceStats ()
1777 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
1778 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1779 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1780 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1782 foreach ($subject as $item)
1784 $result = usePreparedSelectBlade ($item['q']);
1785 $row = $result->fetch (PDO
::FETCH_NUM
);
1786 $ret[$item['txt']] = !strlen ($row[0]) ?
0 : $row[0];
1787 $result->closeCursor();
1795 The following allows figuring out records in TagStorage, which refer to non-existing entities:
1797 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1798 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1799 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1800 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1801 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1802 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1803 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
1805 Accordingly, these are the records, which refer to non-existent tags:
1807 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1811 // chapter_no is a must, see at @commitReduceDictionary() why
1812 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1814 return usePreparedExecuteBlade
1816 'UPDATE Dictionary SET dict_value=? WHERE chapter_id=? AND dict_key=?',
1817 array ($dict_value, $chapter_no, $dict_key)
1821 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1823 if ($chapter_no <= 0)
1824 throw new InvalidArgException ('$chapter_no', $chapter_no);
1825 if (!strlen ($dict_value))
1826 throw new InvalidArgException ('$dict_value', $dict_value);
1827 return usePreparedInsertBlade
1830 array ('chapter_id' => $chapter_no, 'dict_value' => $dict_value)
1834 // Technically dict_key is enough to delete, but including chapter_id into
1835 // WHERE clause makes sure, that the action actually happends for the same
1836 // chapter, which authorization was granted for.
1837 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1839 return usePreparedDeleteBlade ('Dictionary', array ('chapter_id' => $chapter_no, 'dict_key' => $dict_key));
1842 function commitAddChapter ($chapter_name = '')
1844 if (!strlen ($chapter_name))
1845 throw new InvalidArgException ('$chapter_name', $chapter_name);
1846 return usePreparedInsertBlade
1849 array ('name' => $chapter_name)
1853 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1855 if (!strlen ($chapter_name))
1856 throw new InvalidArgException ('$chapter_name', $chapter_name);
1857 return usePreparedExecuteBlade
1859 'UPDATE Chapter SET name=? WHERE id=? AND sticky="no"',
1860 array ($chapter_name, $chapter_no)
1864 function commitDeleteChapter ($chapter_no = 0)
1866 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
1869 // This is a dictionary accessor. We perform link rendering, so the user sees
1870 // nice <select> drop-downs.
1871 function readChapter ($chapter_id = 0, $style = '')
1873 $result = usePreparedSelectBlade
1875 "select dict_key, dict_value from Dictionary " .
1876 "where chapter_id = ?",
1880 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1881 $chapter[$row['dict_key']] = $style == '' ?
$row['dict_value'] : parseWikiLink ($row['dict_value'], $style);
1882 $result->closeCursor();
1883 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1888 // Return refcounters for all given keys of the given chapter.
1889 function getChapterRefc ($chapter_id, $keylist)
1892 foreach ($keylist as $key)
1894 switch ($chapter_id)
1897 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
1898 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
1899 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
1902 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
1903 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
1904 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
1905 "from Dictionary where chapter_id = ?";
1908 // Find the list of all assigned values of dictionary-addressed attributes, each with
1909 // chapter/word keyed reference counters.
1910 $query = "select uint_value, count(object_id) as refcnt " .
1911 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1912 "inner join AttributeValue as av on a.id = av.attr_id " .
1913 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
1914 "where a.type = 'dict' and am.chapter_id = ? group by uint_value";
1917 $result = usePreparedSelectBlade ($query, array ($chapter_id));
1918 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1919 $ret[$row['uint_value']] = $row['refcnt'];
1923 // Return a list of all stickers with sticker map applied. Each sticker records will
1924 // list all its ways on the map with refcnt set.
1925 function getAttrMap ()
1927 $result = usePreparedSelectBlade
1929 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
1930 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
1931 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
1932 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
1933 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
1936 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1938 if (!isset ($ret[$row['id']]))
1939 $ret[$row['id']] = array
1942 'type' => $row['type'],
1943 'name' => $row['name'],
1944 'application' => array(),
1946 if ($row['objtype_id'] == '')
1948 $application = array
1950 'objtype_id' => $row['objtype_id'],
1951 'refcnt' => $row['refcnt'],
1953 if ($row['type'] == 'dict')
1955 $application['chapter_no'] = $row['chapter_id'];
1956 $application['chapter_name'] = $row['chapter_name'];
1958 $ret[$row['id']]['application'][] = $application;
1963 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1965 return usePreparedExecuteBlade ('UPDATE Attribute SET name=? WHERE id=?', array ($attr_name, $attr_id));
1968 function commitAddAttribute ($attr_name = '', $attr_type = '')
1970 if (!strlen ($attr_name))
1971 throw new InvalidArgException ('$attr_name', $attr_name);
1980 throw new InvalidArgException ('$attr_type', $attr_type, 'Attribute type not supported');
1982 return usePreparedInsertBlade
1985 array ('name' => $attr_name, 'type' => $attr_type)
1989 function commitDeleteAttribute ($attr_id = 0)
1991 return usePreparedDeleteBlade ('Attribute', array ('id' => $attr_id));
1994 // FIXME: don't store garbage in chapter_no for non-dictionary types.
1995 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1998 throw new InvalidArgException ('$attr_id', $attr_id);
1999 if ($objtype_id <= 0)
2000 throw new InvalidArgException ('$objtype_id', $objtype_id);
2002 return usePreparedInsertBlade
2007 'attr_id' => $attr_id,
2008 'objtype_id' => $objtype_id,
2009 'chapter_id' => $chapter_no
2014 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2016 return usePreparedDeleteBlade ('AttributeMap', array ('attr_id' => $attr_id, 'objtype_id' => $objtype_id));
2019 // This function returns all optional attributes for requested object
2020 // as an array of records. NULL is returned on error and empty array
2021 // is returned, if there are no attributes found.
2022 function getAttrValues ($object_id)
2025 $result = usePreparedSelectBlade
2027 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2028 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2029 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2030 "inner join Attribute as A on AM.attr_id = A.id " .
2031 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2032 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2033 "left join Chapter as C on AM.chapter_id = C.id " .
2034 "where RO.id = ? order by A.name, A.type",
2037 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2040 $record['id'] = $row['attr_id'];
2041 $record['name'] = $row['attr_name'];
2042 $record['type'] = $row['attr_type'];
2043 switch ($row['attr_type'])
2046 $record['chapter_id'] = $row['chapter_id'];
2047 $record['chapter_name'] = $row['chapter_name'];
2048 $record['key'] = $row['uint_value'];
2053 $record['value'] = $row[$row['attr_type'] . '_value'];
2054 $record['o_value'] = parseWikiLink ($record['value'], 'o');
2055 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2058 $record['value'] = NULL;
2061 $ret[$row['attr_id']] = $record;
2063 $result->closeCursor();
2067 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2069 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2072 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2074 if ($object_id <= 0)
2075 throw new InvalidArgException ('$objtype_id', $objtype_id);
2077 throw new InvalidArgException ('$attr_id', $attr_id);
2078 if (!strlen ($value))
2079 return commitResetAttrValue ($object_id, $attr_id);
2080 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
2081 $row = $result->fetch (PDO
::FETCH_NUM
);
2082 $attr_type = $row[0];
2089 $column = $attr_type . '_value';
2092 $column = 'uint_value';
2095 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
2097 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2098 // We know $value isn't empty here.
2099 usePreparedInsertBlade
2105 'object_id' => $object_id,
2106 'attr_id' => $attr_id,
2112 function commitUseupPort ($port_id = 0)
2114 return usePreparedExecuteBlade ('UPDATE Port SET reservation_comment=NULL WHERE id=?', array ($port_id));
2117 function convertPDOException ($e)
2119 if ($e->getCode() != 23000)
2121 switch ($e->errorInfo
[1])
2124 $text = 'such record already exists';
2128 $text = 'foreign key violation';
2131 $text = 'unknown error code ' . $e->errorInfo
[1];
2134 return new Exception ($text, E_DB_CONSTRAINT
);
2137 // This is a swiss-knife blade to insert a record into a table.
2138 // The first argument is table name.
2139 // The second argument is an array of "name" => "value" pairs.
2140 function usePreparedInsertBlade ($tablename, $columns)
2143 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2144 $query .= ') VALUES (' . implode (', ', array_fill (0, count ($columns), '?')) . ')';
2145 // Now the query should be as follows:
2146 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
2149 $prepared = $dbxlink->prepare ($query);
2150 if (!$prepared->execute (array_values ($columns)))
2152 return $prepared->rowCount() == 1;
2154 catch (PDOException
$e)
2156 throw convertPDOException ($e);
2160 // This swiss-knife blade deletes any number of records from the specified table
2161 // using the specified key names and values.
2162 function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
2166 $query = "DELETE FROM ${tablename} WHERE ";
2167 foreach ($columns as $colname => $colvalue)
2169 $query .= " ${conj} ${colname}=?";
2170 $conj = $conjunction;
2174 $prepared = $dbxlink->prepare ($query);
2175 if (!$prepared->execute (array_values ($columns)))
2177 return $prepared->rowCount(); // FALSE !== 0
2179 catch (PDOException
$e)
2181 throw convertPDOException ($e);
2185 function usePreparedSelectBlade ($query, $args = array())
2188 $prepared = $dbxlink->prepare ($query);
2189 if (!$prepared->execute ($args))
2194 // Prepare and execute the statement with parameters, then return number of
2195 // rows affected (or FALSE in case of an error).
2196 function usePreparedExecuteBlade ($query, $args = array())
2201 if (!$prepared = $dbxlink->prepare ($query))
2203 if (!$prepared->execute ($args))
2205 return $prepared->rowCount();
2207 catch (PDOException
$e)
2209 throw convertPDOException ($e);
2213 function loadConfigCache ()
2215 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
2217 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2218 $cache[$row['varname']] = $row;
2222 function loadUserConfigCache ($username = NULL)
2224 if (!strlen ($username))
2225 throw new InvalidArgException ('$username', $username);
2226 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
2228 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2229 $cache[$row['varname']] = $row;
2233 function deleteUserConfigVar ($username = NULL, $varname = NULL)
2235 usePreparedDeleteBlade ('UserConfig', array ('varname' => $varname, 'user' => $username));
2238 function storeUserConfigVar ($username = NULL, $varname = NULL, $varvalue = NULL)
2240 if (!strlen ($username))
2241 throw new InvalidArgException ('$username', $username);
2242 if (!strlen ($varname))
2243 throw new InvalidArgException ('$varname', $varname);
2244 if ($varvalue === NULL)
2245 throw new InvalidArgException ('$varvalue', $varvalue);
2246 return usePreparedExecuteBlade
2248 'REPLACE UserConfig SET varvalue=?, varname=?, user=?',
2249 array ($varvalue, $varname, $username)
2253 // setConfigVar() is expected to perform all necessary filtering
2254 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2256 if ($varvalue === NULL)
2257 throw new InvalidArgException ('$varvalue', $varvalue);
2258 return usePreparedExecuteBlade
2260 'UPDATE Config SET varvalue=? WHERE varname=?',
2261 array ($varvalue, $varname)
2265 // Database version detector. Should behave corretly on any
2266 // working dataset a user might have.
2267 function getDatabaseVersion ()
2269 $result = usePreparedSelectBlade ('SELECT varvalue FROM Config WHERE varname = "DB_VERSION" and vartype = "string"');
2270 if ($result == NULL)
2273 $errorInfo = $dbxlink->errorInfo();
2274 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2276 die (__FUNCTION__
. ': SQL query #1 failed with error ' . $errorInfo[2]);
2278 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
2279 if (count ($rows) != 1 ||
!strlen ($rows[0][0]))
2281 $result->closeCursor();
2282 die (__FUNCTION__
. ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2285 $result->closeCursor();
2289 // Return an array of virtual services. For each of them list real server pools
2290 // with their load balancers and other stats.
2291 function getSLBSummary ()
2293 $result = usePreparedSelectBlade
2295 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2296 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2297 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2298 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2299 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2300 'group by vs.id, object_id order by vs.vip, object_id'
2303 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2305 $vsid = $row['vsid'];
2306 $object_id = $row['object_id'];
2307 if (!isset ($ret[$vsid]))
2309 $ret[$vsid] = array();
2310 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2311 $ret[$vsid][$cname] = $row[$cname];
2312 $ret[$vsid]['lblist'] = array();
2314 // There's only one assigned RS pool possible for each LB-VS combination.
2315 $ret[$vsid]['lblist'][$row['object_id']] = array
2317 'id' => $row['rspool_id'],
2318 'size' => $row['rscount'],
2319 'name' => $row['pool_name']
2325 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2327 return usePreparedExecuteBlade
2329 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
2333 (!strlen ($rsport) or $rsport === 0) ?
NULL : $rsport,
2335 $inservice == 'yes' ?
'yes' : 'no',
2336 !strlen ($rsconfig) ?
NULL : $rsconfig
2341 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2344 throw new InvalidArgException ('$vip', $vip);
2346 throw new InvalidArgException ('$vport', $vport);
2347 if (!strlen ($proto))
2348 throw new InvalidArgException ('$proto', $proto);
2349 if (FALSE === usePreparedExecuteBlade
2351 'INSERT INTO IPv4VS (vip, vport, proto, name, vsconfig, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?, ?)',
2357 !strlen ($name) ?
NULL : $name,
2358 !strlen ($vsconfig) ?
NULL : $vsconfig,
2359 !strlen ($rsconfig) ?
NULL : $rsconfig,
2362 return __FUNCTION__
. ': SQL insertion failed';
2363 return produceTagsForLastRecord ('ipv4vs', $taglist);
2366 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2368 return usePreparedInsertBlade
2373 'object_id' => $object_id,
2374 'rspool_id' => $pool_id,
2376 'vsconfig' => (!strlen ($vsconfig) ?
NULL : $vsconfig),
2377 'rsconfig' => (!strlen ($rsconfig) ?
NULL : $rsconfig)
2382 function commitDeleteRS ($id = 0)
2384 return usePreparedDeleteBlade ('IPv4RS', array ('id' => $id));
2387 function commitDeleteVS ($id = 0)
2389 releaseFiles ('ipv4vs', $id);
2390 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
2393 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2395 return usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id, 'rspool_id' => $pool_id, 'vs_id' => $vs_id));
2398 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2400 if (long2ip (ip2long ($rsip)) !== $rsip)
2401 throw new InvalidArgException ('$rsip', $rsip);
2402 return usePreparedExecuteBlade
2404 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2408 (!strlen ($rsport) or $rsport === 0) ?
NULL : $rsport,
2409 !strlen ($rsconfig) ?
NULL : $rsconfig,
2415 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2417 return usePreparedExecuteBlade
2419 'UPDATE IPv4LB SET vsconfig=?, rsconfig=? WHERE object_id=? AND rspool_id=? AND vs_id=?',
2422 !strlen ($vsconfig) ?
NULL : $vsconfig,
2423 !strlen ($rsconfig) ?
NULL : $rsconfig,
2431 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2434 throw new InvalidArgException ('$vip', $vip);
2436 throw new InvalidArgException ('$vport', $vport);
2437 if (!strlen ($proto))
2438 throw new InvalidArgException ('$proto', $proto);
2439 return usePreparedExecuteBlade
2441 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2447 !strlen ($name) ?
NULL : $name,
2448 !strlen ($vsconfig) ?
NULL : $vsconfig,
2449 !strlen ($rsconfig) ?
NULL : $rsconfig,
2455 function loadThumbCache ($rack_id = 0)
2458 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
2459 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2461 $ret = base64_decode ($row['thumb_data']);
2465 function saveThumbCache ($rack_id = 0, $cache = NULL)
2468 throw new InvalidArgException ('$cache', $cache);
2469 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=? WHERE id=?', array (base64_encode ($cache), $rack_id));
2472 function resetThumbCache ($rack_id = 0)
2474 usePreparedExecuteBlade ('UPDATE Rack SET thumb_data=NULL WHERE id=?', array ($rack_id));
2477 // Return the list of attached RS pools for the given object. As long as we have
2478 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2479 // by vs_id, because there will be only one RS pool listed for each VS of the
2481 function getRSPoolsForObject ($object_id = 0)
2483 $result = usePreparedSelectBlade
2485 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2486 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2487 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2488 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2489 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2490 'where lb.object_id = ? ' .
2491 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2495 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2496 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2497 $ret[$row['vs_id']][$cname] = $row[$cname];
2501 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2503 if (!strlen ($name))
2504 throw new InvalidArgException ('$name', $name);
2505 if (!usePreparedInsertBlade
2510 'name' => (!strlen ($name) ?
NULL : $name),
2511 'vsconfig' => (!strlen ($vsconfig) ?
NULL : $vsconfig),
2512 'rsconfig' => (!strlen ($rsconfig) ?
NULL : $rsconfig)
2515 return __FUNCTION__
. ': SQL insertion failed';
2516 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2519 function commitDeleteRSPool ($pool_id = 0)
2521 releaseFiles ('ipv4rspool', $pool_id);
2522 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2525 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2527 return usePreparedExecuteBlade
2529 'UPDATE IPv4RSPool SET name=?, vsconfig=?, rsconfig=? WHERE id=?',
2532 !strlen ($name) ?
NULL : $name,
2533 !strlen ($vsconfig) ?
NULL : $vsconfig,
2534 !strlen ($rsconfig) ?
NULL : $rsconfig,
2540 function getRSList ()
2542 $result = usePreparedSelectBlade
2544 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2545 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2548 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2549 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2550 $ret[$row['id']][$cname] = $row[$cname];
2554 // Return the list of all currently configured load balancers with their pool count.
2555 function getLBList ()
2557 $result = usePreparedSelectBlade
2559 "select object_id, count(rspool_id) as poolcount " .
2560 "from IPv4LB group by object_id order by object_id"
2563 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2564 $ret[$row['object_id']] = $row['poolcount'];
2568 // For the given object return: its vsconfig/rsconfig; the list of RS pools
2569 // attached (each with vsconfig/rsconfig in turn), each with the list of
2570 // virtual services terminating the pool. Each pool also lists all real
2571 // servers with rsconfig.
2572 function getSLBConfig ($object_id)
2575 $result = usePreparedSelectBlade
2577 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2578 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2579 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2580 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2581 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2582 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2583 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2584 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2585 "where lb.object_id = ? and rs.inservice = 'yes' " .
2586 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2589 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2591 $vs_id = $row['vs_id'];
2592 if (!isset ($ret[$vs_id]))
2594 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name') as $c)
2595 $ret[$vs_id][$c] = $row[$c];
2596 $ret[$vs_id]['rslist'] = array();
2598 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2599 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2604 function commitSetInService ($rs_id = 0, $inservice = '')
2606 if (!strlen ($inservice))
2607 throw new InvalidArgException ('$inservice', $inservice);
2608 return usePreparedExecuteBlade ('UPDATE IPv4RS SET inservice=? WHERE id=?', array ($inservice, $rs_id));
2611 function executeAutoPorts ($object_id = 0, $type_id = 0)
2613 if ($object_id == 0)
2614 throw new InvalidArgException ('$object_id', $object_id);
2616 throw new InvalidArgException ('$type_id', $type_id);
2618 foreach (getAutoPorts ($type_id) as $autoport)
2619 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2623 // Return only implicitly listed tags, the rest of the chain will be
2624 // generated/deducted later at higher levels.
2625 // Result is a chain: randomly indexed taginfo list.
2626 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2629 $result = usePreparedSelectBlade
2631 "select tt.id, tag from " .
2632 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2633 "where entity_realm = ? and entity_id = ? " .
2635 array ($entity_realm, $entity_id)
2637 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2638 $ret[$row['id']] = $row;
2639 return getExplicitTagsOnly ($ret);
2642 // Return a tag chain with all DB tags on it.
2643 function getTagList ()
2646 $result = usePreparedSelectBlade
2648 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2649 "from TagTree left join TagStorage on id = tag_id " .
2650 "group by id, entity_realm order by tag"
2652 // Collation index. The resulting rows are ordered according to default collation,
2653 // which is utf8_general_ci for UTF-8.
2655 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2657 if (!isset ($ret[$row['id']]))
2658 $ret[$row['id']] = array
2661 'tag' => $row['tag'],
2663 'parent_id' => $row['parent_id'],
2664 'refcnt' => array ('total' => 0)
2668 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2669 $ret[$row['id']]['refcnt']['total'] +
= $row['refcnt'];
2675 function commitCreateTag ($tagname = '', $parent_id = 0)
2678 throw new InvalidArgException ('tagname', $tagname);
2679 return usePreparedInsertBlade
2685 'parent_id' => $parent_id
2690 function commitDestroyTag ($tagid = 0)
2692 if (usePreparedDeleteBlade ('TagTree', array ('id' => $tagid)))
2694 return 'usePreparedDeleteBlade() failed in ' . __FUNCTION__
;
2697 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2699 return usePreparedExecuteBlade
2701 'UPDATE TagTree SET tag=?, parent_id=? WHERE id=?',
2705 $parent_id == 0 ?
NULL : $parent_id,
2711 // Drop the whole chain stored.
2712 function destroyTagsForEntity ($entity_realm, $entity_id)
2714 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
2717 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2718 // FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
2720 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2722 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
2725 // Push a record into TagStorage unconditionally.
2726 function addTagForEntity ($realm = '', $entity_id, $tag_id)
2728 if (!in_array ($realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2730 return usePreparedInsertBlade
2735 'entity_realm' => $realm,
2736 'entity_id' => $entity_id,
2737 'tag_id' => $tag_id,
2742 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2743 // on the implicit list already). Then remove any other records, which
2744 // appear on the "implicit" side of the chain. This will make sure,
2745 // that both the tag base is still minimal and all requested tags appear on
2746 // the resulting tag chain.
2747 // Return TRUE, if any changes were committed.
2748 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2750 // Put the current explicit sub-chain into a buffer and merge all tags from
2751 // the extra chain, which aren't there yet.
2752 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2753 foreach ($extrachain as $extratag)
2754 if (!tagOnChain ($extratag, $newchain))
2755 $newchain[] = $extratag;
2756 // Then minimize the working buffer and check if it differs from the original
2757 // chain we started with. If it is so, save the work and signal the upper layer.
2758 $newchain = getExplicitTagsOnly ($newchain);
2759 if (tagChainCmp ($oldchain, $newchain))
2761 destroyTagsForEntity ($realm, $entity_id);
2762 foreach ($newchain as $taginfo)
2763 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2769 // Presume, that the target record has no tags attached.
2770 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2772 if (!count ($tagidlist))
2774 if (!$last_insert_id)
2775 $last_insert_id = lastInsertID();
2777 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
2778 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
2783 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2786 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2788 // $range is in x.x.x.x/x format, split into ip/mask vars
2789 $rangeArray = explode('/', $range);
2790 if (count ($rangeArray) != 2)
2791 return "Invalid IPv4 prefix '${range}'";
2792 $ip = $rangeArray[0];
2793 $mask = $rangeArray[1];
2795 if (!strlen ($ip) or !strlen ($mask))
2796 return "Invalid IPv4 prefix '${range}'";
2797 $ipL = ip2long($ip);
2798 $maskL = ip2long($mask);
2799 if ($ipL == -1 ||
$ipL === FALSE)
2800 return 'Bad IPv4 address';
2801 if ($mask < 32 && $mask > 0)
2805 $maskB = decbin($maskL);
2806 if (strlen($maskB)!=32)
2807 return 'Invalid netmask';
2810 foreach( str_split ($maskB) as $digit)
2817 if ($zeroes == TRUE)
2818 return 'Invalid netmask';
2823 $binmask = binMaskFromDec($maskL);
2824 $ipL = $ipL & $binmask;
2825 $result = usePreparedInsertBlade
2830 'ip' => sprintf ('%u', $ipL),
2835 if ($result != TRUE)
2836 return "Could not add ${range} (already exists?).";
2838 if ($is_bcast and $maskL < 31)
2840 $network_addr = long2ip ($ipL);
2841 $broadcast_addr = long2ip ($ipL |
binInvMaskFromDec ($maskL));
2842 updateAddress ($network_addr, 'network', 'yes');
2843 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2845 return produceTagsForLastRecord ('ipv4net', $taglist);
2848 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
2849 function destroyIPv4Prefix ($id = 0)
2851 releaseFiles ('ipv4net', $id);
2852 if (FALSE === usePreparedDeleteBlade ('IPv4Network', array ('id' => $id)))
2853 return __FUNCTION__
. ': SQL query #1 failed';
2854 if (FALSE === destroyTagsForEntity ('ipv4net', $id))
2855 return __FUNCTION__
. ': SQL query #2 failed';
2859 function loadScript ($name)
2861 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
2862 $row = $result->fetch (PDO
::FETCH_NUM
);
2869 function saveScript ($name = '', $text)
2871 if (!strlen ($name))
2872 throw new InvalidArgException ('$name', $name);
2873 return usePreparedExecuteBlade
2875 'INSERT INTO Script (script_name, script_text) VALUES (?, ?) ' .
2876 'ON DUPLICATE KEY UPDATE script_text=?',
2877 array ($name, $text, $text)
2881 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2883 if (NULL === getIPv4AddressNetworkId ($localip))
2884 return "$localip: Non existant ip";
2885 if (NULL === getIPv4AddressNetworkId ($remoteip))
2886 return "$remoteip: Non existant ip";
2887 if ( ($localport <= 0) or ($localport >= 65536) )
2888 return "$localport: invaild port";
2889 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
2890 return "$remoteport: invaild port";
2892 $result = usePreparedExecuteBlade
2894 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
2895 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
2907 return $result !== FALSE ?
'' : (__FUNCTION__
. '(): failed to insert the rule');
2910 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
2912 return usePreparedExecuteBlade
2914 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
2915 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',
2916 array ($object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2920 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
2922 return usePreparedExecuteBlade
2924 'UPDATE IPv4NAT SET description=? WHERE object_id=? AND localip=INET_ATON(?) AND remoteip=INET_ATON(?) ' .
2925 'AND localport=? AND remoteport=? AND proto=?',
2926 array ($description, $object_id, $localip, $remoteip, $localport, $remoteport, $proto)
2930 function getNATv4ForObject ($object_id)
2933 $ret['out'] = array();
2934 $ret['in'] = array();
2935 $result = usePreparedSelectBlade
2939 "INET_NTOA(localip) as localip, ".
2941 "INET_NTOA(remoteip) as remoteip, ".
2943 "ipa1.name as local_addr_name, " .
2944 "ipa2.name as remote_addr_name, " .
2947 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
2948 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
2949 "where object_id=? ".
2950 "order by localip, localport, proto, remoteip, remoteport",
2954 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2956 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
2957 $ret['out'][$count][$cname] = $row[$cname];
2962 $result = usePreparedSelectBlade
2966 "INET_NTOA(localip) as localip, ".
2968 "INET_NTOA(remoteip) as remoteip, ".
2970 "IPv4NAT.object_id as object_id, ".
2971 "RackObject.name as object_name, ".
2973 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
2974 "where IPv4Allocation.object_id=? ".
2975 "order by remoteip, remoteport, proto, localip, localport",
2979 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2981 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
2982 $ret['in'][$count][$cname] = $row[$cname];
2988 // Return a list of files, which are not linked to the specified record. This list
2989 // will be used by printSelect().
2990 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
2992 $query = usePreparedSelectBlade
2994 'SELECT id, name FROM File ' .
2995 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
2996 'ORDER BY name, id',
2997 array ($entity_type, $entity_id)
3000 while ($row = $query->fetch (PDO
::FETCH_ASSOC
))
3001 $ret[$row['id']] = $row['name'];
3005 // FIXME: return a standard cell list, so upper layer can iterate over
3007 function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3009 $query = usePreparedSelectBlade
3011 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3012 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3013 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name',
3014 array ($entity_type, $entity_id)
3017 while ($row = $query->fetch (PDO
::FETCH_ASSOC
))
3018 $ret[$row['file_id']] = array (
3019 'id' => $row['file_id'],
3020 'link_id' => $row['link_id'],
3021 'name' => $row['name'],
3022 'type' => $row['type'],
3023 'size' => $row['size'],
3024 'ctime' => $row['ctime'],
3025 'mtime' => $row['mtime'],
3026 'atime' => $row['atime'],
3027 'comment' => $row['comment'],
3032 function getFile ($file_id = 0)
3034 $query = usePreparedSelectBlade
3036 'SELECT id, name, type, size, ctime, mtime, atime, contents, comment ' .
3037 'FROM File WHERE id = ?',
3040 if (($row = $query->fetch (PDO
::FETCH_ASSOC
)) == NULL)
3042 showWarning ('Query succeeded, but returned no data', __FUNCTION__
);
3048 $ret['id'] = $row['id'];
3049 $ret['name'] = $row['name'];
3050 $ret['type'] = $row['type'];
3051 $ret['size'] = $row['size'];
3052 $ret['ctime'] = $row['ctime'];
3053 $ret['mtime'] = $row['mtime'];
3054 $ret['atime'] = $row['atime'];
3055 $ret['contents'] = $row['contents'];
3056 $ret['comment'] = $row['comment'];
3057 $query->closeCursor();
3059 // Someone accessed this file, update atime
3060 usePreparedExecuteBlade ('UPDATE File SET atime = ? WHERE id = ?', array (date ('YmdHis'), $file_id));
3065 function getFileLinks ($file_id = 0)
3067 $query = usePreparedSelectBlade
3069 'SELECT id, file_id, entity_type, entity_id FROM FileLink ' .
3070 'WHERE file_id = ? ORDER BY entity_type, entity_id',
3073 $rows = $query->fetchAll (PDO
::FETCH_ASSOC
);
3075 foreach ($rows as $row)
3077 // get info of the parent
3078 switch ($row['entity_type'])
3083 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3084 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3087 $page = 'ipv4rspool';
3088 $id_name = 'pool_id';
3089 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3090 $name = $parent['name'];
3095 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3096 $name = $parent['name'];
3100 $id_name = 'object_id';
3101 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3102 $name = $parent['dname'];
3106 $id_name = 'rack_id';
3107 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3108 $name = $parent['name'];
3112 $id_name = 'user_id';
3113 $parent = spotEntity ($row['entity_type'], $row['entity_id']);
3114 $name = $parent['user_name'];
3118 // name needs to have some value for hrefs to work
3119 if (!strlen ($name))
3120 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3122 $ret[$row['id']] = array(
3124 'id_name' => $id_name,
3125 'entity_type' => $row['entity_type'],
3126 'entity_id' => $row['entity_id'],
3133 function getFileStats ()
3135 $result = usePreparedSelectBlade ('SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type');
3137 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3138 if ($row['count'] > 0)
3139 $ret["Links in realm '${row['entity_type']}'"] = $row['count'];
3142 // Find number of files without any linkage
3143 $result = usePreparedSelectBlade
3145 'SELECT COUNT(*) ' .
3147 'WHERE id NOT IN (SELECT file_id FROM FileLink)'
3149 $ret["Unattached files"] = $result->fetchColumn ();
3152 // Find total number of files
3153 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM File');
3154 $ret["Total files"] = $result->fetchColumn ();
3159 function commitAddFile ($name, $type, $size, $contents, $comment)
3161 $now = date('YmdHis');
3164 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3165 $query->bindParam(1, $name);
3166 $query->bindParam(2, $type);
3167 $query->bindParam(3, $size);
3168 $query->bindParam(4, $now);
3169 $query->bindParam(5, $now);
3170 $query->bindParam(6, $now);
3171 $query->bindParam(7, $contents, PDO
::PARAM_LOB
);
3172 $query->bindParam(8, $comment);
3175 return $query->execute();
3177 catch (PDOException
$e)
3179 throw convertPDOException ($e);
3183 function commitLinkFile ($file_id, $entity_type, $entity_id)
3185 return usePreparedExecuteBlade
3187 'INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)',
3188 array ($file_id, $entity_type, $entity_id)
3192 function commitReplaceFile ($file_id = 0, $contents)
3195 $query = $dbxlink->prepare('UPDATE File SET mtime = NOW(), contents = ?, size = LENGTH(contents) WHERE id = ?');
3196 $query->bindParam(1, $contents, PDO
::PARAM_LOB
);
3197 $query->bindParam(2, $file_id);
3201 return $query->execute();
3203 catch (PDOException
$e)
3205 throw convertPDOException ($e);
3209 function commitUpdateFile ($file_id = 0, $new_name = '', $new_type = '', $new_comment = '')
3211 if (!strlen ($new_name))
3212 throw new InvalidArgException ('$new_name', $new_name);
3213 if (!strlen ($new_type))
3214 throw new InvalidArgException ('$new_type', $new_type);
3215 return usePreparedExecuteBlade
3217 'UPDATE File SET name = ?, type = ?, comment = ? WHERE id = ?',
3218 array ($new_name, $new_type, $new_comment, $file_id)
3222 function commitUnlinkFile ($link_id)
3224 if (usePreparedDeleteBlade ('FileLink', array ('id' => $link_id)) === FALSE)
3225 return __FUNCTION__
. '(): query failed';
3229 function commitDeleteFile ($file_id)
3231 destroyTagsForEntity ('file', $file_id);
3232 if (usePreparedDeleteBlade ('File', array ('id' => $file_id)) === FALSE)
3233 return __FUNCTION__
. '(): query failed';
3237 function getChapterList ()
3240 $result = usePreparedSelectBlade
3242 'SELECT id, sticky, name, count(chapter_id) as wordc ' .
3243 'FROM Chapter LEFT JOIN Dictionary ON Chapter.id = chapter_id ' .
3244 'GROUP BY id ORDER BY name'
3246 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3247 $ret[$row['id']] = $row;
3251 // Return file id by file name.
3252 function findFileByName ($filename)
3254 $query = usePreparedSelectBlade ('SELECT id FROM File WHERE name = ?', array ($filename));
3255 if (($row = $query->fetch (PDO
::FETCH_ASSOC
)))
3261 function acquireLDAPCache ($form_username, $password_hash, $expiry = 0)
3264 $dbxlink->beginTransaction();
3265 $result = usePreparedSelectBlade
3267 'SELECT TIMESTAMPDIFF(SECOND, first_success, now()) AS success_age, ' .
3268 'TIMESTAMPDIFF(SECOND, last_retry, now()) AS retry_age, displayed_name, memberof ' .
3269 'FROM LDAPCache WHERE presented_username = ? AND successful_hash = ? ' .
3270 'HAVING success_age < ? FOR UPDATE',
3271 array ($form_username, $password_hash, $expiry)
3273 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3275 $row['memberof'] = unserialize (base64_decode ($row['memberof']));
3281 function releaseLDAPCache ()
3287 // This actually changes only last_retry.
3288 function touchLDAPCacheRecord ($form_username)
3290 return usePreparedExecuteBlade ('UPDATE LDAPCache SET last_retry=NOW() WHERE presented_username=?', array ($form_username));
3293 function replaceLDAPCacheRecord ($form_username, $password_hash, $dname, $memberof)
3295 deleteLDAPCacheRecord ($form_username);
3296 usePreparedInsertBlade ('LDAPCache',
3299 'presented_username' => $form_username,
3300 'successful_hash' => $password_hash,
3301 'displayed_name' => $dname,
3302 'memberof' => base64_encode (serialize ($memberof)),
3307 function deleteLDAPCacheRecord ($form_username)
3309 return usePreparedDeleteBlade ('LDAPCache', array ('presented_username' => $form_username));
3312 // Age all records older, than cache_expiry seconds, and all records made in future.
3313 // Calling this function w/o argument purges the whole LDAP cache.
3314 function discardLDAPCache ($maxage = 0)
3316 return usePreparedExecuteBlade ('DELETE from LDAPCache WHERE TIMESTAMPDIFF(SECOND, first_success, NOW()) >= ? or NOW() < first_success', array ($maxage));
3319 function getUserIDByUsername ($username)
3321 $result = usePreparedSelectBlade ('SELECT user_id FROM UserAccount WHeRE user_name = ?', array ($username));
3322 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3323 return $row['user_id'];
3327 // Return TRUE, if the given address is assigned to a port of any object
3328 // except the current object. Using this function as a constraint makes
3329 // it possible to reuse L2 addresses within one object, yet keeping them
3330 // universally unique on the other hand.
3331 function alreadyUsedL2Address ($address, $my_object_id)
3333 $result = usePreparedSelectBlade
3335 'SELECT COUNT(*) FROM Port WHERE BINARY l2address = ? AND object_id != ?',
3336 array ($address, $my_object_id)
3338 $row = $result->fetch (PDO
::FETCH_NUM
);
3339 return $row[0] != 0;
3342 function getPortInterfaceCompat()
3344 $result = usePreparedSelectBlade
3346 'SELECT iif_id, iif_name, oif_id, dict_value AS oif_name ' .
3347 'FROM PortInterfaceCompat INNER JOIN PortInnerInterface ON id = iif_id ' .
3348 'INNER JOIN Dictionary ON dict_key = oif_id ' .
3349 'ORDER BY iif_name, oif_name'
3351 return $result->fetchAll (PDO
::FETCH_ASSOC
);
3354 // Return a set of options for a plain SELECT. These options include the current
3355 // OIF of the given port and all OIFs of its permanent IIF.
3356 function getExistingPortTypeOptions ($port_id)
3358 $result = usePreparedSelectBlade
3360 'SELECT oif_id, dict_value AS oif_name ' .
3361 'FROM PortInterfaceCompat INNER JOIN Dictionary ON oif_id = dict_key ' .
3362 'WHERE iif_id = (SELECT iif_id FROM Port WHERE id = ?) ' .
3363 'ORDER BY oif_name',
3367 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3368 $ret[$row['oif_id']] = $row['oif_name'];
3372 function getPortIIFOptions()
3375 $result = usePreparedSelectBlade ('SELECT id, iif_name FROM PortInnerInterface ORDER BY iif_name');
3376 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3377 $ret[$row['id']] = $row['iif_name'];
3381 function commitSupplementPIC ($iif_id, $oif_id)
3383 return usePreparedInsertBlade
3385 'PortInterfaceCompat',
3386 array ('iif_id' => $iif_id, 'oif_id' => $oif_id)
3390 function commitReducePIC ($iif_id, $oif_id)
3392 return usePreparedDeleteBlade ('PortInterfaceCompat', array ('iif_id' => $iif_id, 'oif_id' => $oif_id));
3395 function getPortIIFStats ($args)
3397 $result = usePreparedSelectBlade
3399 'SELECT dict_value AS title, COUNT(id) AS max, ' .
3400 'COUNT(reservation_comment) + ' .
3401 'SUM((SELECT COUNT(*) FROM Link WHERE id IN (porta, portb))) AS current ' .