RTx-FillTicketData
view release on metacpan or search on metacpan
lib/RTx/FillTicketData.pm view on Meta::CPAN
my $old_md5_sum = ''; # avoid uninitialized warning
my $config;
my %dbh_for;
sub config { return $config; }
sub find_config_file {
RT->Config->Get('FillTicketDataSettingsFile');
}
sub read_config {
my $config_file = shift || find_config_file();
my $json_data = read_file($config_file);
my $md5_sum = md5_hex($json_data);
if ($md5_sum eq $old_md5_sum) {
$RT::Logger->debug("MD5 sum matches the old one ($md5_sum), leaving config alone");
return $config;
}
$RT::Logger->debug(
'New plugin configuration detected, re-initializing',
"old md5: $old_md5_sum, new md5: $md5_sum"
);
$old_md5_sum = $md5_sum;
$config = decode_json($json_data);
init_connections();
return $config;
}
sub read_file {
my $filename = shift;
local $/;
open my $FH, '<', $filename
or die "Could not open file $filename: $!";
return <$FH>;
}
# Re-initialize database connections
sub init_connections {
undef %dbh_for;
for my $db_id (keys %{ $config->{databases} }) {
$dbh_for{$db_id} = _connect_db($config->{databases}->{$db_id});
}
}
# Connect to a database using configuration from $db_config
sub _connect_db {
my $db_config = shift;
my $dsn = "dbi:$db_config->{type}:$db_config->{database}";
for my $field (qw(host port)) {
$dsn .= ";$field=$db_config->{$field}" if $db_config->{$field};
}
my %more_attrs;
given ($db_config->{type}) {
when ('mysql') {
%more_attrs = ( mysql_enable_utf8 => 1 );
}
when ('Pg') {
%more_attrs = ( pg_enable_utf8 => 1 );
}
}
my $dbh = DBI->connect(
$dsn,
$db_config->{username},
$db_config->{password},
{
RaiseError => 1,
PrintError => 1,
%more_attrs
},
);
$dbh->do('SET NAMES utf8') if $db_config->{type} ne 'SQLite';
return $dbh;
}
=head3 get_data
Returns data from configured sources
In: \%arg hash in the form
(
Object-RT::Ticket--CustomField-1-Values => $value1,
Object-RT::Ticket--CustomField-3-Values => $value3,
...
)
Out: \%content_of - hash of values from the configured sources for the same
fields as
=cut
sub get_data {
my $arg = shift;
# Re-read config on every request (to avoid restarts)
read_config();
# Detect whether we have key fields in the input
my %field_id_for;
my %key_field;
my $queue_id = delete $arg->{queue_id};
while (my ($key, $value) = each %$arg) {
$field_id_for{$key} = _get_field_id($key);
if ($value ne '__exists__') {
$key_field{ $field_id_for{$key} } = $value;
}
}
# Append Subject and Body
my %html_id_for = reverse %field_id_for, qw(Body Body Subject Subject);
if (!%key_field) {
warn 'no key field';
return { error => 'No key field' };
( run in 1.019 second using v1.01-cache-2.11-cpan-5b529ec07f3 )