General token sanitizer. Strips out (or encapsulates) unsafe and disallowed tag types and attributes. Should run last in the third, synchronous expansion stage. Tokens from extensions which should not be sanitized can bypass sanitation by setting their rank to 3.
A large part of this code is a straight port from the PHP version.