#!/usr/bin/perl
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2025 Best Practical Solutions, LLC
#                                          <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}
use strict;
use warnings;

# fix lib paths, some may be relative
BEGIN {    # BEGIN RT CMD BOILERPLATE
    require File::Spec;
    require Cwd;
    my @libs = ( "lib", "local/lib" );
    my $bin_path;

    for my $lib (@libs) {
        unless ( File::Spec->file_name_is_absolute($lib) ) {
            $bin_path
                ||= ( File::Spec->splitpath( Cwd::abs_path(__FILE__) ) )[1];
            $lib = File::Spec->catfile( $bin_path, File::Spec->updir, $lib );
        }
        unshift @INC, $lib;
    }

}

# Read in the options
my %opts;
use Getopt::Long;
GetOptions( \%opts, "help|h", "search=s", "replacement=s", 'tickets=s', 'transactions=s', 'skip-headers', 'skip-content' );

if ( $opts{'help'} || !$opts{'search'} ) {
    require Pod::Usage;
    print Pod::Usage::pod2usage( -verbose => 2 );
    exit;
}

use RT -init;

my $replacement = $opts{'replacement'} || '';
my $headers     = $opts{'skip-headers'} ? 0 : 1;
my $content     = $opts{'skip-content'} ? 0 : 1;

my $search = $opts{'search'};

my $attachments = RT::Attachments->new( RT->SystemUser );
if ( $opts{tickets} ) {
    my @tickets = split /\s*,\s*/, $opts{tickets};

    my $txn_alias   = $attachments->TransactionAlias;
    $attachments->Limit(
        ALIAS => $txn_alias,
        FIELD => 'ObjectType',
        VALUE => 'RT::Ticket',
    );
    my $ticket_alias = $attachments->Join(
        ALIAS1 => $txn_alias,
        FIELD1 => 'ObjectId',
        TABLE2 => 'Tickets',
        FIELD2 => 'id',
    );
    $attachments->Limit(
        ALIAS    => $ticket_alias,
        FIELD    => 'EffectiveId',
        VALUE    => \@tickets,
        OPERATOR => 'IN',
    );
}

if ( $opts{'transactions'} ) {
    my @transactions = split /\s*,\s*/, $opts{'transactions'};

    $attachments->Limit(
        FIELD    => 'TransactionId',
        VALUE    => \@transactions,
        OPERATOR => 'IN',
    );
}

my ( $ret, $msg ) = $attachments->ReplaceAttachments(
    Headers     => $headers,
    Content     => $content,
    Search      => Encode::decode( 'UTF-8', $search ),
    Replacement => Encode::decode( 'UTF-8', $replacement ),
    $opts{tickets} || $opts{transactions} ? ( FilterBySearchString => 0 ) : (),
);
print STDERR $msg . "\n";


=head1 NAME

rt-munge-attachments - Remove or replace strings in attachment records

=head1 SYNOPSIS

    rt-munge-attachments --search="user1@example.com" --replace="removed-user@example.com"

=cut

=head1 DESCRIPTION

In RT, "attachments" contain all correspondence on tickets, not just file-based
attachments. Although attachments are normally not modified by RT once created,
this script provides a way to change or remove personalized data like email
addresses that might be contained in the headers or bodies of RT attachment
records. This allows admins to comply with GDPR regulations, but retain ticket
histories with remaining non-personal information.

A transaction is recorded when this script modifies content so there is a record that
something was changed on the ticket. Details of the change are not recorded since
the values would likely contain personal information which the script was run to
remove.

If modifying ticket history violates audit policies, admins should not use this
script.

=head1 OPTIONS

=over

=item --search=SEARCH

Provide a string to search the header and content columns in the attachments table.
If a match is found the content will be removed unless a replacement is provided.

=item --replace=REPLACEMENT

Provide a string to replace the value matched by the search.

=item --tickets=1,2,3

Limit attachments to the specified tickets. Note that if tickets or transactions
are not specified, RT will pre-filter attachments by the search string use SQL,
which might bypass attachments of which contents are encoded(like
base64). Use this option to prevent the pre-filter behavior.

=item --transactions=123,456,7

Limit attachments to the specified transactions. If specified the default pre-filtering
will be prevented. This option can work alongside the --tickets flag.

=item --skip-headers

By default headers are also munged, to disable munging of headers set the
--skip-headers flag.

=item --skip-content

By default transaction content is munged, to disable munging of content set the
--skip-content flag.

=back
