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 &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 $dbh = C4::Context->dbh;
79 my $letters = $dbh->selectall_arrayref(
81 SELECT module, code, branchcode, name
85 . ( $module ? q| AND module = ?| : q|| )
86 . ( $code ? q| AND code = ?| : q|| )
87 . q| GROUP BY code ORDER BY name|, { Slice => {} }
88 , ( $module ? $module : () )
89 , ( $code ? $code : () )
95 # FIXME: using our here means that a Plack server will need to be
96 # restarted fairly regularly when working with this routine.
97 # A better option would be to use Koha::Cache and use a cache
98 # that actually works in a persistent environment, but as a
99 # short-term fix, our will work.
102 my ( $module, $code, $branchcode, $message_transport_type ) = @_;
103 $message_transport_type ||= 'email';
106 if ( C4::Context->preference('IndependentBranches')
108 and C4::Context->userenv ) {
110 $branchcode = C4::Context->userenv->{'branch'};
114 if ( my $l = $letter{$module}{$code}{$branchcode}{$message_transport_type} ) {
115 return { %$l }; # deep copy
118 my $dbh = C4::Context->dbh;
119 my $sth = $dbh->prepare(q{
122 WHERE module=? AND code=? AND (branchcode = ? OR branchcode = '') AND message_transport_type = ?
123 ORDER BY branchcode DESC LIMIT 1
125 $sth->execute( $module, $code, $branchcode, $message_transport_type );
126 my $line = $sth->fetchrow_hashref
128 $line->{'content-type'} = 'text/html; charset="UTF-8"' if $line->{is_html};
129 $letter{$module}{$code}{$branchcode}{$message_transport_type} = $line;
133 =head2 addalert ($borrowernumber, $type, $externalid)
136 - $borrowernumber : the number of the borrower subscribing to the alert
137 - $type : the type of alert.
138 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
140 create an alert and return the alertid (primary key)
145 my ( $borrowernumber, $type, $externalid ) = @_;
146 my $dbh = C4::Context->dbh;
149 "insert into alert (borrowernumber, type, externalid) values (?,?,?)");
150 $sth->execute( $borrowernumber, $type, $externalid );
152 # get the alert number newly created and return it
153 my $alertid = $dbh->{'mysql_insertid'};
157 =head2 delalert ($alertid)
160 - alertid : the alert id
166 my $alertid = shift or die "delalert() called without valid argument (alertid)"; # it's gonna die anyway.
167 $debug and warn "delalert: deleting alertid $alertid";
168 my $sth = C4::Context->dbh->prepare("delete from alert where alertid=?");
169 $sth->execute($alertid);
172 =head2 getalert ([$borrowernumber], [$type], [$externalid])
175 - $borrowernumber : the number of the borrower subscribing to the alert
176 - $type : the type of alert.
177 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
178 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.
183 my ( $borrowernumber, $type, $externalid ) = @_;
184 my $dbh = C4::Context->dbh;
185 my $query = "SELECT a.*, b.branchcode FROM alert a JOIN borrowers b USING(borrowernumber) WHERE";
187 if ($borrowernumber and $borrowernumber =~ /^\d+$/) {
188 $query .= " borrowernumber=? AND ";
189 push @bind, $borrowernumber;
192 $query .= " type=? AND ";
196 $query .= " externalid=? AND ";
197 push @bind, $externalid;
199 $query =~ s/ AND $//;
200 my $sth = $dbh->prepare($query);
201 $sth->execute(@bind);
202 return $sth->fetchall_arrayref({});
205 =head2 findrelatedto($type, $externalid)
208 - $type : the type of alert
209 - $externalid : the id of the "object" to query
211 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.
212 When type=issue, the id is related to a subscriptionid and this sub returns the name of the biblio.
217 # When type=virtual, the id is related to a virtual shelf and this sub returns the name of the sub
220 my $type = shift or return;
221 my $externalid = shift or return;
222 my $q = ($type eq 'issue' ) ?
223 "select title as result from subscription left join biblio on subscription.biblionumber=biblio.biblionumber where subscriptionid=?" :
224 ($type eq 'borrower') ?
225 "select concat(firstname,' ',surname) from borrowers where borrowernumber=?" : undef;
227 warn "findrelatedto(): Illegal type '$type'";
230 my $sth = C4::Context->dbh->prepare($q);
231 $sth->execute($externalid);
232 my ($result) = $sth->fetchrow;
239 - $type : the type of alert
240 - $externalid : the id of the "object" to query
241 - $letter_code : the letter to send.
243 send an alert to all borrowers having put an alert on a given subject.
248 my ( $type, $externalid, $letter_code ) = @_;
249 my $dbh = C4::Context->dbh;
250 if ( $type eq 'issue' ) {
252 # prepare the letter...
253 # search the biblionumber
256 "SELECT biblionumber FROM subscription WHERE subscriptionid=?");
257 $sth->execute($externalid);
258 my ($biblionumber) = $sth->fetchrow
259 or warn( "No subscription for '$externalid'" ),
263 # find the list of borrowers to alert
264 my $alerts = getalert( '', 'issue', $externalid );
266 my $borinfo = C4::Members::GetMember('borrowernumber' => $_->{'borrowernumber'});
267 my $email = $borinfo->{email} or next;
269 # warn "sending issues...";
270 my $userenv = C4::Context->userenv;
271 my $branchdetails = GetBranchDetail($_->{'branchcode'});
272 my $letter = GetPreparedLetter (
274 letter_code => $letter_code,
275 branchcode => $userenv->{branch},
277 'branches' => $_->{branchcode},
278 'biblio' => $biblionumber,
279 'biblioitems' => $biblionumber,
280 'borrowers' => $borinfo,
286 my $message = Koha::Email->new();
287 my %mail = $message->create_message_headers(
290 from => $branchdetails->{'branchemail'},
291 replyto => $branchdetails->{'branchreplyto'},
292 sender => $branchdetails->{'branchreturnpath'},
293 subject => Encode::encode( "utf8", "" . $letter->{title} ),
295 Encode::encode( "utf8", "" . $letter->{content} ),
296 contenttype => 'text/plain; charset="utf8"',
300 sendmail(%mail) or carp $Mail::Sendmail::error;
303 elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' ) {
305 # prepare the letter...
306 # search the biblionumber
307 my $strsth = $type eq 'claimacquisition'
309 SELECT aqorders.*,aqbasket.*,biblio.*,biblioitems.*
311 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
312 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
313 LEFT JOIN biblioitems ON aqorders.biblionumber=biblioitems.biblionumber
314 WHERE aqorders.ordernumber IN (
317 SELECT serial.*,subscription.*, biblio.*, aqbooksellers.*,
318 aqbooksellers.id AS booksellerid
320 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
321 LEFT JOIN biblio ON serial.biblionumber=biblio.biblionumber
322 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
323 WHERE serial.serialid IN (
327 carp "No Order seleted";
328 return { error => "no_order_seleted" };
331 $strsth .= join( ",", @$externalid ) . ")";
332 my $sthorders = $dbh->prepare($strsth);
334 my $dataorders = $sthorders->fetchall_arrayref( {} );
337 $dbh->prepare("select * from aqbooksellers where id=?");
338 $sthbookseller->execute( $dataorders->[0]->{booksellerid} );
339 my $databookseller = $sthbookseller->fetchrow_hashref;
340 my $addressee = $type eq 'claimacquisition' ? 'acqprimary' : 'serialsprimary';
342 $dbh->prepare("SELECT * FROM aqcontacts WHERE booksellerid=? AND $type=1 ORDER BY $addressee DESC");
343 $sthcontact->execute( $dataorders->[0]->{booksellerid} );
344 my $datacontact = $sthcontact->fetchrow_hashref;
348 push @email, $databookseller->{bookselleremail} if $databookseller->{bookselleremail};
349 push @email, $datacontact->{email} if ( $datacontact && $datacontact->{email} );
351 warn "Bookseller $dataorders->[0]->{booksellerid} without emails";
352 return { error => "no_email" };
355 while ($addlcontact = $sthcontact->fetchrow_hashref) {
356 push @cc, $addlcontact->{email} if ( $addlcontact && $addlcontact->{email} );
359 my $userenv = C4::Context->userenv;
360 my $letter = GetPreparedLetter (
362 letter_code => $letter_code,
363 branchcode => $userenv->{branch},
365 'branches' => $userenv->{branch},
366 'aqbooksellers' => $databookseller,
367 'aqcontacts' => $datacontact,
369 repeat => $dataorders,
373 # Remove the order tag
374 $letter->{content} =~ s/<order>(.*?)<\/order>/$1/gxms;
378 To => join( ',', @email),
379 Cc => join( ',', @cc),
380 From => $userenv->{emailaddress},
381 Subject => Encode::encode( "utf8", "" . $letter->{title} ),
382 Message => Encode::encode( "utf8", "" . $letter->{content} ),
383 'Content-Type' => 'text/plain; charset="utf8"',
386 $mail{'Reply-to'} = C4::Context->preference('ReplytoDefault')
387 if C4::Context->preference('ReplytoDefault');
388 $mail{'Sender'} = C4::Context->preference('ReturnpathDefault')
389 if C4::Context->preference('ReturnpathDefault');
391 unless ( sendmail(%mail) ) {
392 carp $Mail::Sendmail::error;
393 return { error => $Mail::Sendmail::error };
398 $type eq 'claimissues' ? "CLAIM ISSUE" : "ACQUISITION CLAIM",
401 . join( ',', @email )
406 ) if C4::Context->preference("LetterLog");
408 # send an "account details" notice to a newly created user
409 elsif ( $type eq 'members' ) {
410 my $branchdetails = GetBranchDetail($externalid->{'branchcode'});
411 my $letter = GetPreparedLetter (
413 letter_code => $letter_code,
414 branchcode => $externalid->{'branchcode'},
416 'branches' => $branchdetails,
417 'borrowers' => $externalid->{'borrowernumber'},
419 substitute => { 'borrowers.password' => $externalid->{'password'} },
422 return { error => "no_email" } unless $externalid->{'emailaddr'};
423 my $email = Koha::Email->new();
424 my %mail = $email->create_message_headers(
426 to => $externalid->{'emailaddr'},
427 from => $branchdetails->{'branchemail'},
428 replyto => $branchdetails->{'branchreplyto'},
429 sender => $branchdetails->{'branchreturnpath'},
430 subject => Encode::encode( "utf8", "" . $letter->{'title'} ),
431 message => Encode::encode( "utf8", "" . $letter->{'content'} ),
432 contenttype => 'text/plain; charset="utf8"'
435 sendmail(%mail) or carp $Mail::Sendmail::error;
439 =head2 GetPreparedLetter( %params )
442 module => letter module, mandatory
443 letter_code => letter code, mandatory
444 branchcode => for letter selection, if missing default system letter taken
445 tables => a hashref with table names as keys. Values are either:
446 - a scalar - primary key value
447 - an arrayref - primary key values
448 - a hashref - full record
449 substitute => custom substitution key/value pairs
450 repeat => records to be substituted on consecutive lines:
451 - an arrayref - tries to guess what needs substituting by
452 taking remaining << >> tokensr; not recommended
453 - a hashref token => @tables - replaces <token> << >> << >> </token>
454 subtemplate for each @tables row; table is a hashref as above
455 want_librarian => boolean, if set to true triggers librarian details
456 substitution from the userenv
458 letter fields hashref (title & content useful)
462 sub GetPreparedLetter {
465 my $module = $params{module} or croak "No module";
466 my $letter_code = $params{letter_code} or croak "No letter_code";
467 my $branchcode = $params{branchcode} || '';
468 my $mtt = $params{message_transport_type} || 'email';
470 my $letter = getletter( $module, $letter_code, $branchcode, $mtt )
471 or warn( "No $module $letter_code letter transported by " . $mtt ),
474 my $tables = $params{tables};
475 my $substitute = $params{substitute};
476 my $repeat = $params{repeat};
477 $tables || $substitute || $repeat
478 or carp( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
480 my $want_librarian = $params{want_librarian};
483 while ( my ($token, $val) = each %$substitute ) {
484 $letter->{title} =~ s/<<$token>>/$val/g;
485 $letter->{content} =~ s/<<$token>>/$val/g;
489 my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
490 $letter->{content} =~ s/<<OPACBaseURL>>/$OPACBaseURL/go;
492 if ($want_librarian) {
493 # parsing librarian name
494 my $userenv = C4::Context->userenv;
495 $letter->{content} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
496 $letter->{content} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
497 $letter->{content} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
500 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
503 if (ref ($repeat) eq 'ARRAY' ) {
504 $repeat_no_enclosing_tags = $repeat;
506 $repeat_enclosing_tags = $repeat;
510 if ($repeat_enclosing_tags) {
511 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
512 if ( $letter->{content} =~ m!<$tag>(.*)</$tag>!s ) {
515 my %subletter = ( title => '', content => $subcontent );
516 _substitute_tables( \%subletter, $_ );
519 $letter->{content} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
525 _substitute_tables( $letter, $tables );
528 if ($repeat_no_enclosing_tags) {
529 if ( $letter->{content} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
534 $c =~ s/<<count>>/$i/go;
535 foreach my $field ( keys %{$_} ) {
536 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
540 } @$repeat_no_enclosing_tags;
542 my $replaceby = join( "\n", @lines );
543 $letter->{content} =~ s/\Q$line\E/$replaceby/s;
547 $letter->{content} =~ s/<<\S*>>//go; #remove any stragglers
548 # $letter->{content} =~ s/<<[^>]*>>//go;
553 sub _substitute_tables {
554 my ( $letter, $tables ) = @_;
555 while ( my ($table, $param) = each %$tables ) {
558 my $ref = ref $param;
561 if ($ref && $ref eq 'HASH') {
565 my $sth = _parseletter_sth($table);
567 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
570 $sth->execute( $ref ? @$param : $param );
572 $values = $sth->fetchrow_hashref;
576 _parseletter ( $letter, $table, $values );
580 sub _parseletter_sth {
584 carp "ERROR: _parseletter_sth() called without argument (table)";
587 # NOTE: we used to check whether we had a statement handle cached in
588 # a %handles module-level variable. This was a dumb move and
589 # broke things for the rest of us. prepare_cached is a better
590 # way to cache statement handles anyway.
592 ($table eq 'biblio' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
593 ($table eq 'biblioitems' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
594 ($table eq 'items' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
595 ($table eq 'issues' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
596 ($table eq 'old_issues' ) ? "SELECT * FROM $table WHERE itemnumber = ? ORDER BY timestamp DESC LIMIT 1" :
597 ($table eq 'reserves' ) ? "SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
598 ($table eq 'borrowers' ) ? "SELECT * FROM $table WHERE borrowernumber = ?" :
599 ($table eq 'branches' ) ? "SELECT * FROM $table WHERE branchcode = ?" :
600 ($table eq 'suggestions' ) ? "SELECT * FROM $table WHERE suggestionid = ?" :
601 ($table eq 'aqbooksellers') ? "SELECT * FROM $table WHERE id = ?" :
602 ($table eq 'aqorders' ) ? "SELECT * FROM $table WHERE ordernumber = ?" :
603 ($table eq 'opac_news' ) ? "SELECT * FROM $table WHERE idnew = ?" :
604 ($table eq 'borrower_modifications') ? "SELECT * FROM $table WHERE verification_token = ?" :
607 warn "ERROR: No _parseletter_sth query for table '$table'";
608 return; # nothing to get
610 unless ($sth = C4::Context->dbh->prepare_cached($query)) {
611 warn "ERROR: Failed to prepare query: '$query'";
614 return $sth; # now cache is populated for that $table
617 =head2 _parseletter($letter, $table, $values)
620 - $letter : a hash to letter fields (title & content useful)
621 - $table : the Koha table to parse.
622 - $values : table record hashref
623 parse all fields from a table, and replace values in title & content with the appropriate value
624 (not exported sub, used only internally)
629 my ( $letter, $table, $values ) = @_;
631 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
632 my @waitingdate = split /-/, $values->{'waitingdate'};
634 $values->{'expirationdate'} = '';
635 if( C4::Context->preference('ExpireReservesMaxPickUpDelay') &&
636 C4::Context->preference('ReservesMaxPickUpDelay') ) {
637 my $dt = dt_from_string();
638 $dt->add( days => C4::Context->preference('ReservesMaxPickUpDelay') );
639 $values->{'expirationdate'} = output_pref({ dt => $dt, dateonly => 1 });
642 $values->{'waitingdate'} = output_pref({ dt => dt_from_string( $values->{'waitingdate'} ), dateonly => 1 });
646 if ($letter->{content} && $letter->{content} =~ /<<today>>/) {
647 my $todaysdate = output_pref( DateTime->now() );
648 $letter->{content} =~ s/<<today>>/$todaysdate/go;
651 while ( my ($field, $val) = each %$values ) {
652 my $replacetablefield = "<<$table.$field>>";
653 my $replacefield = "<<$field>>";
654 $val =~ s/\p{P}$// if $val && $table=~/biblio/;
655 #BZ 9886: Assuming that we want to eliminate ISBD punctuation here
656 #Therefore adding the test on biblio. This includes biblioitems,
657 #but excludes items. Removed unneeded global and lookahead.
659 $val = GetAuthorisedValueByCode ('ROADTYPE', $val, 0) if $table=~/^borrowers$/ && $field=~/^streettype$/;
660 my $replacedby = defined ($val) ? $val : '';
662 and not $replacedby =~ m|0000-00-00|
663 and not $replacedby =~ m|9999-12-31|
664 and $replacedby =~ m|^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$| )
666 # If the value is XXXX-YY-ZZ[ AA:BB:CC] we assume it is a date
667 my $dateonly = defined $1 ? 0 : 1; #$1 refers to the capture group wrapped in parentheses. In this case, that's the hours, minutes, seconds.
669 $replacedby = output_pref({ dt => dt_from_string( $replacedby ), dateonly => $dateonly });
671 warn "$replacedby seems to be a date but an error occurs on generating it ($@)" if $@;
673 ($letter->{title} ) and do {
674 $letter->{title} =~ s/$replacetablefield/$replacedby/g;
675 $letter->{title} =~ s/$replacefield/$replacedby/g;
677 ($letter->{content}) and do {
678 $letter->{content} =~ s/$replacetablefield/$replacedby/g;
679 $letter->{content} =~ s/$replacefield/$replacedby/g;
683 if ($table eq 'borrowers' && $letter->{content}) {
684 if ( my $attributes = GetBorrowerAttributes($values->{borrowernumber}) ) {
686 foreach (@$attributes) {
687 my $code = $_->{code};
688 my $val = $_->{value_description} || $_->{value};
689 $val =~ s/\p{P}(?=$)//g if $val;
690 next unless $val gt '';
692 push @{ $attr{$code} }, $val;
694 while ( my ($code, $val_ar) = each %attr ) {
695 my $replacefield = "<<borrower-attribute:$code>>";
696 my $replacedby = join ',', @$val_ar;
697 $letter->{content} =~ s/$replacefield/$replacedby/g;
706 my $success = EnqueueLetter( { letter => $letter,
707 borrowernumber => '12', message_transport_type => 'email' } )
709 places a letter in the message_queue database table, which will
710 eventually get processed (sent) by the process_message_queue.pl
711 cronjob when it calls SendQueuedMessages.
713 return message_id on success
718 my $params = shift or return;
720 return unless exists $params->{'letter'};
721 # return unless exists $params->{'borrowernumber'};
722 return unless exists $params->{'message_transport_type'};
724 my $content = $params->{letter}->{content};
725 $content =~ s/\s+//g if(defined $content);
726 if ( not defined $content or $content eq '' ) {
727 warn "Trying to add an empty message to the message queue" if $debug;
731 # If we have any attachments we should encode then into the body.
732 if ( $params->{'attachments'} ) {
733 $params->{'letter'} = _add_attachments(
734 { letter => $params->{'letter'},
735 attachments => $params->{'attachments'},
736 message => MIME::Lite->new( Type => 'multipart/mixed' ),
741 my $dbh = C4::Context->dbh();
742 my $statement = << 'ENDSQL';
743 INSERT INTO message_queue
744 ( borrowernumber, subject, content, metadata, letter_code, message_transport_type, status, time_queued, to_address, from_address, content_type )
746 ( ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ? )
749 my $sth = $dbh->prepare($statement);
750 my $result = $sth->execute(
751 $params->{'borrowernumber'}, # borrowernumber
752 $params->{'letter'}->{'title'}, # subject
753 $params->{'letter'}->{'content'}, # content
754 $params->{'letter'}->{'metadata'} || '', # metadata
755 $params->{'letter'}->{'code'} || '', # letter_code
756 $params->{'message_transport_type'}, # message_transport_type
758 $params->{'to_address'}, # to_address
759 $params->{'from_address'}, # from_address
760 $params->{'letter'}->{'content-type'}, # content_type
762 return $dbh->last_insert_id(undef,undef,'message_queue', undef);
765 =head2 SendQueuedMessages ([$hashref])
767 my $sent = SendQueuedMessages( { verbose => 1 } );
769 sends all of the 'pending' items in the message queue.
771 returns number of messages sent.
775 sub SendQueuedMessages {
778 my $unsent_messages = _get_unsent_messages();
779 MESSAGE: foreach my $message ( @$unsent_messages ) {
780 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
781 warn sprintf( 'sending %s message to patron: %s',
782 $message->{'message_transport_type'},
783 $message->{'borrowernumber'} || 'Admin' )
784 if $params->{'verbose'} or $debug;
785 # This is just begging for subclassing
786 next MESSAGE if ( lc($message->{'message_transport_type'}) eq 'rss' );
787 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
788 _send_message_by_email( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
790 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
791 _send_message_by_sms( $message );
794 return scalar( @$unsent_messages );
797 =head2 GetRSSMessages
799 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
801 returns a listref of all queued RSS messages for a particular person.
808 return unless $params;
809 return unless ref $params;
810 return unless $params->{'borrowernumber'};
812 return _get_unsent_messages( { message_transport_type => 'rss',
813 limit => $params->{'limit'},
814 borrowernumber => $params->{'borrowernumber'}, } );
817 =head2 GetPrintMessages
819 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
821 Returns a arrayref of all queued print messages (optionally, for a particular
826 sub GetPrintMessages {
827 my $params = shift || {};
829 return _get_unsent_messages( { message_transport_type => 'print',
830 borrowernumber => $params->{'borrowernumber'},
834 =head2 GetQueuedMessages ([$hashref])
836 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
838 fetches messages out of the message queue.
841 list of hashes, each has represents a message in the message queue.
845 sub GetQueuedMessages {
848 my $dbh = C4::Context->dbh();
849 my $statement = << 'ENDSQL';
850 SELECT message_id, borrowernumber, subject, content, message_transport_type, status, time_queued
856 if ( exists $params->{'borrowernumber'} ) {
857 push @whereclauses, ' borrowernumber = ? ';
858 push @query_params, $params->{'borrowernumber'};
861 if ( @whereclauses ) {
862 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
865 if ( defined $params->{'limit'} ) {
866 $statement .= ' LIMIT ? ';
867 push @query_params, $params->{'limit'};
870 my $sth = $dbh->prepare( $statement );
871 my $result = $sth->execute( @query_params );
872 return $sth->fetchall_arrayref({});
875 =head2 GetMessageTransportTypes
877 my @mtt = GetMessageTransportTypes();
879 returns an arrayref of transport types
883 sub GetMessageTransportTypes {
884 my $dbh = C4::Context->dbh();
885 my $mtts = $dbh->selectcol_arrayref("
886 SELECT message_transport_type
887 FROM message_transport_types
888 ORDER BY message_transport_type
893 =head2 _add_attachements
896 letter - the standard letter hashref
897 attachments - listref of attachments. each attachment is a hashref of:
898 type - the mime type, like 'text/plain'
899 content - the actual attachment
900 filename - the name of the attachment.
901 message - a MIME::Lite object to attach these to.
903 returns your letter object, with the content updated.
907 sub _add_attachments {
910 my $letter = $params->{'letter'};
911 my $attachments = $params->{'attachments'};
912 return $letter unless @$attachments;
913 my $message = $params->{'message'};
915 # First, we have to put the body in as the first attachment
917 Type => $letter->{'content-type'} || 'TEXT',
918 Data => $letter->{'is_html'}
919 ? _wrap_html($letter->{'content'}, $letter->{'title'})
920 : $letter->{'content'},
923 foreach my $attachment ( @$attachments ) {
925 Type => $attachment->{'type'},
926 Data => $attachment->{'content'},
927 Filename => $attachment->{'filename'},
930 # we're forcing list context here to get the header, not the count back from grep.
931 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
932 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
933 $letter->{'content'} = $message->body_as_string;
939 sub _get_unsent_messages {
942 my $dbh = C4::Context->dbh();
943 my $statement = << 'ENDSQL';
944 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
945 FROM message_queue mq
946 LEFT JOIN borrowers b ON b.borrowernumber = mq.borrowernumber
950 my @query_params = ('pending');
952 if ( $params->{'message_transport_type'} ) {
953 $statement .= ' AND message_transport_type = ? ';
954 push @query_params, $params->{'message_transport_type'};
956 if ( $params->{'borrowernumber'} ) {
957 $statement .= ' AND borrowernumber = ? ';
958 push @query_params, $params->{'borrowernumber'};
960 if ( $params->{'limit'} ) {
961 $statement .= ' limit ? ';
962 push @query_params, $params->{'limit'};
966 $debug and warn "_get_unsent_messages SQL: $statement";
967 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
968 my $sth = $dbh->prepare( $statement );
969 my $result = $sth->execute( @query_params );
970 return $sth->fetchall_arrayref({});
973 sub _send_message_by_email {
974 my $message = shift or return;
975 my ($username, $password, $method) = @_;
977 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
978 my $to_address = $message->{'to_address'};
979 unless ($to_address) {
981 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
982 _set_message_status( { message_id => $message->{'message_id'},
983 status => 'failed' } );
986 $to_address = C4::Members::GetNoticeEmailAddress( $message->{'borrowernumber'} );
987 unless ($to_address) {
988 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
989 # warning too verbose for this more common case?
990 _set_message_status( { message_id => $message->{'message_id'},
991 status => 'failed' } );
996 my $utf8 = decode('MIME-Header', $message->{'subject'} );
997 $message->{subject}= encode('MIME-Header', $utf8);
998 my $subject = encode('utf8', $message->{'subject'});
999 my $content = encode('utf8', $message->{'content'});
1000 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
1001 my $is_html = $content_type =~ m/html/io;
1002 my $branch_email = undef;
1003 my $branch_replyto = undef;
1004 my $branch_returnpath = undef;
1006 my $branchdetail = GetBranchDetail( $member->{'branchcode'} );
1007 $branch_email = $branchdetail->{'branchemail'};
1008 $branch_replyto = $branchdetail->{'branchreplyto'};
1009 $branch_returnpath = $branchdetail->{'branchreturnpath'};
1011 my $email = Koha::Email->new();
1012 my %sendmail_params = $email->create_message_headers(
1015 from => $message->{'from_address'} || $branch_email,
1016 replyto => $branch_replyto,
1017 sender => $branch_returnpath,
1018 subject => $subject,
1019 message => $is_html ? _wrap_html( $content, $subject ) : $content,
1020 contenttype => $content_type
1024 $sendmail_params{'Auth'} = {user => $username, pass => $password, method => $method} if $username;
1025 if ( my $bcc = C4::Context->preference('OverdueNoticeBcc') ) {
1026 $sendmail_params{ Bcc } = $bcc;
1029 _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
1030 if ( sendmail( %sendmail_params ) ) {
1031 _set_message_status( { message_id => $message->{'message_id'},
1032 status => 'sent' } );
1035 _set_message_status( { message_id => $message->{'message_id'},
1036 status => 'failed' } );
1037 carp $Mail::Sendmail::error;
1043 my ($content, $title) = @_;
1045 my $css = C4::Context->preference("NoticeCSS") || '';
1046 $css = qq{<link rel="stylesheet" type="text/css" href="$css">} if $css;
1048 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1049 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1050 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
1052 <title>$title</title>
1053 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1064 my ( $message ) = @_;
1065 my $dbh = C4::Context->dbh;
1066 my $count = $dbh->selectrow_array(q|
1069 WHERE message_transport_type = ?
1070 AND borrowernumber = ?
1072 AND CAST(time_queued AS date) = CAST(NOW() AS date)
1075 |, {}, $message->{message_transport_type}, $message->{borrowernumber}, $message->{letter_code}, $message->{content} );
1079 sub _send_message_by_sms {
1080 my $message = shift or return;
1081 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
1083 unless ( $member->{smsalertnumber} ) {
1084 _set_message_status( { message_id => $message->{'message_id'},
1085 status => 'failed' } );
1089 if ( _is_duplicate( $message ) ) {
1090 _set_message_status( { message_id => $message->{'message_id'},
1091 status => 'failed' } );
1095 my $success = C4::SMS->send_sms( { destination => $member->{'smsalertnumber'},
1096 message => $message->{'content'},
1098 _set_message_status( { message_id => $message->{'message_id'},
1099 status => ($success ? 'sent' : 'failed') } );
1103 sub _update_message_to_address {
1105 my $dbh = C4::Context->dbh();
1106 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
1109 sub _set_message_status {
1110 my $params = shift or return;
1112 foreach my $required_parameter ( qw( message_id status ) ) {
1113 return unless exists $params->{ $required_parameter };
1116 my $dbh = C4::Context->dbh();
1117 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1118 my $sth = $dbh->prepare( $statement );
1119 my $result = $sth->execute( $params->{'status'},
1120 $params->{'message_id'} );