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} || '';
455 my $letter = getletter( $module, $letter_code, $branchcode, $params{message_transport_type} )
456 or warn( "No $module $letter_code letter"),
459 my $tables = $params{tables};
460 my $substitute = $params{substitute};
461 my $repeat = $params{repeat};
462 $tables || $substitute || $repeat
463 or carp( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
465 my $want_librarian = $params{want_librarian};
468 while ( my ($token, $val) = each %$substitute ) {
469 $letter->{title} =~ s/<<$token>>/$val/g;
470 $letter->{content} =~ s/<<$token>>/$val/g;
474 my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
475 $letter->{content} =~ s/<<OPACBaseURL>>/$OPACBaseURL/go;
477 if ($want_librarian) {
478 # parsing librarian name
479 my $userenv = C4::Context->userenv;
480 $letter->{content} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
481 $letter->{content} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
482 $letter->{content} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
485 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
488 if (ref ($repeat) eq 'ARRAY' ) {
489 $repeat_no_enclosing_tags = $repeat;
491 $repeat_enclosing_tags = $repeat;
495 if ($repeat_enclosing_tags) {
496 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
497 if ( $letter->{content} =~ m!<$tag>(.*)</$tag>!s ) {
500 my %subletter = ( title => '', content => $subcontent );
501 _substitute_tables( \%subletter, $_ );
504 $letter->{content} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
510 _substitute_tables( $letter, $tables );
513 if ($repeat_no_enclosing_tags) {
514 if ( $letter->{content} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
519 $c =~ s/<<count>>/$i/go;
520 foreach my $field ( keys %{$_} ) {
521 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
525 } @$repeat_no_enclosing_tags;
527 my $replaceby = join( "\n", @lines );
528 $letter->{content} =~ s/\Q$line\E/$replaceby/s;
532 $letter->{content} =~ s/<<\S*>>//go; #remove any stragglers
533 # $letter->{content} =~ s/<<[^>]*>>//go;
538 sub _substitute_tables {
539 my ( $letter, $tables ) = @_;
540 while ( my ($table, $param) = each %$tables ) {
543 my $ref = ref $param;
546 if ($ref && $ref eq 'HASH') {
551 my $sth = _parseletter_sth($table);
553 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
556 $sth->execute( $ref ? @$param : $param );
558 $values = $sth->fetchrow_hashref;
562 _parseletter ( $letter, $table, $values );
566 sub _parseletter_sth {
570 carp "ERROR: _parseletter_sth() called without argument (table)";
573 # NOTE: we used to check whether we had a statement handle cached in
574 # a %handles module-level variable. This was a dumb move and
575 # broke things for the rest of us. prepare_cached is a better
576 # way to cache statement handles anyway.
578 ($table eq 'biblio' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
579 ($table eq 'biblioitems' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
580 ($table eq 'items' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
581 ($table eq 'issues' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
582 ($table eq 'old_issues' ) ? "SELECT * FROM $table WHERE itemnumber = ? ORDER BY timestamp DESC LIMIT 1" :
583 ($table eq 'reserves' ) ? "SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
584 ($table eq 'borrowers' ) ? "SELECT * FROM $table WHERE borrowernumber = ?" :
585 ($table eq 'branches' ) ? "SELECT * FROM $table WHERE branchcode = ?" :
586 ($table eq 'suggestions' ) ? "SELECT * FROM $table WHERE suggestionid = ?" :
587 ($table eq 'aqbooksellers') ? "SELECT * FROM $table WHERE id = ?" :
588 ($table eq 'aqorders' ) ? "SELECT * FROM $table WHERE ordernumber = ?" :
589 ($table eq 'opac_news' ) ? "SELECT * FROM $table WHERE idnew = ?" :
590 ($table eq 'borrower_modifications') ? "SELECT * FROM $table WHERE borrowernumber = ? OR verification_token =?":
593 warn "ERROR: No _parseletter_sth query for table '$table'";
594 return; # nothing to get
596 unless ($sth = C4::Context->dbh->prepare_cached($query)) {
597 warn "ERROR: Failed to prepare query: '$query'";
600 return $sth; # now cache is populated for that $table
603 =head2 _parseletter($letter, $table, $values)
606 - $letter : a hash to letter fields (title & content useful)
607 - $table : the Koha table to parse.
608 - $values : table record hashref
609 parse all fields from a table, and replace values in title & content with the appropriate value
610 (not exported sub, used only internally)
615 my ( $letter, $table, $values ) = @_;
617 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
618 my @waitingdate = split /-/, $values->{'waitingdate'};
620 $values->{'expirationdate'} = '';
621 if( C4::Context->preference('ExpireReservesMaxPickUpDelay') &&
622 C4::Context->preference('ReservesMaxPickUpDelay') ) {
623 my $dt = dt_from_string();
624 $dt->add( days => C4::Context->preference('ReservesMaxPickUpDelay') );
625 $values->{'expirationdate'} = output_pref({ dt => $dt, dateonly => 1 });
628 $values->{'waitingdate'} = output_pref({ dt => dt_from_string( $values->{'waitingdate'} ), dateonly => 1 });
632 if ($letter->{content} && $letter->{content} =~ /<<today>>/) {
633 my $todaysdate = output_pref( DateTime->now() );
634 $letter->{content} =~ s/<<today>>/$todaysdate/go;
637 while ( my ($field, $val) = each %$values ) {
638 my $replacetablefield = "<<$table.$field>>";
639 my $replacefield = "<<$field>>";
640 $val =~ s/\p{P}$// if $val && $table=~/biblio/;
641 #BZ 9886: Assuming that we want to eliminate ISBD punctuation here
642 #Therefore adding the test on biblio. This includes biblioitems,
643 #but excludes items. Removed unneeded global and lookahead.
645 $val = GetAuthorisedValueByCode ('ROADTYPE', $val, 0) if $table=~/^borrowers$/ && $field=~/^streettype$/;
646 my $replacedby = defined ($val) ? $val : '';
647 ($letter->{title} ) and do {
648 $letter->{title} =~ s/$replacetablefield/$replacedby/g;
649 $letter->{title} =~ s/$replacefield/$replacedby/g;
651 ($letter->{content}) and do {
652 $letter->{content} =~ s/$replacetablefield/$replacedby/g;
653 $letter->{content} =~ s/$replacefield/$replacedby/g;
657 if ($table eq 'borrowers' && $letter->{content}) {
658 if ( my $attributes = GetBorrowerAttributes($values->{borrowernumber}) ) {
660 foreach (@$attributes) {
661 my $code = $_->{code};
662 my $val = $_->{value_description} || $_->{value};
663 $val =~ s/\p{P}(?=$)//g if $val;
664 next unless $val gt '';
666 push @{ $attr{$code} }, $val;
668 while ( my ($code, $val_ar) = each %attr ) {
669 my $replacefield = "<<borrower-attribute:$code>>";
670 my $replacedby = join ',', @$val_ar;
671 $letter->{content} =~ s/$replacefield/$replacedby/g;
680 my $success = EnqueueLetter( { letter => $letter,
681 borrowernumber => '12', message_transport_type => 'email' } )
683 places a letter in the message_queue database table, which will
684 eventually get processed (sent) by the process_message_queue.pl
685 cronjob when it calls SendQueuedMessages.
687 return message_id on success
692 my $params = shift or return;
694 return unless exists $params->{'letter'};
695 # return unless exists $params->{'borrowernumber'};
696 return unless exists $params->{'message_transport_type'};
698 my $content = $params->{letter}->{content};
699 $content =~ s/\s+//g if(defined $content);
700 if ( not defined $content or $content eq '' ) {
701 warn "Trying to add an empty message to the message queue" if $debug;
705 # If we have any attachments we should encode then into the body.
706 if ( $params->{'attachments'} ) {
707 $params->{'letter'} = _add_attachments(
708 { letter => $params->{'letter'},
709 attachments => $params->{'attachments'},
710 message => MIME::Lite->new( Type => 'multipart/mixed' ),
715 my $dbh = C4::Context->dbh();
716 my $statement = << 'ENDSQL';
717 INSERT INTO message_queue
718 ( borrowernumber, subject, content, metadata, letter_code, message_transport_type, status, time_queued, to_address, from_address, content_type )
720 ( ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ? )
723 my $sth = $dbh->prepare($statement);
724 my $result = $sth->execute(
725 $params->{'borrowernumber'}, # borrowernumber
726 $params->{'letter'}->{'title'}, # subject
727 $params->{'letter'}->{'content'}, # content
728 $params->{'letter'}->{'metadata'} || '', # metadata
729 $params->{'letter'}->{'code'} || '', # letter_code
730 $params->{'message_transport_type'}, # message_transport_type
732 $params->{'to_address'}, # to_address
733 $params->{'from_address'}, # from_address
734 $params->{'letter'}->{'content-type'}, # content_type
736 return $dbh->last_insert_id(undef,undef,'message_queue', undef);
739 =head2 SendQueuedMessages ([$hashref])
741 my $sent = SendQueuedMessages( { verbose => 1 } );
743 sends all of the 'pending' items in the message queue.
745 returns number of messages sent.
749 sub SendQueuedMessages {
752 my $unsent_messages = _get_unsent_messages();
753 MESSAGE: foreach my $message ( @$unsent_messages ) {
754 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
755 warn sprintf( 'sending %s message to patron: %s',
756 $message->{'message_transport_type'},
757 $message->{'borrowernumber'} || 'Admin' )
758 if $params->{'verbose'} or $debug;
759 # This is just begging for subclassing
760 next MESSAGE if ( lc($message->{'message_transport_type'}) eq 'rss' );
761 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
762 _send_message_by_email( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
764 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
765 _send_message_by_sms( $message );
768 return scalar( @$unsent_messages );
771 =head2 GetRSSMessages
773 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
775 returns a listref of all queued RSS messages for a particular person.
782 return unless $params;
783 return unless ref $params;
784 return unless $params->{'borrowernumber'};
786 return _get_unsent_messages( { message_transport_type => 'rss',
787 limit => $params->{'limit'},
788 borrowernumber => $params->{'borrowernumber'}, } );
791 =head2 GetPrintMessages
793 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
795 Returns a arrayref of all queued print messages (optionally, for a particular
800 sub GetPrintMessages {
801 my $params = shift || {};
803 return _get_unsent_messages( { message_transport_type => 'print',
804 borrowernumber => $params->{'borrowernumber'},
808 =head2 GetQueuedMessages ([$hashref])
810 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
812 fetches messages out of the message queue.
815 list of hashes, each has represents a message in the message queue.
819 sub GetQueuedMessages {
822 my $dbh = C4::Context->dbh();
823 my $statement = << 'ENDSQL';
824 SELECT message_id, borrowernumber, subject, content, message_transport_type, status, time_queued
830 if ( exists $params->{'borrowernumber'} ) {
831 push @whereclauses, ' borrowernumber = ? ';
832 push @query_params, $params->{'borrowernumber'};
835 if ( @whereclauses ) {
836 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
839 if ( defined $params->{'limit'} ) {
840 $statement .= ' LIMIT ? ';
841 push @query_params, $params->{'limit'};
844 my $sth = $dbh->prepare( $statement );
845 my $result = $sth->execute( @query_params );
846 return $sth->fetchall_arrayref({});
849 =head2 GetMessageTransportTypes
851 my @mtt = GetMessageTransportTypes();
853 returns an arrayref of transport types
857 sub GetMessageTransportTypes {
858 my $dbh = C4::Context->dbh();
859 my $mtts = $dbh->selectcol_arrayref("
860 SELECT message_transport_type
861 FROM message_transport_types
862 ORDER BY message_transport_type
867 =head2 _add_attachements
870 letter - the standard letter hashref
871 attachments - listref of attachments. each attachment is a hashref of:
872 type - the mime type, like 'text/plain'
873 content - the actual attachment
874 filename - the name of the attachment.
875 message - a MIME::Lite object to attach these to.
877 returns your letter object, with the content updated.
881 sub _add_attachments {
884 my $letter = $params->{'letter'};
885 my $attachments = $params->{'attachments'};
886 return $letter unless @$attachments;
887 my $message = $params->{'message'};
889 # First, we have to put the body in as the first attachment
891 Type => $letter->{'content-type'} || 'TEXT',
892 Data => $letter->{'is_html'}
893 ? _wrap_html($letter->{'content'}, $letter->{'title'})
894 : $letter->{'content'},
897 foreach my $attachment ( @$attachments ) {
899 Type => $attachment->{'type'},
900 Data => $attachment->{'content'},
901 Filename => $attachment->{'filename'},
904 # we're forcing list context here to get the header, not the count back from grep.
905 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
906 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
907 $letter->{'content'} = $message->body_as_string;
913 sub _get_unsent_messages {
916 my $dbh = C4::Context->dbh();
917 my $statement = << 'ENDSQL';
918 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
919 FROM message_queue mq
920 LEFT JOIN borrowers b ON b.borrowernumber = mq.borrowernumber
924 my @query_params = ('pending');
926 if ( $params->{'message_transport_type'} ) {
927 $statement .= ' AND message_transport_type = ? ';
928 push @query_params, $params->{'message_transport_type'};
930 if ( $params->{'borrowernumber'} ) {
931 $statement .= ' AND borrowernumber = ? ';
932 push @query_params, $params->{'borrowernumber'};
934 if ( $params->{'limit'} ) {
935 $statement .= ' limit ? ';
936 push @query_params, $params->{'limit'};
940 $debug and warn "_get_unsent_messages SQL: $statement";
941 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
942 my $sth = $dbh->prepare( $statement );
943 my $result = $sth->execute( @query_params );
944 return $sth->fetchall_arrayref({});
947 sub _send_message_by_email {
948 my $message = shift or return;
949 my ($username, $password, $method) = @_;
951 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
952 my $to_address = $message->{'to_address'};
953 unless ($to_address) {
955 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
956 _set_message_status( { message_id => $message->{'message_id'},
957 status => 'failed' } );
960 $to_address = C4::Members::GetNoticeEmailAddress( $message->{'borrowernumber'} );
961 unless ($to_address) {
962 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
963 # warning too verbose for this more common case?
964 _set_message_status( { message_id => $message->{'message_id'},
965 status => 'failed' } );
970 my $utf8 = decode('MIME-Header', $message->{'subject'} );
971 $message->{subject}= encode('MIME-Header', $utf8);
972 my $subject = encode('utf8', $message->{'subject'});
973 my $content = encode('utf8', $message->{'content'});
974 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
975 my $is_html = $content_type =~ m/html/io;
977 my $branch_email = ( $member ) ? GetBranchDetail( $member->{'branchcode'} )->{'branchemail'} : undef;
979 my %sendmail_params = (
981 From => $message->{'from_address'} || $branch_email || C4::Context->preference('KohaAdminEmailAddress'),
984 Message => $is_html ? _wrap_html($content, $subject) : $content,
985 'content-type' => $content_type,
987 $sendmail_params{'Auth'} = {user => $username, pass => $password, method => $method} if $username;
988 if ( my $bcc = C4::Context->preference('OverdueNoticeBcc') ) {
989 $sendmail_params{ Bcc } = $bcc;
992 _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
993 if ( sendmail( %sendmail_params ) ) {
994 _set_message_status( { message_id => $message->{'message_id'},
995 status => 'sent' } );
998 _set_message_status( { message_id => $message->{'message_id'},
999 status => 'failed' } );
1000 carp $Mail::Sendmail::error;
1006 my ($content, $title) = @_;
1008 my $css = C4::Context->preference("NoticeCSS") || '';
1009 $css = qq{<link rel="stylesheet" type="text/css" href="$css">} if $css;
1011 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1012 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1013 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
1015 <title>$title</title>
1016 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1026 sub _send_message_by_sms {
1027 my $message = shift or return;
1028 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
1030 unless ( $member->{smsalertnumber} ) {
1031 _set_message_status( { message_id => $message->{'message_id'},
1032 status => 'failed' } );
1036 my $success = C4::SMS->send_sms( { destination => $member->{'smsalertnumber'},
1037 message => $message->{'content'},
1039 _set_message_status( { message_id => $message->{'message_id'},
1040 status => ($success ? 'sent' : 'failed') } );
1044 sub _update_message_to_address {
1046 my $dbh = C4::Context->dbh();
1047 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
1050 sub _set_message_status {
1051 my $params = shift or return;
1053 foreach my $required_parameter ( qw( message_id status ) ) {
1054 return unless exists $params->{ $required_parameter };
1057 my $dbh = C4::Context->dbh();
1058 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1059 my $sth = $dbh->prepare( $statement );
1060 my $result = $sth->execute( $params->{'status'},
1061 $params->{'message_id'} );