protected static function get_context_from_params($param) {
        $levels = context_helper::get_all_levels();
        if (!empty($param['contextid'])) {
            return context::instance_by_id($param['contextid'], IGNORE_MISSING);
        } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
            $contextlevel = "context_".$param['contextlevel'];
            if (!array_search($contextlevel, $levels)) {
                throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
            }
           return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
        } else {
            // No valid context info was found.
            throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
        }
    }