public static function can_user_view_policy_version($policy, $behalfid = null, $userid = null) {
        global $USER;

        if ($policy->status == policy_version::STATUS_ACTIVE) {
            return true;
        }

        if (empty($userid)) {
            $userid = $USER->id;
        }

        // Check if the user is viewing the policy on someone else's behalf.
        // Typical scenario is a parent viewing the policy on behalf of her child.
        if ($behalfid > 0) {
            $behalfcontext = context_user::instance($behalfid);

            if ($behalfid != $userid && !has_capability('tool/policy:acceptbehalf', $behalfcontext, $userid)) {
                return false;
            }

            // Check that the other user (e.g. the child) has access to the policy.
            // Pass a negative third parameter to avoid eventual endless loop.
            // We do not support grand-parent relations.
            return static::can_user_view_policy_version($policy, -1, $behalfid);
        }

        // Users who can manage policies, can see all versions.
        if (has_capability('tool/policy:managedocs', context_system::instance(), $userid)) {
            return true;
        }

        // User who can see all acceptances, must be also allowed to see what was accepted.
        if (has_capability('tool/policy:viewacceptances', context_system::instance(), $userid)) {
            return true;
        }

        // Users have access to all the policies they have ever accepted/declined.
        if (static::is_user_version_accepted($userid, $policy->id) !== null) {
            return true;
        }

        // Check if the user could get access through some of her minors.
        if ($behalfid === null) {
            foreach (static::get_user_minors($userid) as $minor) {
                if (static::can_user_view_policy_version($policy, $minor->id, $userid)) {
                    return true;
                }
            }
        }

        return false;
    }