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.
27 use C4::Members::Attributes qw(GetBorrowerAttributes);
33 use Date::Calc qw( Add_Delta_Days );
37 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
41 # set the version for version checking
42 $VERSION = 3.07.00.049;
45 &GetLetters &GetPreparedLetter &GetWrappedLetter &addalert &getalert &delalert &findrelatedto &SendAlerts &GetPrintMessages
51 C4::Letters - Give functions for Letters management
59 "Letters" is the tool used in Koha to manage informations sent to the patrons and/or the library. This include some cron jobs like
60 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)
62 Letters are managed through "alerts" sent by Koha on some events. All "alert" related functions are in this module too.
64 =head2 GetLetters([$category])
66 $letters = &GetLetters($category);
67 returns informations about letters.
68 if needed, $category filters for letters given category
69 Create a letter selector with the following code
73 my $letters = GetLetters($cat);
75 foreach my $thisletter (keys %$letters) {
76 my $selected = 1 if $thisletter eq $letter;
79 selected => $selected,
80 lettername => $letters->{$thisletter},
82 push @letterloop, \%row;
84 $template->param(LETTERLOOP => \@letterloop);
88 <select name="letter">
89 <option value="">Default</option>
90 <!-- TMPL_LOOP name="LETTERLOOP" -->
91 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="lettername" --></option>
99 # returns a reference to a hash of references to ALL letters...
102 my $dbh = C4::Context->dbh;
105 my $query = "SELECT * FROM letter WHERE module = ? ORDER BY name";
106 $sth = $dbh->prepare($query);
110 my $query = "SELECT * FROM letter ORDER BY name";
111 $sth = $dbh->prepare($query);
114 while ( my $letter = $sth->fetchrow_hashref ) {
115 $letters{ $letter->{'code'} } = $letter->{'name'};
120 # FIXME: using our here means that a Plack server will need to be
121 # restarted fairly regularly when working with this routine.
122 # A better option would be to use Koha::Cache and use a cache
123 # that actually works in a persistent environment, but as a
124 # short-term fix, our will work.
127 my ( $module, $code, $branchcode ) = @_;
131 if ( C4::Context->preference('IndependentBranches')
133 and C4::Context->userenv ) {
135 $branchcode = C4::Context->userenv->{'branch'};
138 if ( my $l = $letter{$module}{$code}{$branchcode} ) {
139 return { %$l }; # deep copy
142 my $dbh = C4::Context->dbh;
143 my $sth = $dbh->prepare("select * from letter where module=? and code=? and (branchcode = ? or branchcode = '') order by branchcode desc limit 1");
144 $sth->execute( $module, $code, $branchcode );
145 my $line = $sth->fetchrow_hashref
147 $line->{'content-type'} = 'text/html; charset="UTF-8"' if $line->{is_html};
148 $letter{$module}{$code}{$branchcode} = $line;
152 =head2 addalert ($borrowernumber, $type, $externalid)
155 - $borrowernumber : the number of the borrower subscribing to the alert
156 - $type : the type of alert.
157 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
159 create an alert and return the alertid (primary key)
164 my ( $borrowernumber, $type, $externalid ) = @_;
165 my $dbh = C4::Context->dbh;
168 "insert into alert (borrowernumber, type, externalid) values (?,?,?)");
169 $sth->execute( $borrowernumber, $type, $externalid );
171 # get the alert number newly created and return it
172 my $alertid = $dbh->{'mysql_insertid'};
176 =head2 delalert ($alertid)
179 - alertid : the alert id
185 my $alertid = shift or die "delalert() called without valid argument (alertid)"; # it's gonna die anyway.
186 $debug and warn "delalert: deleting alertid $alertid";
187 my $sth = C4::Context->dbh->prepare("delete from alert where alertid=?");
188 $sth->execute($alertid);
191 =head2 getalert ([$borrowernumber], [$type], [$externalid])
194 - $borrowernumber : the number of the borrower subscribing to the alert
195 - $type : the type of alert.
196 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
197 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.
202 my ( $borrowernumber, $type, $externalid ) = @_;
203 my $dbh = C4::Context->dbh;
204 my $query = "SELECT a.*, b.branchcode FROM alert a JOIN borrowers b USING(borrowernumber) WHERE";
206 if ($borrowernumber and $borrowernumber =~ /^\d+$/) {
207 $query .= " borrowernumber=? AND ";
208 push @bind, $borrowernumber;
211 $query .= " type=? AND ";
215 $query .= " externalid=? AND ";
216 push @bind, $externalid;
218 $query =~ s/ AND $//;
219 my $sth = $dbh->prepare($query);
220 $sth->execute(@bind);
221 return $sth->fetchall_arrayref({});
224 =head2 findrelatedto($type, $externalid)
227 - $type : the type of alert
228 - $externalid : the id of the "object" to query
230 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.
231 When type=issue, the id is related to a subscriptionid and this sub returns the name of the biblio.
236 # When type=virtual, the id is related to a virtual shelf and this sub returns the name of the sub
239 my $type = shift or return;
240 my $externalid = shift or return;
241 my $q = ($type eq 'issue' ) ?
242 "select title as result from subscription left join biblio on subscription.biblionumber=biblio.biblionumber where subscriptionid=?" :
243 ($type eq 'borrower') ?
244 "select concat(firstname,' ',surname) from borrowers where borrowernumber=?" : undef;
246 warn "findrelatedto(): Illegal type '$type'";
249 my $sth = C4::Context->dbh->prepare($q);
250 $sth->execute($externalid);
251 my ($result) = $sth->fetchrow;
258 - $type : the type of alert
259 - $externalid : the id of the "object" to query
260 - $letter_code : the letter to send.
262 send an alert to all borrowers having put an alert on a given subject.
267 my ( $type, $externalid, $letter_code ) = @_;
268 my $dbh = C4::Context->dbh;
269 if ( $type eq 'issue' ) {
271 # prepare the letter...
272 # search the biblionumber
275 "SELECT biblionumber FROM subscription WHERE subscriptionid=?");
276 $sth->execute($externalid);
277 my ($biblionumber) = $sth->fetchrow
278 or warn( "No subscription for '$externalid'" ),
282 # find the list of borrowers to alert
283 my $alerts = getalert( '', 'issue', $externalid );
286 my $borinfo = C4::Members::GetMember('borrowernumber' => $_->{'borrowernumber'});
287 my $email = $borinfo->{email} or next;
289 # warn "sending issues...";
290 my $userenv = C4::Context->userenv;
291 my $letter = GetPreparedLetter (
293 letter_code => $letter_code,
294 branchcode => $userenv->{branch},
296 'branches' => $_->{branchcode},
297 'biblio' => $biblionumber,
298 'biblioitems' => $biblionumber,
299 'borrowers' => $borinfo,
308 Subject => Encode::encode( "utf8", "" . $letter->{title} ),
309 Message => Encode::encode( "utf8", "" . $letter->{content} ),
310 'Content-Type' => 'text/plain; charset="utf8"',
312 sendmail(%mail) or carp $Mail::Sendmail::error;
315 elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' ) {
317 # prepare the letter...
318 # search the biblionumber
319 my $strsth = $type eq 'claimacquisition'
321 SELECT aqorders.*,aqbasket.*,biblio.*,biblioitems.*,aqbooksellers.*,
322 aqbooksellers.id AS booksellerid
324 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
325 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
326 LEFT JOIN biblioitems ON aqorders.biblioitemnumber=biblioitems.biblioitemnumber
327 LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
328 WHERE aqorders.ordernumber IN (
331 SELECT serial.*,subscription.*, biblio.*, aqbooksellers.*,
332 aqbooksellers.id AS booksellerid
334 LEFT JOIN subscription ON serial.subscriptionid=subscription.subscriptionid
335 LEFT JOIN biblio ON serial.biblionumber=biblio.biblionumber
336 LEFT JOIN aqbooksellers ON subscription.aqbooksellerid=aqbooksellers.id
337 WHERE serial.serialid IN (
339 $strsth .= join( ",", @$externalid ) . ")";
340 my $sthorders = $dbh->prepare($strsth);
342 my $dataorders = $sthorders->fetchall_arrayref( {} );
345 $dbh->prepare("select * from aqbooksellers where id=?");
346 $sthbookseller->execute( $dataorders->[0]->{booksellerid} );
347 my $databookseller = $sthbookseller->fetchrow_hashref;
350 push @email, $databookseller->{bookselleremail} if $databookseller->{bookselleremail};
351 push @email, $databookseller->{contemail} if $databookseller->{contemail};
353 warn "Bookseller $dataorders->[0]->{booksellerid} without emails";
354 return { error => "no_email" };
357 my $userenv = C4::Context->userenv;
358 my $letter = GetPreparedLetter (
360 letter_code => $letter_code,
361 branchcode => $userenv->{branch},
363 'branches' => $userenv->{branch},
364 'aqbooksellers' => $databookseller,
366 repeat => $dataorders,
372 To => join( ',', @email),
373 From => $userenv->{emailaddress},
374 Subject => Encode::encode( "utf8", "" . $letter->{title} ),
375 Message => Encode::encode( "utf8", "" . $letter->{content} ),
376 'Content-Type' => 'text/plain; charset="utf8"',
378 sendmail(%mail) or carp $Mail::Sendmail::error;
382 $type eq 'claimissues' ? "CLAIM ISSUE" : "ACQUISITION CLAIM",
385 . $databookseller->{contemail}
390 ) if C4::Context->preference("LetterLog");
392 # send an "account details" notice to a newly created user
393 elsif ( $type eq 'members' ) {
394 my $branchdetails = GetBranchDetail($externalid->{'branchcode'});
395 my $letter = GetPreparedLetter (
397 letter_code => $letter_code,
398 branchcode => $externalid->{'branchcode'},
400 'branches' => $branchdetails,
401 'borrowers' => $externalid->{'borrowernumber'},
403 substitute => { 'borrowers.password' => $externalid->{'password'} },
407 return { error => "no_email" } unless $externalid->{'emailaddr'};
409 To => $externalid->{'emailaddr'},
410 From => $branchdetails->{'branchemail'} || C4::Context->preference("KohaAdminEmailAddress"),
411 Subject => Encode::encode( "utf8", $letter->{'title'} ),
412 Message => Encode::encode( "utf8", $letter->{'content'} ),
413 'Content-Type' => 'text/plain; charset="utf8"',
415 sendmail(%mail) or carp $Mail::Sendmail::error;
419 =head2 GetPreparedLetter( %params )
422 module => letter module, mandatory
423 letter_code => letter code, mandatory
424 branchcode => for letter selection, if missing default system letter taken
425 tables => a hashref with table names as keys. Values are either:
426 - a scalar - primary key value
427 - an arrayref - primary key values
428 - a hashref - full record
429 substitute => custom substitution key/value pairs
430 repeat => records to be substituted on consecutive lines:
431 - an arrayref - tries to guess what needs substituting by
432 taking remaining << >> tokensr; not recommended
433 - a hashref token => @tables - replaces <token> << >> << >> </token>
434 subtemplate for each @tables row; table is a hashref as above
435 want_librarian => boolean, if set to true triggers librarian details
436 substitution from the userenv
438 letter fields hashref (title & content useful)
442 sub GetPreparedLetter {
445 my $module = $params{module} or croak "No module";
446 my $letter_code = $params{letter_code} or croak "No letter_code";
447 my $branchcode = $params{branchcode} || '';
449 my $letter = getletter( $module, $letter_code, $branchcode )
450 or warn( "No $module $letter_code letter"),
453 my $tables = $params{tables};
454 my $substitute = $params{substitute};
455 my $repeat = $params{repeat};
456 $tables || $substitute || $repeat
457 or carp( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
459 my $want_librarian = $params{want_librarian};
462 while ( my ($token, $val) = each %$substitute ) {
463 $letter->{title} =~ s/<<$token>>/$val/g;
464 $letter->{content} =~ s/<<$token>>/$val/g;
468 my $OPACBaseURL = C4::Context->preference('OPACBaseURL');
469 $letter->{content} =~ s/<<OPACBaseURL>>/$OPACBaseURL/go;
471 if ($want_librarian) {
472 # parsing librarian name
473 my $userenv = C4::Context->userenv;
474 $letter->{content} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
475 $letter->{content} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
476 $letter->{content} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
479 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
482 if (ref ($repeat) eq 'ARRAY' ) {
483 $repeat_no_enclosing_tags = $repeat;
485 $repeat_enclosing_tags = $repeat;
489 if ($repeat_enclosing_tags) {
490 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
491 if ( $letter->{content} =~ m!<$tag>(.*)</$tag>!s ) {
494 my %subletter = ( title => '', content => $subcontent );
495 _substitute_tables( \%subletter, $_ );
498 $letter->{content} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
504 _substitute_tables( $letter, $tables );
507 if ($repeat_no_enclosing_tags) {
508 if ( $letter->{content} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
513 $c =~ s/<<count>>/$i/go;
514 foreach my $field ( keys %{$_} ) {
515 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
519 } @$repeat_no_enclosing_tags;
521 my $replaceby = join( "\n", @lines );
522 $letter->{content} =~ s/\Q$line\E/$replaceby/s;
526 $letter->{content} =~ s/<<\S*>>//go; #remove any stragglers
527 # $letter->{content} =~ s/<<[^>]*>>//go;
532 sub _substitute_tables {
533 my ( $letter, $tables ) = @_;
534 while ( my ($table, $param) = each %$tables ) {
537 my $ref = ref $param;
540 if ($ref && $ref eq 'HASH') {
545 my $sth = _parseletter_sth($table);
547 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
550 $sth->execute( $ref ? @$param : $param );
552 $values = $sth->fetchrow_hashref;
555 _parseletter ( $letter, $table, $values );
559 sub _parseletter_sth {
563 carp "ERROR: _parseletter_sth() called without argument (table)";
566 # NOTE: we used to check whether we had a statement handle cached in
567 # a %handles module-level variable. This was a dumb move and
568 # broke things for the rest of us. prepare_cached is a better
569 # way to cache statement handles anyway.
571 ($table eq 'biblio' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
572 ($table eq 'biblioitems' ) ? "SELECT * FROM $table WHERE biblionumber = ?" :
573 ($table eq 'items' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
574 ($table eq 'issues' ) ? "SELECT * FROM $table WHERE itemnumber = ?" :
575 ($table eq 'old_issues' ) ? "SELECT * FROM $table WHERE itemnumber = ? ORDER BY timestamp DESC LIMIT 1" :
576 ($table eq 'reserves' ) ? "SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
577 ($table eq 'borrowers' ) ? "SELECT * FROM $table WHERE borrowernumber = ?" :
578 ($table eq 'branches' ) ? "SELECT * FROM $table WHERE branchcode = ?" :
579 ($table eq 'suggestions' ) ? "SELECT * FROM $table WHERE suggestionid = ?" :
580 ($table eq 'aqbooksellers') ? "SELECT * FROM $table WHERE id = ?" :
581 ($table eq 'aqorders' ) ? "SELECT * FROM $table WHERE ordernumber = ?" :
582 ($table eq 'opac_news' ) ? "SELECT * FROM $table WHERE idnew = ?" :
583 ($table eq 'borrower_modifications') ? "SELECT * FROM $table WHERE borrowernumber = ? OR verification_token =?":
586 warn "ERROR: No _parseletter_sth query for table '$table'";
587 return; # nothing to get
589 unless ($sth = C4::Context->dbh->prepare_cached($query)) {
590 warn "ERROR: Failed to prepare query: '$query'";
593 return $sth; # now cache is populated for that $table
596 =head2 _parseletter($letter, $table, $values)
599 - $letter : a hash to letter fields (title & content useful)
600 - $table : the Koha table to parse.
601 - $values : table record hashref
602 parse all fields from a table, and replace values in title & content with the appropriate value
603 (not exported sub, used only internally)
608 my ( $letter, $table, $values ) = @_;
610 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
611 my @waitingdate = split /-/, $values->{'waitingdate'};
613 my $dt = dt_from_string();
614 $dt->add( days => C4::Context->preference('ReservesMaxPickUpDelay') );
615 $values->{'expirationdate'} = output_pref( $dt, undef, 1 );
617 $values->{'waitingdate'} = output_pref( dt_from_string( $values->{'waitingdate'} ), undef, 1 );
621 if ($letter->{content} && $letter->{content} =~ /<<today>>/) {
622 my $todaysdate = output_pref( DateTime->now() );
623 $letter->{content} =~ s/<<today>>/$todaysdate/go;
626 while ( my ($field, $val) = each %$values ) {
627 my $replacetablefield = "<<$table.$field>>";
628 my $replacefield = "<<$field>>";
629 $val =~ s/\p{P}$// if $val && $table=~/biblio/;
630 #BZ 9886: Assuming that we want to eliminate ISBD punctuation here
631 #Therefore adding the test on biblio. This includes biblioitems,
632 #but excludes items. Removed unneeded global and lookahead.
634 my $replacedby = defined ($val) ? $val : '';
635 ($letter->{title} ) and do {
636 $letter->{title} =~ s/$replacetablefield/$replacedby/g;
637 $letter->{title} =~ s/$replacefield/$replacedby/g;
639 ($letter->{content}) and do {
640 $letter->{content} =~ s/$replacetablefield/$replacedby/g;
641 $letter->{content} =~ s/$replacefield/$replacedby/g;
645 if ($table eq 'borrowers' && $letter->{content}) {
646 if ( my $attributes = GetBorrowerAttributes($values->{borrowernumber}) ) {
648 foreach (@$attributes) {
649 my $code = $_->{code};
650 my $val = $_->{value_description} || $_->{value};
651 $val =~ s/\p{P}(?=$)//g if $val;
652 next unless $val gt '';
654 push @{ $attr{$code} }, $val;
656 while ( my ($code, $val_ar) = each %attr ) {
657 my $replacefield = "<<borrower-attribute:$code>>";
658 my $replacedby = join ',', @$val_ar;
659 $letter->{content} =~ s/$replacefield/$replacedby/g;
668 my $success = EnqueueLetter( { letter => $letter,
669 borrowernumber => '12', message_transport_type => 'email' } )
671 places a letter in the message_queue database table, which will
672 eventually get processed (sent) by the process_message_queue.pl
673 cronjob when it calls SendQueuedMessages.
675 return message_id on success
680 my $params = shift or return;
682 return unless exists $params->{'letter'};
683 # return unless exists $params->{'borrowernumber'};
684 return unless exists $params->{'message_transport_type'};
686 my $content = $params->{letter}->{content};
687 $content =~ s/\s+//g if(defined $content);
688 if ( not defined $content or $content eq '' ) {
689 warn "Trying to add an empty message to the message queue" if $debug;
693 # If we have any attachments we should encode then into the body.
694 if ( $params->{'attachments'} ) {
695 $params->{'letter'} = _add_attachments(
696 { letter => $params->{'letter'},
697 attachments => $params->{'attachments'},
698 message => MIME::Lite->new( Type => 'multipart/mixed' ),
703 my $dbh = C4::Context->dbh();
704 my $statement = << 'ENDSQL';
705 INSERT INTO message_queue
706 ( borrowernumber, subject, content, metadata, letter_code, message_transport_type, status, time_queued, to_address, from_address, content_type )
708 ( ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ? )
711 my $sth = $dbh->prepare($statement);
712 my $result = $sth->execute(
713 $params->{'borrowernumber'}, # borrowernumber
714 $params->{'letter'}->{'title'}, # subject
715 $params->{'letter'}->{'content'}, # content
716 $params->{'letter'}->{'metadata'} || '', # metadata
717 $params->{'letter'}->{'code'} || '', # letter_code
718 $params->{'message_transport_type'}, # message_transport_type
720 $params->{'to_address'}, # to_address
721 $params->{'from_address'}, # from_address
722 $params->{'letter'}->{'content-type'}, # content_type
724 return $dbh->last_insert_id(undef,undef,'message_queue', undef);
727 =head2 SendQueuedMessages ([$hashref])
729 my $sent = SendQueuedMessages( { verbose => 1 } );
731 sends all of the 'pending' items in the message queue.
733 returns number of messages sent.
737 sub SendQueuedMessages {
740 my $unsent_messages = _get_unsent_messages();
741 MESSAGE: foreach my $message ( @$unsent_messages ) {
742 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
743 warn sprintf( 'sending %s message to patron: %s',
744 $message->{'message_transport_type'},
745 $message->{'borrowernumber'} || 'Admin' )
746 if $params->{'verbose'} or $debug;
747 # This is just begging for subclassing
748 next MESSAGE if ( lc($message->{'message_transport_type'}) eq 'rss' );
749 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
750 _send_message_by_email( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
752 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
753 _send_message_by_sms( $message );
756 return scalar( @$unsent_messages );
759 =head2 GetRSSMessages
761 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
763 returns a listref of all queued RSS messages for a particular person.
770 return unless $params;
771 return unless ref $params;
772 return unless $params->{'borrowernumber'};
774 return _get_unsent_messages( { message_transport_type => 'rss',
775 limit => $params->{'limit'},
776 borrowernumber => $params->{'borrowernumber'}, } );
779 =head2 GetPrintMessages
781 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
783 Returns a arrayref of all queued print messages (optionally, for a particular
788 sub GetPrintMessages {
789 my $params = shift || {};
791 return _get_unsent_messages( { message_transport_type => 'print',
792 borrowernumber => $params->{'borrowernumber'},
796 =head2 GetQueuedMessages ([$hashref])
798 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
800 fetches messages out of the message queue.
803 list of hashes, each has represents a message in the message queue.
807 sub GetQueuedMessages {
810 my $dbh = C4::Context->dbh();
811 my $statement = << 'ENDSQL';
812 SELECT message_id, borrowernumber, subject, content, message_transport_type, status, time_queued
818 if ( exists $params->{'borrowernumber'} ) {
819 push @whereclauses, ' borrowernumber = ? ';
820 push @query_params, $params->{'borrowernumber'};
823 if ( @whereclauses ) {
824 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
827 if ( defined $params->{'limit'} ) {
828 $statement .= ' LIMIT ? ';
829 push @query_params, $params->{'limit'};
832 my $sth = $dbh->prepare( $statement );
833 my $result = $sth->execute( @query_params );
834 return $sth->fetchall_arrayref({});
837 =head2 _add_attachements
840 letter - the standard letter hashref
841 attachments - listref of attachments. each attachment is a hashref of:
842 type - the mime type, like 'text/plain'
843 content - the actual attachment
844 filename - the name of the attachment.
845 message - a MIME::Lite object to attach these to.
847 returns your letter object, with the content updated.
851 sub _add_attachments {
854 my $letter = $params->{'letter'};
855 my $attachments = $params->{'attachments'};
856 return $letter unless @$attachments;
857 my $message = $params->{'message'};
859 # First, we have to put the body in as the first attachment
861 Type => $letter->{'content-type'} || 'TEXT',
862 Data => $letter->{'is_html'}
863 ? _wrap_html($letter->{'content'}, $letter->{'title'})
864 : $letter->{'content'},
867 foreach my $attachment ( @$attachments ) {
869 Type => $attachment->{'type'},
870 Data => $attachment->{'content'},
871 Filename => $attachment->{'filename'},
874 # we're forcing list context here to get the header, not the count back from grep.
875 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
876 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
877 $letter->{'content'} = $message->body_as_string;
883 sub _get_unsent_messages {
886 my $dbh = C4::Context->dbh();
887 my $statement = << 'ENDSQL';
888 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
889 FROM message_queue mq
890 LEFT JOIN borrowers b ON b.borrowernumber = mq.borrowernumber
894 my @query_params = ('pending');
896 if ( $params->{'message_transport_type'} ) {
897 $statement .= ' AND message_transport_type = ? ';
898 push @query_params, $params->{'message_transport_type'};
900 if ( $params->{'borrowernumber'} ) {
901 $statement .= ' AND borrowernumber = ? ';
902 push @query_params, $params->{'borrowernumber'};
904 if ( $params->{'limit'} ) {
905 $statement .= ' limit ? ';
906 push @query_params, $params->{'limit'};
910 $debug and warn "_get_unsent_messages SQL: $statement";
911 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
912 my $sth = $dbh->prepare( $statement );
913 my $result = $sth->execute( @query_params );
914 return $sth->fetchall_arrayref({});
917 sub _send_message_by_email {
918 my $message = shift or return;
919 my ($username, $password, $method) = @_;
921 my $to_address = $message->{to_address};
922 unless ($to_address) {
923 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
925 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
926 _set_message_status( { message_id => $message->{'message_id'},
927 status => 'failed' } );
930 $to_address = C4::Members::GetNoticeEmailAddress( $message->{'borrowernumber'} );
931 unless ($to_address) {
932 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
933 # warning too verbose for this more common case?
934 _set_message_status( { message_id => $message->{'message_id'},
935 status => 'failed' } );
940 my $utf8 = decode('MIME-Header', $message->{'subject'} );
941 $message->{subject}= encode('MIME-Header', $utf8);
942 my $subject = encode('utf8', $message->{'subject'});
943 my $content = encode('utf8', $message->{'content'});
944 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
945 my $is_html = $content_type =~ m/html/io;
946 my %sendmail_params = (
948 From => $message->{'from_address'} || C4::Context->preference('KohaAdminEmailAddress'),
951 Message => $is_html ? _wrap_html($content, $subject) : $content,
952 'content-type' => $content_type,
954 $sendmail_params{'Auth'} = {user => $username, pass => $password, method => $method} if $username;
955 if ( my $bcc = C4::Context->preference('OverdueNoticeBcc') ) {
956 $sendmail_params{ Bcc } = $bcc;
959 _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
960 if ( sendmail( %sendmail_params ) ) {
961 _set_message_status( { message_id => $message->{'message_id'},
962 status => 'sent' } );
965 _set_message_status( { message_id => $message->{'message_id'},
966 status => 'failed' } );
967 carp $Mail::Sendmail::error;
973 my ($content, $title) = @_;
975 my $css = C4::Context->preference("NoticeCSS") || '';
976 $css = qq{<link rel="stylesheet" type="text/css" href="$css">} if $css;
978 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
979 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
980 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
982 <title>$title</title>
983 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
993 sub _send_message_by_sms {
994 my $message = shift or return;
995 my $member = C4::Members::GetMember( 'borrowernumber' => $message->{'borrowernumber'} );
996 return unless $member->{'smsalertnumber'};
998 my $success = C4::SMS->send_sms( { destination => $member->{'smsalertnumber'},
999 message => $message->{'content'},
1001 _set_message_status( { message_id => $message->{'message_id'},
1002 status => ($success ? 'sent' : 'failed') } );
1006 sub _update_message_to_address {
1008 my $dbh = C4::Context->dbh();
1009 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
1012 sub _set_message_status {
1013 my $params = shift or return;
1015 foreach my $required_parameter ( qw( message_id status ) ) {
1016 return unless exists $params->{ $required_parameter };
1019 my $dbh = C4::Context->dbh();
1020 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1021 my $sth = $dbh->prepare( $statement );
1022 my $result = $sth->execute( $params->{'status'},
1023 $params->{'message_id'} );