Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix less than character (<) display issue #2243

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

AbdiTolesa
Copy link
Contributor

@AbdiTolesa AbdiTolesa commented Feb 11, 2025

Fix https://github.com/Strategy11/formidable-pro/issues/5613

Test procedure

  1. Add a Paragraph and Text field to your form.
  2. Submit entries, with text that contains less than characters (<).
  3. Go to the entry administration and opening the entries for editing.
  4. Confirm that the edit values does not contain html entities literal but the actual characters entered during submittion.

Copy link
Contributor

coderabbitai bot commented Feb 11, 2025

Walkthrough

The changes introduce a new method prepare_esc_value() in the FrmFieldText class, which prepares field values for output while preserving intentional HTML entities. Additionally, the front_field_input method in the FrmFieldTextarea class has been modified to change how textarea values are rendered by replacing occurrences of &amp; with &, allowing the ampersand character to be displayed without its HTML entity representation.

Changes

File Change Summary
classes/models/fields/FrmFieldText.php Added a protected method prepare_esc_value() to prepare field values for output with preserved HTML entities.
classes/models/fields/FrmFieldTextarea.php Modified front_field_input method to replace &amp; with & in the textarea value rendering.

Suggested reviewers

  • lauramekaj1
  • truongwp
  • Crabcyborg

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 PHPStan (2.0.3)

/bin/bash: line 1: /vendor/bin/phpstan: No such file or directory


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f9f0fc and 3f9076d.

