1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2012 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';
72 $RT::Logger->debug("Using time $args{Time} for dashboard generation");
74 my $from = $self->GetFrom();
75 $RT::Logger->debug("Sending email from $from");
77 # look through each user for her subscriptions
78 my $Users = RT::Users->new(RT->SystemUser);
79 $Users->LimitToPrivileged;
81 while (defined(my $user = $Users->Next)) {
82 if ($user->PrincipalObj->Disabled) {
83 $RT::Logger->debug("Skipping over " . $user->Name . " due to having a disabled account.");
87 my ($hour, $dow, $dom) = HourDowDomIn($args{Time}, $user->Timezone || RT->Config->Get('Timezone'));
89 $RT::Logger->debug("Checking ".$user->Name."'s subscriptions: hour $hour, dow $dow, dom $dom");
91 my $currentuser = RT::CurrentUser->new;
92 $currentuser->LoadByName($user->Name);
94 # look through this user's subscriptions, are any supposed to be generated
96 for my $subscription ($user->Attributes->Named('Subscription')) {
97 next unless $self->IsSubscriptionReady(
99 Subscription => $subscription,
101 LocalTime => [$hour, $dow, $dom],
104 my $email = $subscription->SubValue('Recipient')
105 || $user->EmailAddress;
108 $self->SendDashboard(
110 CurrentUser => $currentuser,
112 Subscription => $subscription,
117 $RT::Logger->error("Caught exception: $@");
120 my $counter = $subscription->SubValue('Counter') || 0;
121 $subscription->SetSubValues(Counter => $counter + 1)
122 unless $args{DryRun};
128 sub IsSubscriptionReady {
132 Subscription => undef,
134 LocalTime => [0, 0, 0],
138 return 1 if $args{All};
140 my $subscription = $args{Subscription};
142 my $counter = $subscription->SubValue('Counter') || 0;
144 my $sub_frequency = $subscription->SubValue('Frequency');
145 my $sub_hour = $subscription->SubValue('Hour');
146 my $sub_dow = $subscription->SubValue('Dow');
147 my $sub_dom = $subscription->SubValue('Dom');
148 my $sub_fow = $subscription->SubValue('Fow');
150 my ($hour, $dow, $dom) = @{ $args{LocalTime} };
152 $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");
154 return 0 if $sub_frequency eq 'never';
157 return 0 if $sub_hour ne $hour;
159 # all we need is the correct hour for daily dashboards
160 return 1 if $sub_frequency eq 'daily';
162 if ($sub_frequency eq 'weekly') {
163 # correct day of week?
164 return 0 if $sub_dow ne $dow;
166 # does it match the "every N weeks" clause?
167 $sub_fow = 1 if !$sub_fow;
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 $RT::Logger->debug("Got ".length($content)." characters of output.");
253 $content = HTML::RewriteAttributes::Links->rewrite(
255 RT->Config->Get('WebURL') . 'Dashboards/Render.html',
258 $self->EmailDashboard(
260 Dashboard => $dashboard,
265 sub ObsoleteSubscription {
270 Subscription => undef,
271 CurrentUser => undef,
275 my $subscription = $args{Subscription};
277 my $ok = RT::Interface::Email::SendEmailUsingTemplate(
280 Template => 'Error: Missing dashboard',
282 SubscriptionObj => $subscription,
285 'X-RT-Dashboard-Subscription-Id' => $subscription->Id,
286 'X-RT-Dashboard-Id' => $subscription->SubValue('DashboardId'),
290 # only delete the subscription if the email looks like it went through
292 my ($deleted, $msg) = $subscription->Delete();
294 $RT::Logger->debug("Deleted an obsolete subscription: $msg");
297 $RT::Logger->warning("Unable to delete an obsolete subscription: $msg");
301 $RT::Logger->warning("Unable to notify ".$args{CurrentUser}->Name." of an obsolete subscription");
308 CurrentUser => undef,
311 Subscription => undef,
316 my $subscription = $args{Subscription};
317 my $dashboard = $args{Dashboard};
318 my $currentuser = $args{CurrentUser};
319 my $email = $args{Email};
321 my $frequency = $subscription->SubValue('Frequency');
323 my %frequency_lookup = (
324 'm-f' => 'Weekday', # loc
325 'daily' => 'Daily', # loc
326 'weekly' => 'Weekly', # loc
327 'monthly' => 'Monthly', # loc
328 'never' => 'Never', # loc
331 my $frequency_display = $frequency_lookup{$frequency}
334 my $subject = sprintf '[%s] ' . RT->Config->Get('DashboardSubject'),
335 RT->Config->Get('rtname'),
336 $currentuser->loc($frequency_display),
339 my $entity = $self->BuildEmail(
345 $entity->head->replace('X-RT-Dashboard-Id', $dashboard->Id);
346 $entity->head->replace('X-RT-Dashboard-Subscription-Id', $subscription->Id);
348 $RT::Logger->debug('Mailing dashboard "'.$dashboard->Name.'" to user '.$currentuser->Name." <$email>");
350 my $ok = RT::Interface::Email::SendEmail(
355 $RT::Logger->error("Failed to email dashboard to user ".$currentuser->Name." <$email>");
359 $RT::Logger->debug("Done sending dashboard to ".$currentuser->Name." <$email>");
375 my $content = HTML::RewriteAttributes::Resources->rewrite($args{Content}, sub {
378 # already attached this object
379 return "cid:$cid_of{$uri}" if $cid_of{$uri};
381 $cid_of{$uri} = time() . $$ . int(rand(1e6));
382 my ($data, $filename, $mimetype, $encoding) = GetResource($uri);
384 # downgrade non-text strings, because all strings are utf8 by
385 # default, which is wrong for non-text strings.
386 if ( $mimetype !~ m{text/} ) {
387 utf8::downgrade( $data, 1 ) or $RT::Logger->warning("downgrade $data failed");
390 push @parts, MIME::Entity->build(
394 Encoding => $encoding,
395 Disposition => 'inline',
397 'Content-Id' => $cid_of{$uri},
400 return "cid:$cid_of{$uri}";
404 my ($content) = GetResource($uri);
410 my $entity = MIME::Entity->build(
413 Subject => $args{Subject},
414 Type => "multipart/mixed",
418 Data => Encode::encode_utf8($content),
421 Disposition => 'inline',
424 for my $part (@parts) {
425 $entity->add_part($part);
438 $RT::Logger->debug("Creating Mason object.");
440 # user may not have permissions on the data directory, so create a
442 $data_dir = tempdir(CLEANUP => 1);
444 $mason = HTML::Mason::Interp->new(
445 RT::Interface::Web::Handler->DefaultHandlerArgs,
446 out_method => \$outbuf,
447 autohandler_name => '', # disable forced login and more
448 data_dir => $data_dir,
450 $mason->set_escape( h => \&RT::Interface::Web::EscapeUTF8 );
451 $mason->set_escape( u => \&RT::Interface::Web::EscapeURI );
452 $mason->set_escape( j => \&RT::Interface::Web::EscapeJS );
472 my $key = "$now $tz";
473 return @{$cache{$key}} if exists $cache{$key};
475 my ($hour, $dow, $dom);
478 local $ENV{'TZ'} = $tz;
479 ## Using POSIX::tzset fixes a bug where the TZ environment variable
482 (undef, undef, $hour, $dom, undef, undef, $dow) = localtime($now);
484 tzset(); # return back previous value
487 if length($hour) == 1;
488 $dow = (qw/Sunday Monday Tuesday Wednesday Thursday Friday Saturday/)[$dow];
490 return @{$cache{$key}} = ($hour, $dow, $dom);
495 my $uri = URI->new(shift);
496 my ($content, $filename, $mimetype, $encoding);
498 $RT::Logger->debug("Getting resource $uri");
500 # strip out the equivalent of WebURL, so we start at the correct /
501 my $path = $uri->path;
502 my $webpath = RT->Config->Get('WebPath');
503 $path =~ s/^\Q$webpath//;
505 # add a leading / if needed
507 unless $path =~ m{^/};
509 $HTML::Mason::Commands::r->path_info($path);
511 # grab the query arguments
513 for (split /&/, ($uri->query||'')) {
514 my ($k, $v) = /^(.*?)=(.*)$/
515 or die "Unable to parse query parameter '$_'";
517 for ($k, $v) { s/%(..)/chr hex $1/ge }
519 # no value yet, simple key=value
520 if (!exists $args{$k}) {
523 # already have key=value, need to upgrade it to key=[value1, value2]
524 elsif (!ref($args{$k})) {
525 $args{$k} = [$args{$k}, $v];
527 # already key=[value1, value2], just add the new value
529 push @{ $args{$k} }, $v;
533 $RT::Logger->debug("Running component '$path'");
534 $content = RunComponent($path, %args);
536 # guess at the filename from the component name
537 $filename = $1 if $path =~ m{^.*/(.*?)$};
539 # the rest of this was taken from Email::MIME::CreateHTML::Resolver::LWP
540 ($mimetype, $encoding) = MIME::Types::by_suffix($filename);
542 my $content_type = $HTML::Mason::Commands::r->content_type;
544 $mimetype = $content_type;
546 # strip down to just a MIME type
547 $mimetype = $1 if $mimetype =~ /(\S+);\s*charset=(.*)$/;
550 #If all else fails then some conservative and general-purpose defaults are:
551 $mimetype ||= 'application/octet-stream';
552 $encoding ||= 'base64';
554 $RT::Logger->debug("Resource $uri: length=".length($content)." filename='$filename' mimetype='$mimetype', encoding='$encoding'");
556 return ($content, $filename, $mimetype, $encoding);
561 package RT::Dashboard::FakeRequest;
562 sub new { bless {}, shift }
563 sub header_out { shift }
564 sub headers_out { shift }
567 $self->{content_type} = shift if @_;
568 return $self->{content_type};
572 $self->{path_info} = shift if @_;
573 return $self->{path_info};
577 RT::Base->_ImportOverlays();