Moved traversal joins before all other joins.

By changing the insertion order of the joins, developers can use the data from the traversed tables in their own joins. For example, developers can now use a column retrieved from a traverse join in an `ON` clause.

This also incorporates some miscellaneous fixes from #949:
 * `$params->sql` instead of `$this->sql` should be the source of the rewriting process.
 * The `/g` flag in `preg_replace` is unnecessary and deprecated.
 * A copy-paste typo caused `$params->having` being inserted in the `ORDER BY` clause.
Although the rewriting still remains unused, this should reduce the amount of headaches whenever it does become usable.