public static function get_repository_by_id($repositoryid, $context, $options = array()) {
        global $CFG, $DB;
        $cache = cache::make('core', 'repositories');
        if (!is_object($context)) {
            $context = context::instance_by_id($context);
        }
        $cachekey = 'rep:'. $repositoryid. ':'. $context->id. ':'. serialize($options);
        if ($repository = $cache->get($cachekey)) {
            return $repository;
        }

        if (!$record = $cache->get('i:'. $repositoryid)) {
            $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
                      FROM {repository_instances} i
                      JOIN {repository} r ON r.id = i.typeid
                     WHERE i.id = ?";
            if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
                throw new repository_exception('invalidrepositoryid', 'repository');
            }
            $cache->set('i:'. $record->id, $record);
        }

        $type = $record->repositorytype;
        if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
            require_once($CFG->dirroot . "/repository/$type/lib.php");
            $classname = 'repository_' . $type;
            $options['type'] = $type;
            $options['typeid'] = $record->typeid;
            $options['visible'] = $record->visible;
            if (empty($options['name'])) {
                $options['name'] = $record->name;
            }
            $repository = new $classname($repositoryid, $context, $options, $record->readonly);
            if (empty($repository->super_called)) {
                // to make sure the super construct is called
                debugging('parent::__construct must be called by '.$type.' plugin.');
            }
            $cache->set($cachekey, $repository);
            return $repository;
        } else {
            throw new repository_exception('invalidplugin', 'repository');
        }
    }