3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 use C4
::Koha
qw(GetAuthorisedValueByCode);
28 use C4
::Members
::Attributes
qw(GetBorrowerAttributes);
34 use Date
::Calc
qw( Add_Delta_Days );
38 use vars
qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
42 # set the version for version checking
43 $VERSION = 3.07.00.049;
46 &GetLetters &GetPreparedLetter &GetWrappedLetter &addalert &getalert &delalert &findrelatedto &SendAlerts &GetPrintMessages &GetMessageTransportTypes
52 C4::Letters - Give functions for Letters management
60 "Letters" is the tool used in Koha to manage informations sent to the patrons and/or the library. This include some cron jobs like
61 late issues, as well as other tasks like sending a mail to users that have subscribed to a "serial issue alert" (= being warned every time a new issue has arrived at the library)
63 Letters are managed through "alerts" sent by Koha on some events. All "alert" related functions are in this module too.
65 =head2 GetLetters([$category])
67 $letters = &GetLetters($category);
68 returns informations about letters.
69 if needed, $category filters for letters given category
70 Create a letter selector with the following code
74 my $letters = GetLetters($cat);
76 foreach my $thisletter (keys %$letters) {
77 my $selected = 1 if $thisletter eq $letter;
80 selected => $selected,
81 lettername => $letters->{$thisletter},
83 push @letterloop, \%row;
85 $template->param(LETTERLOOP => \@letterloop);
89 <select name="letter">
90 <option value="">Default</option>
91 <!-- TMPL_LOOP name="LETTERLOOP" -->
92 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="lettername" --></option>
100 # returns a reference to a hash of references to ALL letters...
103 my $dbh = C4
::Context
->dbh;
106 SELECT * FROM letter WHERE 1
108 $query .= q{ AND module = ? } if defined $cat;
109 $query .= q{ GROUP BY code ORDER BY name};
110 $sth = $dbh->prepare($query);
111 $sth->execute((defined $cat ?
$cat : ()));
113 while ( my $letter = $sth->fetchrow_hashref ) {
114 $letters{ $letter->{'code'} } = $letter->{'name'};
119 # FIXME: using our here means that a Plack server will need to be
120 # restarted fairly regularly when working with this routine.
121 # A better option would be to use Koha::Cache and use a cache
122 # that actually works in a persistent environment, but as a
123 # short-term fix, our will work.
126 my ( $module, $code, $branchcode, $message_transport_type ) = @_;
127 $message_transport_type ||= 'email';
130 if ( C4
::Context
->preference('IndependentBranches')
132 and C4
::Context
->userenv ) {
134 $branchcode = C4
::Context
->userenv->{'branch'};
138 if ( my $l = $letter{$module}{$code}{$branchcode}{$message_transport_type} ) {
139 return { %$l }; # deep copy
142 my $dbh = C4
::Context
->dbh;
143 my $sth = $dbh->prepare(q{
146 WHERE module=? AND code=? AND (branchcode = ? OR branchcode = '') AND message_transport_type = ?
147 ORDER BY branchcode DESC LIMIT 1
149 $sth->execute( $module, $code, $branchcode, $message_transport_type );
150 my $line = $sth->fetchrow_hashref
152 $line->{'content-type'} = 'text/html; charset="UTF-8"' if $line->{is_html
};
153 $letter{$module}{$code}{$branchcode}{$message_transport_type} = $line;
157 =head2 addalert ($borrowernumber, $type, $externalid)
160 - $borrowernumber : the number of the borrower subscribing to the alert
161 - $type : the type of alert.
162 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
164 create an alert and return the alertid (primary key)
169 my ( $borrowernumber, $type, $externalid ) = @_;
170 my $dbh = C4
::Context
->dbh;
173 "insert into alert (borrowernumber, type, externalid) values (?,?,?)");
174 $sth->execute( $borrowernumber, $type, $externalid );
176 # get the alert number newly created and return it
177 my $alertid = $dbh->{'mysql_insertid'};
181 =head2 delalert ($alertid)
184 - alertid : the alert id
190 my $alertid = shift or die "delalert() called without valid argument (alertid)"; # it's gonna die anyway.
191 $debug and warn "delalert: deleting alertid $alertid";
192 my $sth = C4
::Context
->dbh->prepare("delete from alert where alertid=?");
193 $sth->execute($alertid);
196 =head2 getalert ([$borrowernumber], [$type], [$externalid])
199 - $borrowernumber : the number of the borrower subscribing to the alert
200 - $type : the type of alert.
201 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
202 all parameters NON mandatory. If a parameter is omitted, the query is done without the corresponding parameter. For example, without $externalid, returns all alerts for a borrower on a topic.
207 my ( $borrowernumber, $type, $externalid ) = @_;
208 my $dbh = C4
::Context
->dbh;
209 my $query = "SELECT a.*, b.branchcode FROM alert a JOIN borrowers b USING(borrowernumber) WHERE";
211 if ($borrowernumber and $borrowernumber =~ /^\d+$/) {
212 $query .= " borrowernumber=? AND ";
213 push @bind, $borrowernumber;
216 $query .= " type=? AND ";
220 $query .= " externalid=? AND ";
221 push @bind, $externalid;
223 $query =~ s/ AND $//;
224 my $sth = $dbh->prepare($query);
225 $sth->execute(@bind);
226 return $sth->fetchall_arrayref({});
229 =head2 findrelatedto($type, $externalid)
232 - $type : the type of alert
233 - $externalid : the id of the "object" to query
235 In the table alert, a "id" is stored in the externalid field. This "id" is related to another table, depending on the type of the alert.
236 When type=issue, the id is related to a subscriptionid and this sub returns the name of the biblio.
241 # When type=virtual, the id is related to a virtual shelf and this sub returns the name of the sub
244 my $type = shift or return;
245 my $externalid = shift or return;
246 my $q = ($type eq 'issue' ) ?
247 "select title as result from subscription left join biblio on subscription.biblionumber=biblio.biblionumber where subscriptionid=?" :
248 ($type eq 'borrower') ?
249 "select concat(firstname,' ',surname) from borrowers where borrowernumber=?" : undef;
251 warn "findrelatedto(): Illegal type '$type'";
254 my $sth = C4
::Context
->dbh->prepare($q);
255 $sth->execute($externalid);
256 my ($result) = $sth->fetchrow;
263 - $type : the type of alert
264 - $externalid : the id of the "object" to query
265 - $letter_code : the letter to send.
267 send an alert to all borrowers having put an alert on a given subject.
272 my ( $type, $externalid, $letter_code ) = @_;
273 my $dbh = C4
::Context
->dbh;
274 if ( $type eq 'issue' ) {
276 # prepare the letter...
277 # search the biblionumber
280 "SELECT biblionumber FROM subscription WHERE subscriptionid=?");
281 $sth->execute($externalid);
282 my ($biblionumber) = $sth->fetchrow
283 or warn( "No subscription for '$externalid'" ),
287 # find the list of borrowers to alert
288 my $alerts = getalert
( '', 'issue', $externalid );
291 my $borinfo = C4
::Members
::GetMember
('borrowernumber' => $_->{'borrowernumber'});
292 my $email = $borinfo->{email
} or next;
294 # warn "sending issues...";
295 my $userenv = C4
::Context
->userenv;
296 my $branchdetails = GetBranchDetail
($_->{'branchcode'});
297 my $letter = GetPreparedLetter
(
299 letter_code
=> $letter_code,
300 branchcode
=> $userenv->{branch
},
302 'branches' => $_->{branchcode
},
303 'biblio' => $biblionumber,
304 'biblioitems' => $biblionumber,
305 'borrowers' => $borinfo,
313 From
=> $branchdetails->{'branchemail'} || C4
::Context
->preference("KohaAdminEmailAddress"),
314 Subject
=> Encode
::encode
( "utf8", "" . $letter->{title
} ),
315 Message
=> Encode
::encode
( "utf8", "" . $letter->{content
} ),
316 'Content-Type' => 'text/plain; charset="utf8"',
318 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
321 elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' ) {
323 # prepare the letter...
324 # search the biblionumber
325 my $strsth = $type eq 'claimacquisition'
327 SELECT aqorders
.*,aqbasket
.*,biblio
.*,biblioitems
.*,aqbooksellers
.*,
328 aqbooksellers
.id AS booksellerid
330 LEFT JOIN aqbasket ON aqbasket
.basketno
=aqorders
.basketno
331 LEFT JOIN biblio ON aqorders
.biblionumber
=biblio
.biblionumber
332 LEFT JOIN biblioitems ON aqorders
.biblionumber
=biblioitems
.biblionumber
333 LEFT JOIN aqbooksellers ON aqbasket
.booksellerid
=aqbooksellers
.id
334 WHERE aqorders
.ordernumber IN
(
337 SELECT serial
.*,subscription
.*, biblio
.*, aqbooksellers
.*,
338 aqbooksellers
.id AS booksellerid
340 LEFT JOIN subscription ON serial
.subscriptionid
=subscription
.subscriptionid
341 LEFT JOIN biblio ON serial
.biblionumber
=biblio
.biblionumber
342 LEFT JOIN aqbooksellers ON subscription
.aqbooksellerid
=aqbooksellers
.id
343 WHERE serial
.serialid IN
(
345 $strsth .= join( ",", @
$externalid ) . ")";
346 my $sthorders = $dbh->prepare($strsth);
348 my $dataorders = $sthorders->fetchall_arrayref( {} );
351 $dbh->prepare("select * from aqbooksellers where id=?");
352 $sthbookseller->execute( $dataorders->[0]->{booksellerid
} );
353 my $databookseller = $sthbookseller->fetchrow_hashref;
356 push @email, $databookseller->{bookselleremail
} if $databookseller->{bookselleremail
};
357 push @email, $databookseller->{contemail
} if $databookseller->{contemail
};
359 warn "Bookseller $dataorders->[0]->{booksellerid} without emails";
360 return { error
=> "no_email" };
363 my $userenv = C4
::Context
->userenv;
364 my $letter = GetPreparedLetter
(
366 letter_code
=> $letter_code,
367 branchcode
=> $userenv->{branch
},
369 'branches' => $userenv->{branch
},
370 'aqbooksellers' => $databookseller,
372 repeat
=> $dataorders,
378 To
=> join( ',', @email),
379 From
=> $userenv->{emailaddress
},
380 Subject
=> Encode
::encode
( "utf8", "" . $letter->{title
} ),
381 Message
=> Encode
::encode
( "utf8", "" . $letter->{content
} ),
382 'Content-Type' => 'text/plain; charset="utf8"',
384 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
388 $type eq 'claimissues' ?
"CLAIM ISSUE" : "ACQUISITION CLAIM",
391 . $databookseller->{contemail
}
396 ) if C4
::Context
->preference("LetterLog");
398 # send an "account details" notice to a newly created user
399 elsif ( $type eq 'members' ) {
400 my $branchdetails = GetBranchDetail
($externalid->{'branchcode'});
401 my $letter = GetPreparedLetter
(
403 letter_code
=> $letter_code,
404 branchcode
=> $externalid->{'branchcode'},
406 'branches' => $branchdetails,
407 'borrowers' => $externalid->{'borrowernumber'},
409 substitute
=> { 'borrowers.password' => $externalid->{'password'} },
413 return { error
=> "no_email" } unless $externalid->{'emailaddr'};
415 To
=> $externalid->{'emailaddr'},
416 From
=> $branchdetails->{'branchemail'} || C4
::Context
->preference("KohaAdminEmailAddress"),
417 Subject
=> Encode
::encode
( "utf8", $letter->{'title'} ),
418 Message
=> Encode
::encode
( "utf8", $letter->{'content'} ),
419 'Content-Type' => 'text/plain; charset="utf8"',
421 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
425 =head2 GetPreparedLetter( %params )
428 module => letter module, mandatory
429 letter_code => letter code, mandatory
430 branchcode => for letter selection, if missing default system letter taken
431 tables => a hashref with table names as keys. Values are either:
432 - a scalar - primary key value
433 - an arrayref - primary key values
434 - a hashref - full record
435 substitute => custom substitution key/value pairs
436 repeat => records to be substituted on consecutive lines:
437 - an arrayref - tries to guess what needs substituting by
438 taking remaining << >> tokensr; not recommended
439 - a hashref token => @tables - replaces <token> << >> << >> </token>
440 subtemplate for each @tables row; table is a hashref as above
441 want_librarian => boolean, if set to true triggers librarian details
442 substitution from the userenv
444 letter fields hashref (title & content useful)
448 sub GetPreparedLetter
{
451 my $module = $params{module
} or croak
"No module";
452 my $letter_code = $params{letter_code
} or croak
"No letter_code";
453 my $branchcode = $params{branchcode
} || '';
454 my $mtt = $params{message_transport_type
} || 'email';
456 my $letter = getletter
( $module, $letter_code, $branchcode, $mtt )
457 or warn( "No $module $letter_code letter transported by " . $mtt ),
460 my $tables = $params{tables
};
461 my $substitute = $params{substitute
};
462 my $repeat = $params{repeat
};
463 $tables || $substitute || $repeat
464 or carp
( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
466 my $want_librarian = $params{want_librarian
};
469 while ( my ($token, $val) = each %$substitute ) {
470 $letter->{title
} =~ s/<<$token>>/$val/g;
471 $letter->{content
} =~ s/<<$token>>/$val/g;
475 my $OPACBaseURL = C4
::Context
->preference('OPACBaseURL');
476 $letter->{content
} =~ s/<<OPACBaseURL>>/$OPACBaseURL/go;
478 if ($want_librarian) {
479 # parsing librarian name
480 my $userenv = C4
::Context
->userenv;
481 $letter->{content
} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
482 $letter->{content
} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
483 $letter->{content
} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
486 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
489 if (ref ($repeat) eq 'ARRAY' ) {
490 $repeat_no_enclosing_tags = $repeat;
492 $repeat_enclosing_tags = $repeat;
496 if ($repeat_enclosing_tags) {
497 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
498 if ( $letter->{content
} =~ m!<$tag>(.*)</$tag>!s ) {
501 my %subletter = ( title
=> '', content
=> $subcontent );
502 _substitute_tables
( \
%subletter, $_ );
505 $letter->{content
} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
511 _substitute_tables
( $letter, $tables );
514 if ($repeat_no_enclosing_tags) {
515 if ( $letter->{content
} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
520 $c =~ s/<<count>>/$i/go;
521 foreach my $field ( keys %{$_} ) {
522 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
526 } @
$repeat_no_enclosing_tags;
528 my $replaceby = join( "\n", @lines );
529 $letter->{content
} =~ s/\Q$line\E/$replaceby/s;
533 $letter->{content
} =~ s/<<\S*>>//go; #remove any stragglers
534 # $letter->{content} =~ s/<<[^>]*>>//go;
539 sub _substitute_tables
{
540 my ( $letter, $tables ) = @_;
541 while ( my ($table, $param) = each %$tables ) {
544 my $ref = ref $param;
547 if ($ref && $ref eq 'HASH') {
552 my $sth = _parseletter_sth
($table);
554 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
557 $sth->execute( $ref ? @
$param : $param );
559 $values = $sth->fetchrow_hashref;
563 _parseletter
( $letter, $table, $values );
567 sub _parseletter_sth
{
571 carp
"ERROR: _parseletter_sth() called without argument (table)";
574 # NOTE: we used to check whether we had a statement handle cached in
575 # a %handles module-level variable. This was a dumb move and
576 # broke things for the rest of us. prepare_cached is a better
577 # way to cache statement handles anyway.
579 ($table eq 'biblio' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
580 ($table eq 'biblioitems' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
581 ($table eq 'items' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
582 ($table eq 'issues' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
583 ($table eq 'old_issues' ) ?
"SELECT * FROM $table WHERE itemnumber = ? ORDER BY timestamp DESC LIMIT 1" :
584 ($table eq 'reserves' ) ?
"SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
585 ($table eq 'borrowers' ) ?
"SELECT * FROM $table WHERE borrowernumber = ?" :
586 ($table eq 'branches' ) ?
"SELECT * FROM $table WHERE branchcode = ?" :
587 ($table eq 'suggestions' ) ?
"SELECT * FROM $table WHERE suggestionid = ?" :
588 ($table eq 'aqbooksellers') ?
"SELECT * FROM $table WHERE id = ?" :
589 ($table eq 'aqorders' ) ?
"SELECT * FROM $table WHERE ordernumber = ?" :
590 ($table eq 'opac_news' ) ?
"SELECT * FROM $table WHERE idnew = ?" :
591 ($table eq 'borrower_modifications') ?
"SELECT * FROM $table WHERE borrowernumber = ? OR verification_token =?":
594 warn "ERROR: No _parseletter_sth query for table '$table'";
595 return; # nothing to get
597 unless ($sth = C4
::Context
->dbh->prepare_cached($query)) {
598 warn "ERROR: Failed to prepare query: '$query'";
601 return $sth; # now cache is populated for that $table
604 =head2 _parseletter($letter, $table, $values)
607 - $letter : a hash to letter fields (title & content useful)
608 - $table : the Koha table to parse.
609 - $values : table record hashref
610 parse all fields from a table, and replace values in title & content with the appropriate value
611 (not exported sub, used only internally)
616 my ( $letter, $table, $values ) = @_;
618 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
619 my @waitingdate = split /-/, $values->{'waitingdate'};
621 $values->{'expirationdate'} = '';
622 if( C4
::Context
->preference('ExpireReservesMaxPickUpDelay') &&
623 C4
::Context
->preference('ReservesMaxPickUpDelay') ) {
624 my $dt = dt_from_string
();
625 $dt->add( days
=> C4
::Context
->preference('ReservesMaxPickUpDelay') );
626 $values->{'expirationdate'} = output_pref
({ dt
=> $dt, dateonly
=> 1 });
629 $values->{'waitingdate'} = output_pref
({ dt
=> dt_from_string
( $values->{'waitingdate'} ), dateonly
=> 1 });
633 if ($letter->{content
} && $letter->{content
} =~ /<<today>>/) {
634 my $todaysdate = output_pref
( DateTime
->now() );
635 $letter->{content
} =~ s/<<today>>/$todaysdate/go;
638 while ( my ($field, $val) = each %$values ) {
639 my $replacetablefield = "<<$table.$field>>";
640 my $replacefield = "<<$field>>";
641 $val =~ s/\p{P}$// if $val && $table=~/biblio/;
642 #BZ 9886: Assuming that we want to eliminate ISBD punctuation here
643 #Therefore adding the test on biblio. This includes biblioitems,
644 #but excludes items. Removed unneeded global and lookahead.
646 $val = GetAuthorisedValueByCode
('ROADTYPE', $val, 0) if $table=~/^borrowers$/ && $field=~/^streettype$/;
647 my $replacedby = defined ($val) ?
$val : '';
648 ($letter->{title
} ) and do {
649 $letter->{title
} =~ s/$replacetablefield/$replacedby/g;
650 $letter->{title
} =~ s/$replacefield/$replacedby/g;
652 ($letter->{content
}) and do {
653 $letter->{content
} =~ s/$replacetablefield/$replacedby/g;
654 $letter->{content
} =~ s/$replacefield/$replacedby/g;
658 if ($table eq 'borrowers' && $letter->{content
}) {
659 if ( my $attributes = GetBorrowerAttributes
($values->{borrowernumber
}) ) {
661 foreach (@
$attributes) {
662 my $code = $_->{code
};
663 my $val = $_->{value_description
} || $_->{value
};
664 $val =~ s/\p{P}(?=$)//g if $val;
665 next unless $val gt '';
667 push @
{ $attr{$code} }, $val;
669 while ( my ($code, $val_ar) = each %attr ) {
670 my $replacefield = "<<borrower-attribute:$code>>";
671 my $replacedby = join ',', @
$val_ar;
672 $letter->{content
} =~ s/$replacefield/$replacedby/g;
681 my $success = EnqueueLetter( { letter => $letter,
682 borrowernumber => '12', message_transport_type => 'email' } )
684 places a letter in the message_queue database table, which will
685 eventually get processed (sent) by the process_message_queue.pl
686 cronjob when it calls SendQueuedMessages.
688 return message_id on success
693 my $params = shift or return;
695 return unless exists $params->{'letter'};
696 # return unless exists $params->{'borrowernumber'};
697 return unless exists $params->{'message_transport_type'};
699 my $content = $params->{letter
}->{content
};
700 $content =~ s/\s+//g if(defined $content);
701 if ( not defined $content or $content eq '' ) {
702 warn "Trying to add an empty message to the message queue" if $debug;
706 # If we have any attachments we should encode then into the body.
707 if ( $params->{'attachments'} ) {
708 $params->{'letter'} = _add_attachments
(
709 { letter
=> $params->{'letter'},
710 attachments
=> $params->{'attachments'},
711 message
=> MIME
::Lite
->new( Type
=> 'multipart/mixed' ),
716 my $dbh = C4
::Context
->dbh();
717 my $statement = << 'ENDSQL';
718 INSERT INTO message_queue
719 ( borrowernumber
, subject
, content
, metadata
, letter_code
, message_transport_type
, status
, time_queued
, to_address
, from_address
, content_type
)
721 ( ?
, ?
, ?
, ?
, ?
, ?
, ?
, NOW
(), ?
, ?
, ?
)
724 my $sth = $dbh->prepare($statement);
725 my $result = $sth->execute(
726 $params->{'borrowernumber'}, # borrowernumber
727 $params->{'letter'}->{'title'}, # subject
728 $params->{'letter'}->{'content'}, # content
729 $params->{'letter'}->{'metadata'} || '', # metadata
730 $params->{'letter'}->{'code'} || '', # letter_code
731 $params->{'message_transport_type'}, # message_transport_type
733 $params->{'to_address'}, # to_address
734 $params->{'from_address'}, # from_address
735 $params->{'letter'}->{'content-type'}, # content_type
737 return $dbh->last_insert_id(undef,undef,'message_queue', undef);
740 =head2 SendQueuedMessages ([$hashref])
742 my $sent = SendQueuedMessages( { verbose => 1 } );
744 sends all of the 'pending' items in the message queue.
746 returns number of messages sent.
750 sub SendQueuedMessages
{
753 my $unsent_messages = _get_unsent_messages
();
754 MESSAGE
: foreach my $message ( @
$unsent_messages ) {
755 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
756 warn sprintf( 'sending %s message to patron: %s',
757 $message->{'message_transport_type'},
758 $message->{'borrowernumber'} || 'Admin' )
759 if $params->{'verbose'} or $debug;
760 # This is just begging for subclassing
761 next MESSAGE
if ( lc($message->{'message_transport_type'}) eq 'rss' );
762 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
763 _send_message_by_email
( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
765 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
766 _send_message_by_sms
( $message );
769 return scalar( @
$unsent_messages );
772 =head2 GetRSSMessages
774 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
776 returns a listref of all queued RSS messages for a particular person.
783 return unless $params;
784 return unless ref $params;
785 return unless $params->{'borrowernumber'};
787 return _get_unsent_messages
( { message_transport_type
=> 'rss',
788 limit
=> $params->{'limit'},
789 borrowernumber
=> $params->{'borrowernumber'}, } );
792 =head2 GetPrintMessages
794 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
796 Returns a arrayref of all queued print messages (optionally, for a particular
801 sub GetPrintMessages
{
802 my $params = shift || {};
804 return _get_unsent_messages
( { message_transport_type
=> 'print',
805 borrowernumber
=> $params->{'borrowernumber'},
809 =head2 GetQueuedMessages ([$hashref])
811 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
813 fetches messages out of the message queue.
816 list of hashes, each has represents a message in the message queue.
820 sub GetQueuedMessages
{
823 my $dbh = C4
::Context
->dbh();
824 my $statement = << 'ENDSQL';
825 SELECT message_id
, borrowernumber
, subject
, content
, message_transport_type
, status
, time_queued
831 if ( exists $params->{'borrowernumber'} ) {
832 push @whereclauses, ' borrowernumber = ? ';
833 push @query_params, $params->{'borrowernumber'};
836 if ( @whereclauses ) {
837 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
840 if ( defined $params->{'limit'} ) {
841 $statement .= ' LIMIT ? ';
842 push @query_params, $params->{'limit'};
845 my $sth = $dbh->prepare( $statement );
846 my $result = $sth->execute( @query_params );
847 return $sth->fetchall_arrayref({});
850 =head2 GetMessageTransportTypes
852 my @mtt = GetMessageTransportTypes();
854 returns an arrayref of transport types
858 sub GetMessageTransportTypes
{
859 my $dbh = C4
::Context
->dbh();
860 my $mtts = $dbh->selectcol_arrayref("
861 SELECT message_transport_type
862 FROM message_transport_types
863 ORDER BY message_transport_type
868 =head2 _add_attachements
871 letter - the standard letter hashref
872 attachments - listref of attachments. each attachment is a hashref of:
873 type - the mime type, like 'text/plain'
874 content - the actual attachment
875 filename - the name of the attachment.
876 message - a MIME::Lite object to attach these to.
878 returns your letter object, with the content updated.
882 sub _add_attachments
{
885 my $letter = $params->{'letter'};
886 my $attachments = $params->{'attachments'};
887 return $letter unless @
$attachments;
888 my $message = $params->{'message'};
890 # First, we have to put the body in as the first attachment
892 Type
=> $letter->{'content-type'} || 'TEXT',
893 Data
=> $letter->{'is_html'}
894 ? _wrap_html
($letter->{'content'}, $letter->{'title'})
895 : $letter->{'content'},
898 foreach my $attachment ( @
$attachments ) {
900 Type
=> $attachment->{'type'},
901 Data
=> $attachment->{'content'},
902 Filename
=> $attachment->{'filename'},
905 # we're forcing list context here to get the header, not the count back from grep.
906 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
907 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
908 $letter->{'content'} = $message->body_as_string;
914 sub _get_unsent_messages
{
917 my $dbh = C4
::Context
->dbh();
918 my $statement = << 'ENDSQL';
919 SELECT mq
.message_id
, mq
.borrowernumber
, mq
.subject
, mq
.content
, mq
.message_transport_type
, mq
.status
, mq
.time_queued
, mq
.from_address
, mq
.to_address
, mq
.content_type
, b
.branchcode
, mq
.letter_code
920 FROM message_queue mq
921 LEFT JOIN borrowers b ON b
.borrowernumber
= mq
.borrowernumber
925 my @query_params = ('pending');
927 if ( $params->{'message_transport_type'} ) {
928 $statement .= ' AND message_transport_type = ? ';
929 push @query_params, $params->{'message_transport_type'};
931 if ( $params->{'borrowernumber'} ) {
932 $statement .= ' AND borrowernumber = ? ';
933 push @query_params, $params->{'borrowernumber'};
935 if ( $params->{'limit'} ) {
936 $statement .= ' limit ? ';
937 push @query_params, $params->{'limit'};
941 $debug and warn "_get_unsent_messages SQL: $statement";
942 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
943 my $sth = $dbh->prepare( $statement );
944 my $result = $sth->execute( @query_params );
945 return $sth->fetchall_arrayref({});
948 sub _send_message_by_email
{
949 my $message = shift or return;
950 my ($username, $password, $method) = @_;
952 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
953 my $to_address = $message->{'to_address'};
954 unless ($to_address) {
956 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
957 _set_message_status
( { message_id
=> $message->{'message_id'},
958 status
=> 'failed' } );
961 $to_address = C4
::Members
::GetNoticeEmailAddress
( $message->{'borrowernumber'} );
962 unless ($to_address) {
963 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
964 # warning too verbose for this more common case?
965 _set_message_status
( { message_id
=> $message->{'message_id'},
966 status
=> 'failed' } );
971 my $utf8 = decode
('MIME-Header', $message->{'subject'} );
972 $message->{subject
}= encode
('MIME-Header', $utf8);
973 my $subject = encode
('utf8', $message->{'subject'});
974 my $content = encode
('utf8', $message->{'content'});
975 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
976 my $is_html = $content_type =~ m/html/io;
978 my $branch_email = ( $member ) ? GetBranchDetail
( $member->{'branchcode'} )->{'branchemail'} : undef;
980 my %sendmail_params = (
982 From
=> $message->{'from_address'} || $branch_email || C4
::Context
->preference('KohaAdminEmailAddress'),
985 Message
=> $is_html ? _wrap_html
($content, $subject) : $content,
986 'content-type' => $content_type,
988 $sendmail_params{'Auth'} = {user
=> $username, pass
=> $password, method
=> $method} if $username;
989 if ( my $bcc = C4
::Context
->preference('OverdueNoticeBcc') ) {
990 $sendmail_params{ Bcc
} = $bcc;
993 _update_message_to_address
($message->{'message_id'},$to_address) unless $message->{to_address
}; #if initial message address was empty, coming here means that a to address was found and queue should be updated
994 if ( sendmail
( %sendmail_params ) ) {
995 _set_message_status
( { message_id
=> $message->{'message_id'},
996 status
=> 'sent' } );
999 _set_message_status
( { message_id
=> $message->{'message_id'},
1000 status
=> 'failed' } );
1001 carp
$Mail::Sendmail
::error
;
1007 my ($content, $title) = @_;
1009 my $css = C4
::Context
->preference("NoticeCSS") || '';
1010 $css = qq{<link rel
="stylesheet" type
="text/css" href
="$css">} if $css;
1012 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1013 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1014 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
1016 <title>$title</title>
1017 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1028 my ( $message ) = @_;
1029 my $dbh = C4
::Context
->dbh;
1030 my $count = $dbh->selectrow_array(q
|
1033 WHERE message_transport_type
= ?
1034 AND borrowernumber
= ?
1036 AND CAST
(time_queued AS date
) = CAST
(NOW
() AS date
)
1039 |, {}, $message->{message_transport_type
}, $message->{borrowernumber
}, $message->{letter_code
}, $message->{content
} );
1043 sub _send_message_by_sms
{
1044 my $message = shift or return;
1045 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
1047 unless ( $member->{smsalertnumber
} ) {
1048 _set_message_status
( { message_id
=> $message->{'message_id'},
1049 status
=> 'failed' } );
1053 if ( _is_duplicate
( $message ) ) {
1054 _set_message_status
( { message_id
=> $message->{'message_id'},
1055 status
=> 'failed' } );
1059 my $success = C4
::SMS
->send_sms( { destination
=> $member->{'smsalertnumber'},
1060 message
=> $message->{'content'},
1062 _set_message_status
( { message_id
=> $message->{'message_id'},
1063 status
=> ($success ?
'sent' : 'failed') } );
1067 sub _update_message_to_address
{
1069 my $dbh = C4
::Context
->dbh();
1070 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
1073 sub _set_message_status
{
1074 my $params = shift or return;
1076 foreach my $required_parameter ( qw( message_id status ) ) {
1077 return unless exists $params->{ $required_parameter };
1080 my $dbh = C4
::Context
->dbh();
1081 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1082 my $sth = $dbh->prepare( $statement );
1083 my $result = $sth->execute( $params->{'status'},
1084 $params->{'message_id'} );