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 );
39 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
43 # set the version for version checking
44 $VERSION = 3.07.00.049;
47 &GetLetters &GetLettersAvailableForALibrary &GetLetterTemplates &DelLetter &GetPreparedLetter &GetWrappedLetter &addalert &getalert &delalert &findrelatedto &SendAlerts &GetPrintMessages &GetMessageTransportTypes
53 C4::Letters - Give functions for Letters management
61 "Letters" is the tool used in Koha to manage informations sent to the patrons and/or the library. This include some cron jobs like
62 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)
64 Letters are managed through "alerts" sent by Koha on some events. All "alert" related functions are in this module too.
66 =head2 GetLetters([$module])
68 $letters = &GetLetters($module);
69 returns informations about letters.
70 if needed, $module filters for letters given module
76 my $module = $filters->{module};
77 my $code = $filters->{code};
78 my $branchcode = $filters->{branchcode};
79 my $dbh = C4::Context->dbh;
80 my $letters = $dbh->selectall_arrayref(
82 SELECT module, code, branchcode, name
86 . ( $module ? q| AND module = ?| : q|| )
87 . ( $code ? q| AND code = ?| : q|| )
88 . ( defined $branchcode ? q| AND branchcode = ?| : q|| )
89 . q| GROUP BY code ORDER BY name|, { Slice => {} }
90 , ( $module ? $module : () )
91 , ( $code ? $code : () )
92 , ( defined $branchcode ? $branchcode : () )
98 =head2 GetLetterTemplates
100 my $letter_templates = GetLetterTemplates(
102 module => 'circulation',
104 branchcode => 'CPL', # '' for default,
108 Return a hashref of letter templates.
109 The key will be the message transport type.
113 sub GetLetterTemplates {
116 my $module = $params->{module};
117 my $code = $params->{code};
118 my $branchcode = $params->{branchcode} // '';
119 my $dbh = C4::Context->dbh;
120 my $letters = $dbh->selectall_hashref(
122 SELECT module, code, branchcode, name, is_html, title, content, message_transport_type
128 , 'message_transport_type'
130 , $module, $code, $branchcode
136 =head2 GetLettersAvailableForALibrary
138 my $letters = GetLettersAvailableForALibrary(
140 branchcode => 'CPL', # '' for default
141 module => 'circulation',
145 Return an arrayref of letters, sorted by name.
146 If a specific letter exist for the given branchcode, it will be retrieve.
147 Otherwise the default letter will be.
151 sub GetLettersAvailableForALibrary {
153 my $branchcode = $filters->{branchcode};
154 my $module = $filters->{module};
156 croak "module should be provided" unless $module;
158 my $dbh = C4::Context->dbh;
159 my $default_letters = $dbh->selectall_arrayref(
161 SELECT module, code, branchcode, name
165 . q| AND branchcode = ''|
166 . ( $module ? q| AND module = ?| : q|| )
167 . q| ORDER BY name|, { Slice => {} }
168 , ( $module ? $module : () )
171 my $specific_letters;
173 $specific_letters = $dbh->selectall_arrayref(
175 SELECT module, code, branchcode, name
179 . q| AND branchcode = ?|
180 . ( $module ? q| AND module = ?| : q|| )
181 . q| ORDER BY name|, { Slice => {} }
183 , ( $module ? $module : () )
188 for my $l (@$default_letters) {
189 $letters{ $l->{code} } = $l;
191 for my $l (@$specific_letters) {
192 # Overwrite the default letter with the specific one.
193 $letters{ $l->{code} } = $l;
196 return [ map { $letters{$_} }
197 sort { $letters{$a}->{name} cmp $letters{$b}->{name} }
202 # FIXME: using our here means that a Plack server will need to be
203 # restarted fairly regularly when working with this routine.
204 # A better option would be to use Koha::Cache and use a cache
205 # that actually works in a persistent environment, but as a
206 # short-term fix, our will work.
209 my ( $module, $code, $branchcode, $message_transport_type ) = @_;
210 $message_transport_type ||= 'email';
213 if ( C4::Context->preference('IndependentBranches')
215 and C4::Context->userenv ) {
217 $branchcode = C4::Context->userenv->{'branch'};
221 if ( my $l = $letter{$module}{$code}{$branchcode}{$message_transport_type} ) {
222 return { %$l }; # deep copy
225 my $dbh = C4::Context->dbh;
226 my $sth = $dbh->prepare(q{
229 WHERE module=? AND code=? AND (branchcode = ? OR branchcode = '') AND message_transport_type = ?
230 ORDER BY branchcode DESC LIMIT 1
232 $sth->execute( $module, $code, $branchcode, $message_transport_type );
233 my $line = $sth->fetchrow_hashref
235 $line->{'content-type'} = 'text/html; charset="UTF-8"' if $line->{is_html};
236 $letter{$module}{$code}{$branchcode}{$message_transport_type} = $line;
245 module => 'circulation',
251 Delete the letter. The mtt parameter is facultative.
252 If not given, all templates mathing the other parameters will be removed.
258 my $branchcode = $params->{branchcode};
259 my $module = $params->{module};
260 my $code = $params->{code};
261 my $mtt = $params->{mtt};
262 my $dbh = C4::Context->dbh;
268 | . ( $mtt ? q| AND message_transport_type = ?| : q|| )
269 , undef, $branchcode, $module, $code, ( $mtt ? $mtt : () ) );
272 =head2 addalert ($borrowernumber, $type, $externalid)
275 - $borrowernumber : the number of the borrower subscribing to the alert
276 - $type : the type of alert.
277 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
279 create an alert and return the alertid (primary key)
284 my ( $borrowernumber, $type, $externalid ) = @_;
285 my $dbh = C4::Context->dbh;
288 "insert into alert (borrowernumber, type, externalid) values (?,?,?)");
289 $sth->execute( $borrowernumber, $type, $externalid );
291 # get the alert number newly created and return it
292 my $alertid = $dbh->{'mysql_insertid'};
296 =head2 delalert ($alertid)
299 - alertid : the alert id
305 my $alertid = shift or die "delalert() called without valid argument (alertid)"; # it's gonna die anyway.
306 $debug and warn "delalert: deleting alertid $alertid";
307 my $sth = C4::Context->dbh->prepare("delete from alert where alertid=?");
308 $sth->execute($alertid);
311 =head2 getalert ([$borrowernumber], [$type], [$externalid])
314 - $borrowernumber : the number of the borrower subscribing to the alert
315 - $type : the type of alert.
316 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
317 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.
322 my ( $borrowernumber, $type, $externalid ) = @_;
323 my $dbh = C4::Context->dbh;
324 my $query = "SELECT a.*, b.branchcode FROM alert a JOIN borrowers b USING(borrowernumber) WHERE";
326 if ($borrowernumber and $borrowernumber =~ /^\d+$/) {
327 $query .= " borrowernumber=? AND ";
328 push @bind, $borrowernumber;
331 $query .= " type=? AND ";
335 $query .= " externalid=? AND ";
336 push @bind, $externalid;
338 $query =~ s/ AND $//;
339 my $sth = $dbh->prepare($query);
340 $sth->execute(@bind);
341 return $sth->fetchall_arrayref({});
344 =head2 findrelatedto($type, $externalid)
347 - $type : the type of alert
348 - $externalid : the id of the "object" to query
350 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.
351 When type=issue, the id is related to a subscriptionid and this sub returns the name of the biblio.
356 # When type=virtual, the id is related to a virtual shelf and this sub returns the name of the sub
359 my $type = shift or return;
360 my $externalid = shift or return;
361 my $q = ($type eq 'issue' ) ?
362 "select title as result from subscription left join biblio on subscription.biblionumber=biblio.biblionumber where subscriptionid=?" :
363 ($type eq 'borrower') ?
364 "select concat(firstname,' ',surname) from borrowers where borrowernumber=?" : undef;
366 warn "findrelatedto(): Illegal type '$type'";
369 my $sth = C4::Context->dbh->prepare($q);
370 $sth->execute($externalid);
371 my ($result) = $sth->fetchrow;
378 - $type : the type of alert
379 - $externalid : the id of the "object" to query
380 - $letter_code : the letter to send.
382 send an alert to all borrowers having put an alert on a given subject.
387 my ( $type, $externalid, $letter_code ) = @_;
388 my $dbh = C4::Context->dbh;
389 if ( $type eq 'issue' ) {
391 # prepare the letter...
392 # search the biblionumber
395 "SELECT biblionumber FROM subscription WHERE subscriptionid=?");
396 $sth->execute($externalid);
397 my ($biblionumber) = $sth->fetchrow
398 or warn( "No subscription for '$externalid'" ),
402 # find the list of borrowers to alert
403 my $alerts = getalert( '', 'issue', $externalid );
405 my $borinfo = C4::Members::GetMember('borrowernumber' => $_->{'borrowernumber'});
406 my $email = $borinfo->{email} or next;
408 # warn "sending issues...";
409 my $userenv = C4::Context->userenv;
410 my $branchdetails = GetBranchDetail($_->{'branchcode'});
411 my $letter = GetPreparedLetter (
413 letter_code => $letter_code,
414 branchcode => $userenv->{branch},
416 'branches' => $_->{branchcode},
417 'biblio' => $biblionumber,
418 'biblioitems' => $biblionumber,
419 'borrowers' => $borinfo,
425 my $message = Koha::Email->new();
426 my %mail = $message->create_message_headers(
429 from => $branchdetails->{'branchemail'},
430 replyto => $branchdetails->{'branchreplyto'},
431 sender => $branchdetails->{'branchreturnpath'},
432 subject => Encode::encode( "utf8", "" . $letter->{title} ),
433 message => $letter->{'is_html'} ? _wrap_html( Encode::encode( "utf8", $letter->{'content'} ), Encode::encode( "utf8", "" . $letter->{'title'} ) ) : Encode::encode( "utf8", "" . $letter->{'content'} ),
434 contenttype => $letter->{'is_html'} ? 'text/html; charset="utf-8"' : 'text/plain; charset="utf-8"',
437 sendmail(%mail) or carp $Mail::Sendmail::error;
440 elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' ) {
442 # prepare the letter...
443 # search the biblionumber
444 my $strsth = $type eq 'claimacquisition'
446 SELECT aqorders.*,aqbasket.*,biblio.*,biblioitems.*
448 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
449 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
450 LEFT JOIN biblioitems ON aqorders.biblionumber=biblioitems.biblionumber
451 WHERE aqorders.ordernumber IN (
454 SELECT serial.*,subscription.*, biblio.*, aqbooksellers.*,
455 aqbooksellers.id AS booksellerid
457 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
458 LEFT JOIN biblio ON serial.biblionumber=biblio.biblionumber
459 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
460 WHERE serial.serialid IN (
464 carp "No Order seleted";
465 return { error => "no_order_seleted" };
468 $strsth .= join( ",", @$externalid ) . ")";
469 my $sthorders = $dbh->prepare($strsth);
471 my $dataorders = $sthorders->fetchall_arrayref( {} );
474 $dbh->prepare("select * from aqbooksellers where id=?");
475 $sthbookseller->execute( $dataorders->[0]->{booksellerid} );
476 my $databookseller = $sthbookseller->fetchrow_hashref;
477 my $addressee = $type eq 'claimacquisition' ? 'acqprimary' : 'serialsprimary';
479 $dbh->prepare("SELECT * FROM aqcontacts WHERE booksellerid=? AND $type=1 ORDER BY $addressee DESC");
480 $sthcontact->execute( $dataorders->[0]->{booksellerid} );
481 my $datacontact = $sthcontact->fetchrow_hashref;
485 push @email, $databookseller->{bookselleremail} if $databookseller->{bookselleremail};
486 push @email, $datacontact->{email} if ( $datacontact && $datacontact->{email} );
488 warn "Bookseller $dataorders->[0]->{booksellerid} without emails";
489 return { error => "no_email" };
492 while ($addlcontact = $sthcontact->fetchrow_hashref) {
493 push @cc, $addlcontact->{email} if ( $addlcontact && $addlcontact->{email} );
496 my $userenv = C4::Context->userenv;
497 my $letter = GetPreparedLetter (
499 letter_code => $letter_code,
500 branchcode => $userenv->{branch},
502 'branches' => $userenv->{branch},
503 'aqbooksellers' => $databookseller,
504 'aqcontacts' => $datacontact,
506 repeat => $dataorders,
510 # Remove the order tag
511 $letter->{content} =~ s/<order>(.*?)<\/order>/$1/gxms;
515 To => join( ',', @email),
516 Cc => join( ',', @cc),
517 From => $userenv->{emailaddress},
518 Subject => Encode::encode( "utf8", "" . $letter->{title} ),
519 Message => $letter->{'is_html'} ? _wrap_html( Encode::encode( "utf8", $letter->{'content'} ), Encode::encode( "utf8", "" . $letter->{'title'} ) ) : Encode::encode( "utf8", "" . $letter->{'content'} ),
520 'Content-Type' => $letter->{'is_html'} ? 'text/html; charset="utf-8"' : 'text/plain; charset="utf-8"',
523 $mail{'Reply-to'} = C4::Context->preference('ReplytoDefault')
524 if C4::Context->preference('ReplytoDefault');
525 $mail{'Sender'} = C4::Context->preference('ReturnpathDefault')
526 if C4::Context->preference('ReturnpathDefault');
528 unless ( sendmail(%mail) ) {
529 carp $Mail::Sendmail::error;
530 return { error => $Mail::Sendmail::error };
535 $type eq 'claimissues' ? "CLAIM ISSUE" : "ACQUISITION CLAIM",
538 . join( ',', @email )
543 ) if C4::Context->preference("LetterLog");
545 # send an "account details" notice to a newly created user
546 elsif ( $type eq 'members' ) {
547 my $branchdetails = GetBranchDetail($externalid->{'branchcode'});
548 my $letter = GetPreparedLetter (
550 letter_code => $letter_code,
551 branchcode => $externalid->{'branchcode'},
553 'branches' => $branchdetails,
554 'borrowers' => $externalid->{'borrowernumber'},
556 substitute => { 'borrowers.password' => $externalid->{'password'} },
559 return { error => "no_email" } unless $externalid->{'emailaddr'};
560 my $email = Koha::Email->new();
561 my %mail = $email->create_message_headers(
563 to => $externalid->{'emailaddr'},
564 from => $branchdetails->{'branchemail'},
565 replyto => $branchdetails->{'branchreplyto'},
566 sender => $branchdetails->{'branchreturnpath'},
567 subject => Encode::encode( "utf8", "" . $letter->{'title'} ),
568 message => $letter->{'is_html'} ? _wrap_html( Encode::encode( "utf8", $letter->{'content'} ), Encode::encode( "utf8", "" . $letter->{'title'} ) ) : Encode::encode( "utf8", "" . $letter->{'content'} ),
569 contenttype => $letter->{'is_html'} ? 'text/html; charset="utf-8"' : 'text/plain; charset="utf-8"',
572 sendmail(%mail) or carp $Mail::Sendmail::error;
576 =head2 GetPreparedLetter( %params )
579 module => letter module, mandatory
580 letter_code => letter code, mandatory
581 branchcode => for letter selection, if missing default system letter taken
582 tables => a hashref with table names as keys. Values are either:
583 - a scalar - primary key value
584 - an arrayref - primary key values
585 - a hashref - full record
586 substitute => custom substitution key/value pairs
587 repeat => records to be substituted on consecutive lines:
588 - an arrayref - tries to guess what needs substituting by
589 taking remaining << >> tokensr; not recommended
590 - a hashref token => @tables - replaces <token> << >> << >> </token>
591 subtemplate for each @tables row; table is a hashref as above
592 want_librarian => boolean, if set to true triggers librarian details
593 substitution from the userenv
595 letter fields hashref (title & content useful)
599 sub GetPreparedLetter {
602 my $module = $params{module} or croak "No module";
603 my $letter_code = $params{letter_code} or croak "No letter_code";
604 my $branchcode = $params{branchcode} || '';
605 my $mtt = $params{message_transport_type} || 'email';
607 my $letter = getletter( $module, $letter_code, $branchcode, $mtt )
608 or warn( "No $module $letter_code letter transported by " . $mtt ),
611 my $tables = $params{tables};
612 my $substitute = $params{substitute};
613 my $repeat = $params{repeat};
614 $tables || $substitute || $repeat
615 or carp( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
617 my $want_librarian = $params{want_librarian};
620 while ( my ($token, $val) = each %$substitute ) {
621 $letter->{title} =~ s/<<$token>>/$val/g;
622 $letter->{content} =~ s/<<$token>>/$val/g;
626 my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
627 $letter->{content} =~ s/<<OPACBaseURL>>/$OPACBaseURL/go;
629 if ($want_librarian) {
630 # parsing librarian name
631 my $userenv = C4::Context->userenv;
632 $letter->{content} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
633 $letter->{content} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
634 $letter->{content} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
637 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
640 if (ref ($repeat) eq 'ARRAY' ) {
641 $repeat_no_enclosing_tags = $repeat;
643 $repeat_enclosing_tags = $repeat;
647 if ($repeat_enclosing_tags) {
648 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
649 if ( $letter->{content} =~ m!<$tag>(.*)</$tag>!s ) {
652 my %subletter = ( title => '', content => $subcontent );
653 _substitute_tables( \%subletter, $_ );
656 $letter->{content} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
662 _substitute_tables( $letter, $tables );
665 if ($repeat_no_enclosing_tags) {
666 if ( $letter->{content} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
671 $c =~ s/<<count>>/$i/go;
672 foreach my $field ( keys %{$_} ) {
673 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
677 } @$repeat_no_enclosing_tags;
679 my $replaceby = join( "\n", @lines );
680 $letter->{content} =~ s/\Q$line\E/$replaceby/s;
684 $letter->{content} =~ s/<<\S*>>//go; #remove any stragglers
685 # $letter->{content} =~ s/<<[^>]*>>//go;
690 sub _substitute_tables {
691 my ( $letter, $tables ) = @_;
692 while ( my ($table, $param) = each %$tables ) {
695 my $ref = ref $param;
698 if ($ref && $ref eq 'HASH') {
702 my $sth = _parseletter_sth($table);
704 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
707 $sth->execute( $ref ? @$param : $param );
709 $values = $sth->fetchrow_hashref;
713 _parseletter ( $letter, $table, $values );
717 sub _parseletter_sth {
721 carp "ERROR: _parseletter_sth() called without argument (table)";
724 # NOTE: we used to check whether we had a statement handle cached in
725 # a %handles module-level variable. This was a dumb move and
726 # broke things for the rest of us. prepare_cached is a better
727 # way to cache statement handles anyway.
729 ($table eq 'biblio' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
730 ($table eq 'biblioitems' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
731 ($table eq 'items' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
732 ($table eq 'issues' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
733 ($table eq 'old_issues' ) ? "SELECT * FROM $table WHERE itemnumber = ? ORDER BY timestamp DESC LIMIT 1" :
734 ($table eq 'reserves' ) ? "SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
735 ($table eq 'borrowers' ) ? "SELECT * FROM $table WHERE borrowernumber = ?" :
736 ($table eq 'branches' ) ? "SELECT * FROM $table WHERE branchcode = ?" :
737 ($table eq 'suggestions' ) ? "SELECT * FROM $table WHERE suggestionid = ?" :
738 ($table eq 'aqbooksellers') ? "SELECT * FROM $table WHERE id = ?" :
739 ($table eq 'aqorders' ) ? "SELECT * FROM $table WHERE ordernumber = ?" :
740 ($table eq 'opac_news' ) ? "SELECT * FROM $table WHERE idnew = ?" :
741 ($table eq 'borrower_modifications') ? "SELECT * FROM $table WHERE verification_token = ?" :
744 warn "ERROR: No _parseletter_sth query for table '$table'";
745 return; # nothing to get
747 unless ($sth = C4::Context->dbh->prepare_cached($query)) {
748 warn "ERROR: Failed to prepare query: '$query'";
751 return $sth; # now cache is populated for that $table
754 =head2 _parseletter($letter, $table, $values)
757 - $letter : a hash to letter fields (title & content useful)
758 - $table : the Koha table to parse.
759 - $values : table record hashref
760 parse all fields from a table, and replace values in title & content with the appropriate value
761 (not exported sub, used only internally)
766 my ( $letter, $table, $values ) = @_;
768 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
769 my @waitingdate = split /-/, $values->{'waitingdate'};
771 $values->{'expirationdate'} = '';
772 if( C4::Context->preference('ExpireReservesMaxPickUpDelay') &&
773 C4::Context->preference('ReservesMaxPickUpDelay') ) {
774 my $dt = dt_from_string();
775 $dt->add( days => C4::Context->preference('ReservesMaxPickUpDelay') );
776 $values->{'expirationdate'} = output_pref({ dt => $dt, dateonly => 1 });
779 $values->{'waitingdate'} = output_pref({ dt => dt_from_string( $values->{'waitingdate'} ), dateonly => 1 });
783 if ($letter->{content} && $letter->{content} =~ /<<today>>/) {
784 my $todaysdate = output_pref( DateTime->now() );
785 $letter->{content} =~ s/<<today>>/$todaysdate/go;
788 while ( my ($field, $val) = each %$values ) {
789 my $replacetablefield = "<<$table.$field>>";
790 my $replacefield = "<<$field>>";
791 $val =~ s/\p{P}$// if $val && $table=~/biblio/;
792 #BZ 9886: Assuming that we want to eliminate ISBD punctuation here
793 #Therefore adding the test on biblio. This includes biblioitems,
794 #but excludes items. Removed unneeded global and lookahead.
796 $val = GetAuthorisedValueByCode ('ROADTYPE', $val, 0) if $table=~/^borrowers$/ && $field=~/^streettype$/;
797 my $replacedby = defined ($val) ? $val : '';
799 and not $replacedby =~ m|0000-00-00|
800 and not $replacedby =~ m|9999-12-31|
801 and $replacedby =~ m|^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$| )
803 # If the value is XXXX-YY-ZZ[ AA:BB:CC] we assume it is a date
804 my $dateonly = defined $1 ? 0 : 1; #$1 refers to the capture group wrapped in parentheses. In this case, that's the hours, minutes, seconds.
806 $replacedby = output_pref({ dt => dt_from_string( $replacedby ), dateonly => $dateonly });
808 warn "$replacedby seems to be a date but an error occurs on generating it ($@)" if $@;
810 ($letter->{title} ) and do {
811 $letter->{title} =~ s/$replacetablefield/$replacedby/g;
812 $letter->{title} =~ s/$replacefield/$replacedby/g;
814 ($letter->{content}) and do {
815 $letter->{content} =~ s/$replacetablefield/$replacedby/g;
816 $letter->{content} =~ s/$replacefield/$replacedby/g;
820 if ($table eq 'borrowers' && $letter->{content}) {
821 if ( my $attributes = GetBorrowerAttributes($values->{borrowernumber}) ) {
823 foreach (@$attributes) {
824 my $code = $_->{code};
825 my $val = $_->{value_description} || $_->{value};
826 $val =~ s/\p{P}(?=$)//g if $val;
827 next unless $val gt '';
829 push @{ $attr{$code} }, $val;
831 while ( my ($code, $val_ar) = each %attr ) {
832 my $replacefield = "<<borrower-attribute:$code>>";
833 my $replacedby = join ',', @$val_ar;
834 $letter->{content} =~ s/$replacefield/$replacedby/g;
843 my $success = EnqueueLetter( { letter => $letter,
844 borrowernumber => '12', message_transport_type => 'email' } )
846 places a letter in the message_queue database table, which will
847 eventually get processed (sent) by the process_message_queue.pl
848 cronjob when it calls SendQueuedMessages.
850 return message_id on success
855 my $params = shift or return;
857 return unless exists $params->{'letter'};
858 # return unless exists $params->{'borrowernumber'};
859 return unless exists $params->{'message_transport_type'};
861 my $content = $params->{letter}->{content};
862 $content =~ s/\s+//g if(defined $content);
863 if ( not defined $content or $content eq '' ) {
864 warn "Trying to add an empty message to the message queue" if $debug;
868 # If we have any attachments we should encode then into the body.
869 if ( $params->{'attachments'} ) {
870 $params->{'letter'} = _add_attachments(
871 { letter => $params->{'letter'},
872 attachments => $params->{'attachments'},
873 message => MIME::Lite->new( Type => 'multipart/mixed' ),
878 my $dbh = C4::Context->dbh();
879 my $statement = << 'ENDSQL';
880 INSERT INTO message_queue
881 ( borrowernumber, subject, content, metadata, letter_code, message_transport_type, status, time_queued, to_address, from_address, content_type )
883 ( ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ? )
886 my $sth = $dbh->prepare($statement);
887 my $result = $sth->execute(
888 $params->{'borrowernumber'}, # borrowernumber
889 $params->{'letter'}->{'title'}, # subject
890 $params->{'letter'}->{'content'}, # content
891 $params->{'letter'}->{'metadata'} || '', # metadata
892 $params->{'letter'}->{'code'} || '', # letter_code
893 $params->{'message_transport_type'}, # message_transport_type
895 $params->{'to_address'}, # to_address
896 $params->{'from_address'}, # from_address
897 $params->{'letter'}->{'content-type'}, # content_type
899 return $dbh->last_insert_id(undef,undef,'message_queue', undef);
902 =head2 SendQueuedMessages ([$hashref])
904 my $sent = SendQueuedMessages( { verbose => 1 } );
906 sends all of the 'pending' items in the message queue.
908 returns number of messages sent.
912 sub SendQueuedMessages {
915 my $unsent_messages = _get_unsent_messages();
916 MESSAGE: foreach my $message ( @$unsent_messages ) {
917 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
918 warn sprintf( 'sending %s message to patron: %s',
919 $message->{'message_transport_type'},
920 $message->{'borrowernumber'} || 'Admin' )
921 if $params->{'verbose'} or $debug;
922 # This is just begging for subclassing
923 next MESSAGE if ( lc($message->{'message_transport_type'}) eq 'rss' );
924 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
925 _send_message_by_email( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
927 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
928 _send_message_by_sms( $message );
931 return scalar( @$unsent_messages );
934 =head2 GetRSSMessages
936 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
938 returns a listref of all queued RSS messages for a particular person.
945 return unless $params;
946 return unless ref $params;
947 return unless $params->{'borrowernumber'};
949 return _get_unsent_messages( { message_transport_type => 'rss',
950 limit => $params->{'limit'},
951 borrowernumber => $params->{'borrowernumber'}, } );
954 =head2 GetPrintMessages
956 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
958 Returns a arrayref of all queued print messages (optionally, for a particular
963 sub GetPrintMessages {
964 my $params = shift || {};
966 return _get_unsent_messages( { message_transport_type => 'print',
967 borrowernumber => $params->{'borrowernumber'},
971 =head2 GetQueuedMessages ([$hashref])
973 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
975 fetches messages out of the message queue.
978 list of hashes, each has represents a message in the message queue.
982 sub GetQueuedMessages {
985 my $dbh = C4::Context->dbh();
986 my $statement = << 'ENDSQL';
987 SELECT message_id, borrowernumber, subject, content, message_transport_type, status, time_queued
993 if ( exists $params->{'borrowernumber'} ) {
994 push @whereclauses, ' borrowernumber = ? ';
995 push @query_params, $params->{'borrowernumber'};
998 if ( @whereclauses ) {
999 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
1002 if ( defined $params->{'limit'} ) {
1003 $statement .= ' LIMIT ? ';
1004 push @query_params, $params->{'limit'};
1007 my $sth = $dbh->prepare( $statement );
1008 my $result = $sth->execute( @query_params );
1009 return $sth->fetchall_arrayref({});
1012 =head2 GetMessageTransportTypes
1014 my @mtt = GetMessageTransportTypes();
1016 returns an arrayref of transport types
1020 sub GetMessageTransportTypes {
1021 my $dbh = C4::Context->dbh();
1022 my $mtts = $dbh->selectcol_arrayref("
1023 SELECT message_transport_type
1024 FROM message_transport_types
1025 ORDER BY message_transport_type
1030 =head2 _add_attachements
1033 letter - the standard letter hashref
1034 attachments - listref of attachments. each attachment is a hashref of:
1035 type - the mime type, like 'text/plain'
1036 content - the actual attachment
1037 filename - the name of the attachment.
1038 message - a MIME::Lite object to attach these to.
1040 returns your letter object, with the content updated.
1044 sub _add_attachments {
1047 my $letter = $params->{'letter'};
1048 my $attachments = $params->{'attachments'};
1049 return $letter unless @$attachments;
1050 my $message = $params->{'message'};
1052 # First, we have to put the body in as the first attachment
1054 Type => $letter->{'content-type'} || 'TEXT',
1055 Data => $letter->{'is_html'}
1056 ? _wrap_html($letter->{'content'}, $letter->{'title'})
1057 : $letter->{'content'},
1060 foreach my $attachment ( @$attachments ) {
1062 Type => $attachment->{'type'},
1063 Data => $attachment->{'content'},
1064 Filename => $attachment->{'filename'},
1067 # we're forcing list context here to get the header, not the count back from grep.
1068 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
1069 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
1070 $letter->{'content'} = $message->body_as_string;
1076 sub _get_unsent_messages {
1079 my $dbh = C4::Context->dbh();
1080 my $statement = << 'ENDSQL';
1081 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
1082 FROM message_queue mq
1083 LEFT JOIN borrowers b ON b.borrowernumber = mq.borrowernumber
1087 my @query_params = ('pending');
1088 if ( ref $params ) {
1089 if ( $params->{'message_transport_type'} ) {
1090 $statement .= ' AND message_transport_type = ? ';
1091 push @query_params, $params->{'message_transport_type'};
1093 if ( $params->{'borrowernumber'} ) {
1094 $statement .= ' AND borrowernumber = ? ';
1095 push @query_params, $params->{'borrowernumber'};
1097 if ( $params->{'limit'} ) {
1098 $statement .= ' limit ? ';
1099 push @query_params, $params->{'limit'};
1103 $debug and warn "_get_unsent_messages SQL: $statement";
1104 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
1105 my $sth = $dbh->prepare( $statement );
1106 my $result = $sth->execute( @query_params );
1107 return $sth->fetchall_arrayref({});
1110 sub _send_message_by_email {
1111 my $message = shift or return;
1112 my ($username, $password, $method) = @_;
1114 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
1115 my $to_address = $message->{'to_address'};
1116 unless ($to_address) {
1118 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
1119 _set_message_status( { message_id => $message->{'message_id'},
1120 status => 'failed' } );
1123 $to_address = C4::Members::GetNoticeEmailAddress( $message->{'borrowernumber'} );
1124 unless ($to_address) {
1125 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
1126 # warning too verbose for this more common case?
1127 _set_message_status( { message_id => $message->{'message_id'},
1128 status => 'failed' } );
1133 my $utf8 = decode('MIME-Header', $message->{'subject'} );
1134 $message->{subject}= encode('MIME-Header', $utf8);
1135 my $subject = encode('utf8', $message->{'subject'});
1136 my $content = encode('utf8', $message->{'content'});
1137 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
1138 my $is_html = $content_type =~ m/html/io;
1139 my $branch_email = undef;
1140 my $branch_replyto = undef;
1141 my $branch_returnpath = undef;
1143 my $branchdetail = GetBranchDetail( $member->{'branchcode'} );
1144 $branch_email = $branchdetail->{'branchemail'};
1145 $branch_replyto = $branchdetail->{'branchreplyto'};
1146 $branch_returnpath = $branchdetail->{'branchreturnpath'};
1148 my $email = Koha::Email->new();
1149 my %sendmail_params = $email->create_message_headers(
1152 from => $message->{'from_address'} || $branch_email,
1153 replyto => $branch_replyto,
1154 sender => $branch_returnpath,
1155 subject => $subject,
1156 message => $is_html ? _wrap_html( $content, $subject ) : $content,
1157 contenttype => $content_type
1161 $sendmail_params{'Auth'} = {user => $username, pass => $password, method => $method} if $username;
1162 if ( my $bcc = C4::Context->preference('OverdueNoticeBcc') ) {
1163 $sendmail_params{ Bcc } = $bcc;
1166 _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
1167 if ( sendmail( %sendmail_params ) ) {
1168 _set_message_status( { message_id => $message->{'message_id'},
1169 status => 'sent' } );
1172 _set_message_status( { message_id => $message->{'message_id'},
1173 status => 'failed' } );
1174 carp $Mail::Sendmail::error;
1180 my ($content, $title) = @_;
1182 my $css = C4::Context->preference("NoticeCSS") || '';
1183 $css = qq{<link rel="stylesheet" type="text/css" href="$css">} if $css;
1185 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1186 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1187 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
1189 <title>$title</title>
1190 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1201 my ( $message ) = @_;
1202 my $dbh = C4::Context->dbh;
1203 my $count = $dbh->selectrow_array(q|
1206 WHERE message_transport_type = ?
1207 AND borrowernumber = ?
1209 AND CAST(time_queued AS date) = CAST(NOW() AS date)
1212 |, {}, $message->{message_transport_type}, $message->{borrowernumber}, $message->{letter_code}, $message->{content} );
1216 sub _send_message_by_sms {
1217 my $message = shift or return;
1218 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
1220 unless ( $member->{smsalertnumber} ) {
1221 _set_message_status( { message_id => $message->{'message_id'},
1222 status => 'failed' } );
1226 if ( _is_duplicate( $message ) ) {
1227 _set_message_status( { message_id => $message->{'message_id'},
1228 status => 'failed' } );
1232 my $success = C4::SMS->send_sms( { destination => $member->{'smsalertnumber'},
1233 message => $message->{'content'},
1235 _set_message_status( { message_id => $message->{'message_id'},
1236 status => ($success ? 'sent' : 'failed') } );
1240 sub _update_message_to_address {
1242 my $dbh = C4::Context->dbh();
1243 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
1246 sub _set_message_status {
1247 my $params = shift or return;
1249 foreach my $required_parameter ( qw( message_id status ) ) {
1250 return unless exists $params->{ $required_parameter };
1253 my $dbh = C4::Context->dbh();
1254 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1255 my $sth = $dbh->prepare( $statement );
1256 my $result = $sth->execute( $params->{'status'},
1257 $params->{'message_id'} );