User:Xybot/FixEscapes

From OpenStreetMap Wiki
Jump to: navigation, search

This is the Ruleset FixEscapes of the Xybot script

sub begin {
  my $me = shift;
  Data::Primitive->setCreator("FixEscapes");
  Data::Primitive->setComment('Fixing falsely escaped entities');
}

sub process {
  my ($me, $obj) = @_;

  my $resultstr = "";
  my $work = $obj;
  my $clone = undef;
  my $k;
  my $v;

  while (($k,$v) = each(%{$work->{"tags"}})) {
    my $key = $k;
    my $val = $v;
    $key =~ s/^\s*(.*?)\s*$/$1/;        # remove surrounding space in keys
    $val =~ s/^\s*(.*?)\s*$/$1/;        # remove surrounding space in values
    $val =~ s/\\{2,}/\\/g;              # remove falsely escaped backslashes (backslash has also to be escaped in perl)
    $val =~ s/\\+s/;/g;                 # remove falsely escaped semicolons (backslash has also to be escaped in perl)
    $val =~ s/&lt;/</g;                 # remove falsely escaped lesser than
    $val =~ s/&gt;/>/g;                 # remove falsely escaped greater than
    $val =~ s/&amp;/&/g;                # remove falsely escaped ampersands
    $val =~ s/&quot;/"/g;               # remove falsely excaped quotation marks
    $val =~ s/&apos;/'/g;               # remove falsely excaped apostrophe marks

    if ($val =~ /&(\w+?);/) {
      $obj->log(ref($obj), $work->{"id"}, "  NOTICE found html-entity '&".$1.";'", "");
    }

    # delete keys with empty values
    if ($val eq "") {
      $clone=$work->clone() unless defined($clone);
      delete $clone->{"tags"}->{$k};
      $resultstr .= sprintf " - deleting tag '%s=%s'", $k, $v,
      $work=$clone;
    } elsif ($k ne $key && $v ne $val) {
      $clone=$work->clone() unless defined($clone);
      delete $clone->{"tags"}->{$k};
      $clone->{"tags"}->{$key} = $val;
      $resultstr .= sprintf " - modifying tag '%s=%s' to '%s=%s'", $k, $v, $key, $val;
      $work=$clone;
    } elsif ($k ne $key) {
      $clone=$work->clone() unless defined($clone);
      delete $clone->{"tags"}->{$k};
      $clone->{"tags"}->{$key} = $v;
      $resultstr .= sprintf " - modifying key '%s' to '%s' value '%s'", $k, $key, $v;
      $work=$clone;
    } elsif ($v ne $val) {
      $clone=$work->clone() unless defined($clone);
      $clone->{"tags"}->{$k} = $val;
      $resultstr .= sprintf " - key '%s' modifying value '%s' to '%s'", $k, $v, $val;
      $work=$clone;
    }
  }
  $obj->log(ref($obj), $work->{"id"}, $resultstr, $obj->update($clone, $me)) if (defined($clone));
}