📒 Files selected for processing (1)
  • classes/models/fields/FrmFieldText.php (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • classes/models/fields/FrmFieldText.php
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: PHP 8 tests in WP trunk
  • GitHub Check: PHP 7.4 tests in WP trunk
  • GitHub Check: Cypress

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
classes/models/fields/FrmFieldText.php (1)

54-54: Update version tag placeholder.

The @since x.x version tag needs to be updated with the actual version number.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 14f1769 and 8f9f0fc.

📒 Files selected for processing (2)
  • classes/models/fields/FrmFieldText.php (1 hunks)
  • classes/models/fields/FrmFieldTextarea.php (1 hunks)
🔇 Additional comments (1)
classes/models/fields/FrmFieldText.php (1)

58-70: Consider edge cases and potential improvements.

The method has several areas that could be improved:

  1. The method is protected but not used within the class.
  2. Empty string case isn't handled explicitly.
  3. Array handling assumes comma-separator is always desired.
  4. Potential double-encoding of entities when htmlentities() is applied.

Consider these improvements:

 protected function prepare_esc_value() {
     $value = $this->field['value'];
-    if ( is_null( $value ) ) {
+    if ( is_null( $value ) || '' === $value ) {
         return '';
     }
     if ( is_array( $value ) ) {
-        $value = implode( ', ', $value );
+        $separator = apply_filters( 'frm_array_value_separator', ', ', array( 'field' => $this->field ) );
+        $value = implode( $separator, $value );
     }
     if ( strpos( $value, '&lt;' ) !== false ) {
-        $value = htmlentities( $value );
+        $value = htmlentities( $value, ENT_QUOTES | ENT_HTML5, 'UTF-8', false );
     }
     return str_replace( '&amp;', '&', $value );
 }

Let's verify if this method is used elsewhere in the codebase:

❌ Incorrect review comment

🏁 Script executed:

#!/bin/bash
# Search for method usage
rg "prepare_esc_value" -A 5

Length of output: 1335


Clarification on Method Usage and Improvement Suggestions

  • Our search confirms that prepare_esc_value is indeed used—in particular, it’s called from the HTML input generation in classes/models/fields/FrmFieldType.php. Thus, the review comment’s assertion that the method is “not used within the class” is inaccurate.
  • The other suggested improvements (explicit handling of empty strings, configurable array separators via a filter, and avoiding potential double-encoding by refining the htmlentities() call) remain valid considerations for enhancing robustness.

Likely an incorrect or invalid review comment.

@@ -94,7 +94,7 @@ public function front_field_input( $args, $shortcode_atts ) {

return '<textarea name="' . esc_attr( $args['field_name'] ) . '" id="' . esc_attr( $args['html_id'] ) . '" ' .
$rows . $input_html . '>' .
FrmAppHelper::esc_textarea( $this->field['value'] ) .
str_replace( '&amp;', '&', FrmAppHelper::esc_textarea( $this->field['value'] ) ) .
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify security implications of entity replacement.

While the change fixes the HTML entities display issue, replacing &amp; with & after escaping might have security implications or affect HTML form validation.

Let's verify how WordPress core handles similar cases:

Consider these alternatives:

  1. Use WordPress's wp_specialchars_decode() with controlled flags.
  2. Apply the entity replacement before escaping.
-str_replace( '&amp;', '&', FrmAppHelper::esc_textarea( $this->field['value'] ) ) .
+FrmAppHelper::esc_textarea( wp_specialchars_decode( $this->field['value'], ENT_QUOTES ) ) .

🌐 Web query:

How does WordPress handle HTML entities in textarea fields?

💡 Result:

WordPress handles HTML entities in textarea fields through a combination of core sanitization functions and plugin-specific processing layers. Here's the key technical breakdown:

Core Sanitization Process

  1. Automatic Entity Conversion:
    WordPress automatically converts special characters to HTML entities during database operations using functions like wp_filter_post_kses()[1][5]. For example:

    & becomes &amp;
    < becomes &lt;
  2. Textarea-Specific Escaping:

    • Uses esc_textarea() for frontend rendering to prevent XSS attacks[5]
    • Preserves raw input when using get_post_field('post_content') but applies entity conversion during display[3][7]

ACF-Specific Behavior

  1. Field Type Differences:

    • Text/Textarea Fields: Strip HTML tags by default[3]
    • WYSIWYG Fields: Preserve HTML but require unescaped output[3]
  2. Common Pitfalls:

    // Double-encoding occurs when manually escaping before update_field()
    update_field('textarea', htmlentities($input)); // Bad practice[1]

Workflow Solutions

  1. Safe Input Handling:

    // For plain text storage (ACF text/textarea):
    update_field('field_key', sanitize_textarea_field($_POST['content']));
    
    // For HTML content (ACF WYSIWYG):
    update_field('field_key', wp_kses_post($_POST['content']));
  2. Output Best Practices:

    // Text/Textarea (escape output):
    echo esc_textarea(get_field('text_field'));
    
    // WYSIWYG (raw HTML output):
    echo wp_kses_post(get_field('wysiwyg_field'));

Developers should avoid manual htmlentities() calls when using ACF's API[1][3], as WordPress and ACF already handle encoding through their respective pipelines. The formatting setting in ACF field configurations ("Convert new lines to
") directly affects whether \n characters become <br> tags during rendering[3][9].

Citations:


Security concern: Directly replacing escaped entities may undermine output safety.

  • The current code applies FrmAppHelper::esc_textarea() and then uses str_replace( '&amp;', '&', … ) to alter the escaped output. This can inadvertently reintroduce unescaped ampersands into the rendered textarea.
  • WordPress’s core approach uses esc_textarea() to ensure proper escaping. When necessary, decoding should occur before escaping (for example, using wp_specialchars_decode( $value, ENT_QUOTES )), which avoids bypassing built-in XSS protections.
  • Given the potential risk of exposing unsanitized characters, consider refactoring the code as suggested:
    - str_replace( '&amp;', '&', FrmAppHelper::esc_textarea( $this->field['value'] ) ) .
    + FrmAppHelper::esc_textarea( wp_specialchars_decode( $this->field['value'], ENT_QUOTES ) ) .

This approach aligns better with WordPress escaping best practices and minimizes potential security vulnerabilities.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
str_replace( '&amp;', '&', FrmAppHelper::esc_textarea( $this->field['value'] ) ) .
FrmAppHelper::esc_textarea( wp_specialchars_decode( $this->field['value'], ENT_QUOTES ) ) .

@AbdiTolesa AbdiTolesa changed the title Fix html entities display issue Fix less than character (<) display issue Feb 11, 2025
@Crabcyborg Crabcyborg requested a review from truongwp February 17, 2025 19:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant