Reimplemented on top of fix for moodle core

7c259c989075e497c62eb281208869220ad3c56d