1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2016 Best Practical Solutions, LLC
6 # <sales@bestpractical.com>
8 # (Except where explicitly superseded by other copyright notices)
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 # General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
30 # CONTRIBUTION SUBMISSION POLICY:
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
47 # END BPS TAGGED BLOCK }}}
49 package RT::Dashboard::Mailer;
54 use HTML::RewriteAttributes::Links;
55 use HTML::RewriteAttributes::Resources;
59 use RT::Interface::Web::Handler;
60 use RT::Interface::Web;
61 use File::Temp 'tempdir';
74 $RT::Logger->debug("Using time $args{Time} for dashboard generation");
76 my $from = $self->GetFrom();
77 $RT::Logger->debug("Sending email from $from");
79 # look through each user for her subscriptions
80 my $Users = RT::Users->new(RT->SystemUser);
81 $Users->LimitToPrivileged;
83 while (defined(my $user = $Users->Next)) {
84 if ($user->PrincipalObj->Disabled) {
85 $RT::Logger->debug("Skipping over " . $user->Name . " due to having a disabled account.");
89 my ($hour, $dow, $dom) = HourDowDomIn($args{Time}, $user->Timezone || RT->Config->Get('Timezone'));
91 $RT::Logger->debug("Checking ".$user->Name."'s subscriptions: hour $hour, dow $dow, dom $dom");
93 my $currentuser = RT::CurrentUser->new;
94 $currentuser->LoadByName($user->Name);
96 # look through this user's subscriptions, are any supposed to be generated
98 for my $subscription ($user->Attributes->Named('Subscription')) {
99 next unless $self->IsSubscriptionReady(
101 Subscription => $subscription,
103 LocalTime => [$hour, $dow, $dom],
106 my $email = $subscription->SubValue('Recipient')
107 || $user->EmailAddress;
110 $self->SendDashboard(
112 CurrentUser => $currentuser,
114 Subscription => $subscription,
119 $RT::Logger->error("Caught exception: $@");
122 my $counter = $subscription->SubValue('Counter') || 0;
123 $subscription->SetSubValues(Counter => $counter + 1)
124 unless $args{DryRun};
130 sub IsSubscriptionReady {
134 Subscription => undef,
136 LocalTime => [0, 0, 0],
140 return 1 if $args{All};
142 my $subscription = $args{Subscription};
144 my $counter = $subscription->SubValue('Counter') || 0;
146 my $sub_frequency = $subscription->SubValue('Frequency');
147 my $sub_hour = $subscription->SubValue('Hour');
148 my $sub_dow = $subscription->SubValue('Dow');
149 my $sub_dom = $subscription->SubValue('Dom');
150 my $sub_fow = $subscription->SubValue('Fow') || 1;
152 my ($hour, $dow, $dom) = @{ $args{LocalTime} };
154 $RT::Logger->debug("Checking against subscription " . $subscription->Id . " for " . $args{User}->Name . " with frequency $sub_frequency, hour $sub_hour, dow $sub_dow, dom $sub_dom, fow $sub_fow, counter $counter");
156 return 0 if $sub_frequency eq 'never';
159 return 0 if $sub_hour ne $hour;
161 # all we need is the correct hour for daily dashboards
162 return 1 if $sub_frequency eq 'daily';
164 if ($sub_frequency eq 'weekly') {
165 # correct day of week?
166 return 0 if $sub_dow ne $dow;
168 # does it match the "every N weeks" clause?
169 return 1 if $counter % $sub_fow == 0;
171 $subscription->SetSubValues(Counter => $counter + 1)
172 unless $args{DryRun};
176 # if monthly, correct day of month?
177 if ($sub_frequency eq 'monthly') {
178 return $sub_dom == $dom;
181 # monday through friday
182 if ($sub_frequency eq 'm-f') {
183 return 0 if $dow eq 'Sunday' || $dow eq 'Saturday';
187 $RT::Logger->debug("Invalid subscription frequency $sub_frequency for " . $args{User}->Name);
189 # unknown frequency type, bail out
194 RT->Config->Get('DashboardAddress') || RT->Config->Get('OwnerEmail')
200 CurrentUser => undef,
202 Subscription => undef,
207 my $currentuser = $args{CurrentUser};
208 my $subscription = $args{Subscription};
210 my $rows = $subscription->SubValue('Rows');
212 my $DashboardId = $subscription->SubValue('DashboardId');
214 my $dashboard = RT::Dashboard->new($currentuser);
215 my ($ok, $msg) = $dashboard->LoadById($DashboardId);
217 # failed to load dashboard. perhaps it was deleted or it changed privacy
219 $RT::Logger->warning("Unable to load dashboard $DashboardId of subscription ".$subscription->Id." for user ".$currentuser->Name.": $msg");
220 return $self->ObsoleteSubscription(
222 Subscription => $subscription,
226 $RT::Logger->debug('Generating dashboard "'.$dashboard->Name.'" for user "'.$currentuser->Name.'":');
230 Dashboard: @{[ $dashboard->Name ]}
231 User: @{[ $currentuser->Name ]} <$args{Email}>
236 local $HTML::Mason::Commands::session{CurrentUser} = $currentuser;
237 local $HTML::Mason::Commands::r = RT::Dashboard::FakeRequest->new;
239 my $content = RunComponent(
240 '/Dashboards/Render.html',
241 id => $dashboard->Id,
245 if ( RT->Config->Get('EmailDashboardRemove') ) {
246 for ( RT->Config->Get('EmailDashboardRemove') ) {
251 $content = ScrubContent($content);
253 $RT::Logger->debug("Got ".length($content)." characters of output.");
255 $content = HTML::RewriteAttributes::Links->rewrite(
257 RT->Config->Get('WebURL') . 'Dashboards/Render.html',
260 $self->EmailDashboard(
262 Dashboard => $dashboard,
267 sub ObsoleteSubscription {
272 Subscription => undef,
273 CurrentUser => undef,
277 my $subscription = $args{Subscription};
279 my $ok = RT::Interface::Email::SendEmailUsingTemplate(
282 Template => 'Error: Missing dashboard',
284 SubscriptionObj => $subscription,
287 'X-RT-Dashboard-Subscription-Id' => $subscription->Id,
288 'X-RT-Dashboard-Id' => $subscription->SubValue('DashboardId'),
292 # only delete the subscription if the email looks like it went through
294 my ($deleted, $msg) = $subscription->Delete();
296 $RT::Logger->debug("Deleted an obsolete subscription: $msg");
299 $RT::Logger->warning("Unable to delete an obsolete subscription: $msg");
303 $RT::Logger->warning("Unable to notify ".$args{CurrentUser}->Name." of an obsolete subscription");
310 CurrentUser => undef,
313 Subscription => undef,
318 my $subscription = $args{Subscription};
319 my $dashboard = $args{Dashboard};
320 my $currentuser = $args{CurrentUser};
321 my $email = $args{Email};
323 my $frequency = $subscription->SubValue('Frequency');
325 my %frequency_lookup = (
326 'm-f' => 'Weekday', # loc
327 'daily' => 'Daily', # loc
328 'weekly' => 'Weekly', # loc
329 'monthly' => 'Monthly', # loc
330 'never' => 'Never', # loc
333 my $frequency_display = $frequency_lookup{$frequency}
336 my $subject = sprintf '[%s] ' . RT->Config->Get('DashboardSubject'),
337 RT->Config->Get('rtname'),
338 $currentuser->loc($frequency_display),
341 my $entity = $self->BuildEmail(
347 $entity->head->replace('X-RT-Dashboard-Id', $dashboard->Id);
348 $entity->head->replace('X-RT-Dashboard-Subscription-Id', $subscription->Id);
350 $RT::Logger->debug('Mailing dashboard "'.$dashboard->Name.'" to user '.$currentuser->Name." <$email>");
352 my $ok = RT::Interface::Email::SendEmail(
353 %{ RT->Config->Get('Crypt')->{'Dashboards'} || {} },
358 $RT::Logger->error("Failed to email dashboard to user ".$currentuser->Name." <$email>");
362 $RT::Logger->debug("Done sending dashboard to ".$currentuser->Name." <$email>");
378 my $content = HTML::RewriteAttributes::Resources->rewrite($args{Content}, sub {
381 # already attached this object
382 return "cid:$cid_of{$uri}" if $cid_of{$uri};
384 my ($data, $filename, $mimetype, $encoding) = GetResource($uri);
385 return $uri unless defined $data;
387 $cid_of{$uri} = time() . $$ . int(rand(1e6));
389 # Encode textual data in UTF-8, and downgrade (treat
390 # codepoints as codepoints, and ensure the UTF-8 flag is
391 # off) everything else.
393 if ( $mimetype =~ m{text/} ) {
394 $data = Encode::encode( "UTF-8", $data );
395 @extra = ( Charset => "UTF-8" );
397 utf8::downgrade( $data, 1 ) or $RT::Logger->warning("downgrade $data failed");
400 push @parts, MIME::Entity->build(
404 Encoding => $encoding,
405 Disposition => 'inline',
406 Name => RT::Interface::Email::EncodeToMIME( String => $filename ),
407 'Content-Id' => $cid_of{$uri},
411 return "cid:$cid_of{$uri}";
415 my ($content) = GetResource($uri);
416 return defined $content ? $content : "";
421 my $entity = MIME::Entity->build(
422 From => Encode::encode("UTF-8", $args{From}),
423 To => Encode::encode("UTF-8", $args{To}),
424 Subject => RT::Interface::Email::EncodeToMIME( String => $args{Subject} ),
425 Type => "multipart/mixed",
431 Data => Encode::encode("UTF-8", $content),
432 Disposition => 'inline',
433 Encoding => "base64",
436 for my $part (@parts) {
437 $entity->add_part($part);
440 $entity->make_singlepart;
452 $RT::Logger->debug("Creating Mason object.");
454 # user may not have permissions on the data directory, so create a
456 $data_dir = tempdir(CLEANUP => 1);
458 $mason = HTML::Mason::Interp->new(
459 RT::Interface::Web::Handler->DefaultHandlerArgs,
460 out_method => \$outbuf,
461 autohandler_name => '', # disable forced login and more
462 data_dir => $data_dir,
464 $mason->set_escape( h => \&RT::Interface::Web::EscapeHTML );
465 $mason->set_escape( u => \&RT::Interface::Web::EscapeURI );
466 $mason->set_escape( j => \&RT::Interface::Web::EscapeJS );
484 $scrubber = HTML::Scrubber->new;
485 # Allow everything by default, except JS attributes ...
489 map { ("on$_" => 0) }
490 qw(blur change click dblclick error focus keydown keypress keyup load
491 mousedown mousemove mouseout mouseover mouseup reset select submit unload)
495 $scrubber->deny('script');
502 return _scrubber->scrub($content);
513 my $key = "$now $tz";
514 return @{$cache{$key}} if exists $cache{$key};
516 my ($hour, $dow, $dom);
519 local $ENV{'TZ'} = $tz;
520 ## Using POSIX::tzset fixes a bug where the TZ environment variable
523 (undef, undef, $hour, $dom, undef, undef, $dow) = localtime($now);
525 tzset(); # return back previous value
528 if length($hour) == 1;
529 $dow = (qw/Sunday Monday Tuesday Wednesday Thursday Friday Saturday/)[$dow];
531 return @{$cache{$key}} = ($hour, $dow, $dom);
536 my $uri = URI->new(shift);
537 my ($content, $content_type, $filename, $mimetype, $encoding);
539 # Avoid trying to inline any remote URIs. We absolutified all URIs
540 # using WebURL in SendDashboard() above, so choose the simpler match on
541 # that rather than testing a bunch of URI accessors.
542 my $WebURL = RT->Config->Get("WebURL");
543 return unless $uri =~ /^\Q$WebURL/;
545 $RT::Logger->debug("Getting resource $uri");
547 # strip out the equivalent of WebURL, so we start at the correct /
548 my $path = $uri->path;
549 my $webpath = RT->Config->Get('WebPath');
550 $path =~ s/^\Q$webpath//;
552 # add a leading / if needed
554 unless $path =~ m{^/};
556 # Try the static handler first for non-Mason CSS, JS, etc.
557 my $res = RT::Interface::Web::Handler->GetStatic($path);
558 if ($res->is_success) {
559 RT->Logger->debug("Fetched '$path' from the static handler");
560 $content = $res->decoded_content;
561 $content_type = $res->headers->content_type;
563 # Try it through Mason instead...
564 $HTML::Mason::Commands::r->path_info($path);
566 # grab the query arguments
567 my %args = map { $_ => [ map {Encode::decode("UTF-8",$_)}
568 $uri->query_param($_) ] } $uri->query_param;
569 # Convert empty and single element arrayrefs to a non-ref scalar
570 @$_ < 2 and $_ = $_->[0]
573 $RT::Logger->debug("Running component '$path'");
574 $content = RunComponent($path, %args);
576 $content_type = $HTML::Mason::Commands::r->content_type;
579 # guess at the filename from the component name
580 $filename = $1 if $path =~ m{^.*/(.*?)$};
582 # the rest of this was taken from Email::MIME::CreateHTML::Resolver::LWP
583 ($mimetype, $encoding) = MIME::Types::by_suffix($filename);
586 $mimetype = $content_type;
588 # strip down to just a MIME type
589 $mimetype = $1 if $mimetype =~ /(\S+);\s*charset=(.*)$/;
592 #If all else fails then some conservative and general-purpose defaults are:
593 $mimetype ||= 'application/octet-stream';
594 $encoding ||= 'base64';
596 $RT::Logger->debug("Resource $uri: length=".length($content)." filename='$filename' mimetype='$mimetype', encoding='$encoding'");
598 return ($content, $filename, $mimetype, $encoding);
603 package RT::Dashboard::FakeRequest;
604 sub new { bless {}, shift }
605 sub header_out { return undef }
606 sub headers_out { wantarray ? () : {} }
607 sub err_headers_out { wantarray ? () : {} }
610 $self->{content_type} = shift if @_;
611 return $self->{content_type};
615 $self->{path_info} = shift if @_;
616 return $self->{path_info};
620 RT::Base->_ImportOverlays();