Dec 26, 2015

Drupal 8, Beta 15 --> RC 1: Eliminating use of checkPlain( )

Since SafeMarkup::checkPlain() is now deprecated and possibly intended to be removed along with other SafeMarkup methods, I decided to address this in migrating to RC 1.

In the common use case where D8's Twig templates are used for output, you can dispense with checkPlain() entirely and rely on Twig's autoescaping. That turned out to apply to our simple use of forms to input and render a few text values.

In the original code, checkPlain() was called both to process user-entered values as well as to sanitize those values before they were placed into render arrays. When I typed <script> into a form field, it was incorrectly escaped twice and displayed as   &lt;script&gt;

Removing those calls works fine and conforms to what is considered good practice for D8. Potentially unsafe markup is stored as is in the database, but Twig converts it before it is sent to the browser.

The article  SafeMarkup methods are removed  is extremely useful in how it breaks down the different use cases for checkPlain() and what needs to be done differently for each in D8 in order to prevent unsafe markup from being rendered.

Besides Twig templates, the other use cases are:

-  Text placed into a render array by using the #plain_text key
-  A mixture of escaped markup with markup not to be escaped
-  Non-HTML responses, eg. JSON

The discussion also applies to the check_plain() function in Drupal 7, for which checkPlain() was a replacement. If you're starting out with a conversion from D7, the article is a must read.

Sources:

SafeMarkup::set(), SafeMarkup::checkPlain(), and other methods are removed from Drupal 8 core
https://groups.drupal.org/node/478558

SafeMarkup methods are removed
https://www.drupal.org/node/2549395

Twig autoescape enabled and text sanitization APIs updated
https://www.drupal.org/node/2296163

No comments:

Post a Comment