Skip to content

CommentStorageController::preSave() unconditionally overwrites hostname with current request IP #7151

@izmeez

Description

@izmeez

Description of the bug

In core comment module, CommentStorageController::preSave() in comment.entity.inc unconditionally sets $comment->hostname to ip_address() (the current HTTP request's client IP) on every comment save, regardless of whether a hostname value has already been set on the comment object.

This means it is impossible to programmatically create or import a comment with a specific hostname value — any value set on $comment->hostname before calling comment_save() is silently discarded and replaced with the current request IP.

Steps To Reproduce

To reproduce the behavior:

  1. In any module, create a comment programmatically with a specific hostname:
$comment = entity_create('comment', array(
  'nid'      => 1,
  'uid'      => 0,
  'hostname' => '192.168.1.100',
  'subject'  => 'Test',
  'node_type' => 'comment_node_post',
));
comment_save($comment);
  1. Check the hostname column in the {comment} table for the saved comment.

Expected behavior

hostname is 192.168.1.100 as set on the object before save.

Actual result

hostname contains the IP address of the current HTTP request, not 192.168.1.100.

Root cause

In CommentStorageController::preSave():

$comment->hostname = ip_address();

This line runs unconditionally, overwriting any previously set value.

Proposed fix

Only set hostname from the request IP when no hostname has already been provided:

$comment->hostname = $comment->hostname ?: ip_address();

Or equivalently:

if (empty($comment->hostname)) {
  $comment->hostname = ip_address();
}

This preserves the existing behaviour for comments submitted via the normal comment form (where hostname is not set before save) while allowing programmatic comment creation to specify a hostname.

Impact

Any module that creates or imports comments programmatically and needs to preserve the original commenter's IP address is affected. This includes comment migration and import tools such as the Feeds Comment Processor contrib module, which currently requires a db_update() workaround after every comment_save() call to correct the hostname.

Additional information

Add any other information that could help, such as:

  • Backdrop CMS version: 1.34.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions