Base commit ported from https://github.com/Elgg/Elgg/pull/5242