Ported from https://github.com/Elgg/Elgg/pull/480 and wrapped into plugin.