Local.pm 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. package Cpanel::iContact::Provider::Local;
  2. use strict;
  3. use warnings;
  4. use parent 'Cpanel::iContact::Provider';
  5. use Try::Tiny;
  6. =encoding utf-8
  7. =head1 NAME
  8. Cpanel::iContact::Provider::Local - Backend for the Local iContact module
  9. =head1 SYNOPSIS
  10. use Cpanel::iContact::Provider::Local;
  11. my $notifier = Cpanel::iContact::Provider::Local->new();
  12. $notifier->send();
  13. =head1 DESCRIPTION
  14. Provide backend accessor for the Local iContact module.
  15. =cut
  16. =head2 send
  17. Sends off the notification over to /var/cpanel/iContact
  18. =over 2
  19. =item Input
  20. =over 3
  21. None
  22. =back
  23. =item Output
  24. =over 3
  25. Truthy value on success, exception on failure.
  26. =back
  27. =back
  28. =cut
  29. our $DIR = '/var/cpanel/iContact_notices';
  30. sub send {
  31. my ($self) = @_;
  32. my $args_hr = $self->{'args'};
  33. my $contact_hr = $self->{'contact'};
  34. my @errs;
  35. my $subject = $args_hr->{'subject'};
  36. my $text = ${ $args_hr->{'text_body'} };
  37. my $html = ${ $args_hr->{'html_body'} };
  38. # Send it
  39. my $time = time;
  40. $time =~ tr/ /-/;
  41. my $user = getpwuid($<);
  42. my $file = "$DIR/$user/$time.json";
  43. try {
  44. # Make the dir if it doesn't exist
  45. if( !-d "$DIR/$user" ) {
  46. my $path = '/';
  47. foreach my $component ( split( /\//, "$DIR/$user" ) ) {
  48. local $!;
  49. $path .= "$component/";
  50. mkdir( $path ) || do {
  51. die "Couldn't create $path: $!" if int $! != 17; # EEXISTS
  52. };
  53. }
  54. }
  55. require Cpanel::JSON::XS;
  56. open( my $fh, ">", $file ) || die "Couldn't open '$file': $!";
  57. print $fh Cpanel::JSON::XS::encode_json( { 'subject' => $subject, 'text' => $text, 'html' => $html } );
  58. close $fh;
  59. }
  60. catch {
  61. require Cpanel::Exception;
  62. die Cpanel::Exception::create(
  63. 'ConnectionFailed',
  64. 'The system failed to save the message to “[_1]” due to an error: [_2]',
  65. [ $file, $_ ]
  66. );
  67. };
  68. return 1;
  69. }
  70. sub reap_older_than {
  71. my ($timestamp) = @_;
  72. return () unless -d $DIR;
  73. opendir(my $dh, $DIR) || die "Can't opendir $DIR: $!";
  74. my @actual_files = grep { !/^\./ && -f "$DIR/$_" } readdir($dh);
  75. closedir $dh;
  76. my %files_by_age = ();
  77. @files_by_age{@actual_files} = map { (stat "$DIR/$_")[9] } @actual_files;
  78. my @files_to_kill = grep { $files_by_age{$_} < $timestamp } @actual_files;
  79. foreach my $goner (@files_to_kill) { unlink "$DIR/$goner" or warn "Could not delete $DIR/$goner!"; }
  80. return @files_to_kill;
  81. }
  82. 1;