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);
32 use Date
::Calc
qw( Add_Delta_Days );
36 use vars
qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
40 # set the version for version checking
44 &GetLetters &GetPreparedLetter &GetWrappedLetter &addalert &getalert &delalert &findrelatedto &SendAlerts &GetPrintMessages
50 C4::Letters - Give functions for Letters management
58 "Letters" is the tool used in Koha to manage informations sent to the patrons and/or the library. This include some cron jobs like
59 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)
61 Letters are managed through "alerts" sent by Koha on some events. All "alert" related functions are in this module too.
63 =head2 GetLetters([$category])
65 $letters = &GetLetters($category);
66 returns informations about letters.
67 if needed, $category filters for letters given category
68 Create a letter selector with the following code
72 my $letters = GetLetters($cat);
74 foreach my $thisletter (keys %$letters) {
75 my $selected = 1 if $thisletter eq $letter;
78 selected => $selected,
79 lettername => $letters->{$thisletter},
81 push @letterloop, \%row;
83 $template->param(LETTERLOOP => \@letterloop);
87 <select name="letter">
88 <option value="">Default</option>
89 <!-- TMPL_LOOP name="LETTERLOOP" -->
90 <option value="<!-- TMPL_VAR name="value" -->" <!-- TMPL_IF name="selected" -->selected<!-- /TMPL_IF -->><!-- TMPL_VAR name="lettername" --></option>
98 # returns a reference to a hash of references to ALL letters...
101 my $dbh = C4
::Context
->dbh;
104 my $query = "SELECT * FROM letter WHERE module = ? ORDER BY name";
105 $sth = $dbh->prepare($query);
109 my $query = "SELECT * FROM letter ORDER BY name";
110 $sth = $dbh->prepare($query);
113 while ( my $letter = $sth->fetchrow_hashref ) {
114 $letters{ $letter->{'code'} } = $letter->{'name'};
120 sub getletter
($$$) {
121 my ( $module, $code, $branchcode ) = @_;
123 if (C4
::Context
->preference('IndependantBranches') && $branchcode){
124 $branchcode = C4
::Context
->userenv->{'branch'};
127 if ( my $l = $letter{$module}{$code}{$branchcode} ) {
128 return { %$l }; # deep copy
131 my $dbh = C4
::Context
->dbh;
132 my $sth = $dbh->prepare("select * from letter where module=? and code=? and (branchcode = ? or branchcode = '') order by branchcode desc limit 1");
133 $sth->execute( $module, $code, $branchcode );
134 my $line = $sth->fetchrow_hashref
136 $line->{'content-type'} = 'text/html; charset="UTF-8"' if $line->{is_html
};
137 $letter{$module}{$code}{$branchcode} = $line;
141 =head2 addalert ($borrowernumber, $type, $externalid)
144 - $borrowernumber : the number of the borrower subscribing to the alert
145 - $type : the type of alert.
146 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
148 create an alert and return the alertid (primary key)
153 my ( $borrowernumber, $type, $externalid ) = @_;
154 my $dbh = C4
::Context
->dbh;
157 "insert into alert (borrowernumber, type, externalid) values (?,?,?)");
158 $sth->execute( $borrowernumber, $type, $externalid );
160 # get the alert number newly created and return it
161 my $alertid = $dbh->{'mysql_insertid'};
165 =head2 delalert ($alertid)
168 - alertid : the alert id
174 my $alertid = shift or die "delalert() called without valid argument (alertid)"; # it's gonna die anyway.
175 $debug and warn "delalert: deleting alertid $alertid";
176 my $sth = C4
::Context
->dbh->prepare("delete from alert where alertid=?");
177 $sth->execute($alertid);
180 =head2 getalert ([$borrowernumber], [$type], [$externalid])
183 - $borrowernumber : the number of the borrower subscribing to the alert
184 - $type : the type of alert.
185 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
186 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.
190 sub getalert
(;$$$) {
191 my ( $borrowernumber, $type, $externalid ) = @_;
192 my $dbh = C4
::Context
->dbh;
193 my $query = "SELECT a.*, b.branchcode FROM alert a JOIN borrowers b USING(borrowernumber) WHERE";
195 if ($borrowernumber and $borrowernumber =~ /^\d+$/) {
196 $query .= " borrowernumber=? AND ";
197 push @bind, $borrowernumber;
200 $query .= " type=? AND ";
204 $query .= " externalid=? AND ";
205 push @bind, $externalid;
207 $query =~ s/ AND $//;
208 my $sth = $dbh->prepare($query);
209 $sth->execute(@bind);
210 return $sth->fetchall_arrayref({});
213 =head2 findrelatedto($type, $externalid)
216 - $type : the type of alert
217 - $externalid : the id of the "object" to query
219 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.
220 When type=issue, the id is related to a subscriptionid and this sub returns the name of the biblio.
225 # When type=virtual, the id is related to a virtual shelf and this sub returns the name of the sub
227 sub findrelatedto
($$) {
228 my $type = shift or return undef;
229 my $externalid = shift or return undef;
230 my $q = ($type eq 'issue' ) ?
231 "select title as result from subscription left join biblio on subscription.biblionumber=biblio.biblionumber where subscriptionid=?" :
232 ($type eq 'borrower') ?
233 "select concat(firstname,' ',surname) from borrowers where borrowernumber=?" : undef;
235 warn "findrelatedto(): Illegal type '$type'";
238 my $sth = C4
::Context
->dbh->prepare($q);
239 $sth->execute($externalid);
240 my ($result) = $sth->fetchrow;
247 - $type : the type of alert
248 - $externalid : the id of the "object" to query
249 - $letter_code : the letter to send.
251 send an alert to all borrowers having put an alert on a given subject.
256 my ( $type, $externalid, $letter_code ) = @_;
257 my $dbh = C4
::Context
->dbh;
258 if ( $type eq 'issue' ) {
260 # prepare the letter...
261 # search the biblionumber
264 "SELECT biblionumber FROM subscription WHERE subscriptionid=?");
265 $sth->execute($externalid);
266 my ($biblionumber) = $sth->fetchrow
267 or warn( "No subscription for '$externalid'" ),
271 # find the list of borrowers to alert
272 my $alerts = getalert
( '', 'issue', $externalid );
275 my $borinfo = C4
::Members
::GetMember
('borrowernumber' => $_->{'borrowernumber'});
276 my $email = $borinfo->{email
} or next;
278 # warn "sending issues...";
279 my $userenv = C4
::Context
->userenv;
280 my $letter = GetPreparedLetter
(
282 letter_code
=> $letter_code,
283 branchcode
=> $userenv->{branch
},
285 'branches' => $_->{branchcode
},
286 'biblio' => $biblionumber,
287 'biblioitems' => $biblionumber,
288 'borrowers' => $borinfo,
297 Subject
=> Encode
::encode
( "utf8", "" . $letter->{title
} ),
298 Message
=> Encode
::encode
( "utf8", "" . $letter->{content
} ),
299 'Content-Type' => 'text/plain; charset="utf8"',
301 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
304 elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' ) {
306 # prepare the letter...
307 # search the biblionumber
308 my $strsth = $type eq 'claimacquisition'
310 SELECT aqorders
.*,aqbasket
.*,biblio
.*,biblioitems
.*,aqbooksellers
.*
312 LEFT JOIN aqbasket ON aqbasket
.basketno
=aqorders
.basketno
313 LEFT JOIN biblio ON aqorders
.biblionumber
=biblio
.biblionumber
314 LEFT JOIN biblioitems ON aqorders
.biblioitemnumber
=biblioitems
.biblioitemnumber
315 LEFT JOIN aqbooksellers ON aqbasket
.booksellerid
=aqbooksellers
.id
316 WHERE aqorders
.ordernumber IN
(
319 SELECT serial
.*,subscription
.*, biblio
.*, aqbooksellers
.*
321 LEFT JOIN subscription ON serial
.subscriptionid
=subscription
.subscriptionid
322 LEFT JOIN biblio ON serial
.biblionumber
=biblio
.biblionumber
323 LEFT JOIN aqbooksellers ON subscription
.aqbooksellerid
=aqbooksellers
.id
324 WHERE serial
.serialid IN
(
326 $strsth .= join( ",", @
$externalid ) . ")";
327 my $sthorders = $dbh->prepare($strsth);
329 my $dataorders = $sthorders->fetchall_arrayref( {} );
332 $dbh->prepare("select * from aqbooksellers where id=?");
333 $sthbookseller->execute( $dataorders->[0]->{booksellerid
} );
334 my $databookseller = $sthbookseller->fetchrow_hashref;
337 push @email, $databookseller->{bookselleremail
} if $databookseller->{bookselleremail
};
338 push @email, $databookseller->{contemail
} if $databookseller->{contemail
};
340 warn "Bookseller $dataorders->[0]->{booksellerid} without emails";
341 return { error
=> "no_email" };
344 my $userenv = C4
::Context
->userenv;
345 my $letter = GetPreparedLetter
(
347 letter_code
=> $letter_code,
348 branchcode
=> $userenv->{branch
},
350 'branches' => $userenv->{branch
},
351 'aqbooksellers' => $databookseller,
353 repeat
=> $dataorders,
359 To
=> join( ','. @email),
360 From
=> $userenv->{emailaddress
},
361 Subject
=> Encode
::encode
( "utf8", "" . $letter->{title
} ),
362 Message
=> Encode
::encode
( "utf8", "" . $letter->{content
} ),
363 'Content-Type' => 'text/plain; charset="utf8"',
365 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
369 $type eq 'claimissues' ?
"CLAIM ISSUE" : "ACQUISITION CLAIM",
372 . $databookseller->{contemail
}
377 ) if C4
::Context
->preference("LetterLog");
379 # send an "account details" notice to a newly created user
380 elsif ( $type eq 'members' ) {
381 my $branchdetails = GetBranchDetail
($externalid->{'branchcode'});
382 my $letter = GetPreparedLetter
(
384 letter_code
=> $letter_code,
385 branchcode
=> $externalid->{'branchcode'},
387 'branches' => $branchdetails,
388 'borrowers' => $externalid->{'borrowernumber'},
390 substitute
=> { 'borrowers.password' => $externalid->{'password'} },
394 return { error
=> "no_email" } unless $externalid->{'emailaddr'};
396 To
=> $externalid->{'emailaddr'},
397 From
=> $branchdetails->{'branchemail'} || C4
::Context
->preference("KohaAdminEmailAddress"),
398 Subject
=> Encode
::encode
( "utf8", $letter->{'title'} ),
399 Message
=> Encode
::encode
( "utf8", $letter->{'content'} ),
400 'Content-Type' => 'text/plain; charset="utf8"',
402 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
406 =head2 GetPreparedLetter( %params )
409 module => letter module, mandatory
410 letter_code => letter code, mandatory
411 branchcode => for letter selection, if missing default system letter taken
412 tables => a hashref with table names as keys. Values are either:
413 - a scalar - primary key value
414 - an arrayref - primary key values
415 - a hashref - full record
416 substitute => custom substitution key/value pairs
417 repeat => records to be substituted on consecutive lines:
418 - an arrayref - tries to guess what needs substituting by
419 taking remaining << >> tokensr; not recommended
420 - a hashref token => @tables - replaces <token> << >> << >> </token>
421 subtemplate for each @tables row; table is a hashref as above
422 want_librarian => boolean, if set to true triggers librarian details
423 substitution from the userenv
425 letter fields hashref (title & content useful)
429 sub GetPreparedLetter
{
432 my $module = $params{module
} or croak
"No module";
433 my $letter_code = $params{letter_code
} or croak
"No letter_code";
434 my $branchcode = $params{branchcode
} || '';
436 my $letter = getletter
( $module, $letter_code, $branchcode )
437 or warn( "No $module $letter_code letter"),
440 my $tables = $params{tables
};
441 my $substitute = $params{substitute
};
442 my $repeat = $params{repeat
};
443 $tables || $substitute || $repeat
444 or carp
( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
446 my $want_librarian = $params{want_librarian
};
449 while ( my ($token, $val) = each %$substitute ) {
450 $letter->{title
} =~ s/<<$token>>/$val/g;
451 $letter->{content
} =~ s/<<$token>>/$val/g;
455 if ($want_librarian) {
456 # parsing librarian name
457 my $userenv = C4
::Context
->userenv;
458 $letter->{content
} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
459 $letter->{content
} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
460 $letter->{content
} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
463 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
466 if (ref ($repeat) eq 'ARRAY' ) {
467 $repeat_no_enclosing_tags = $repeat;
469 $repeat_enclosing_tags = $repeat;
473 if ($repeat_enclosing_tags) {
474 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
475 if ( $letter->{content
} =~ m!<$tag>(.*)</$tag>!s ) {
478 my %subletter = ( title
=> '', content
=> $subcontent );
479 _substitute_tables
( \
%subletter, $_ );
482 $letter->{content
} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
488 _substitute_tables
( $letter, $tables );
491 if ($repeat_no_enclosing_tags) {
492 if ( $letter->{content
} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
497 $c =~ s/<<count>>/$i/go;
498 foreach my $field ( keys %{$_} ) {
499 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
503 } @
$repeat_no_enclosing_tags;
505 my $replaceby = join( "\n", @lines );
506 $letter->{content
} =~ s/\Q$line\E/$replaceby/s;
510 $letter->{content
} =~ s/<<\S*>>//go; #remove any stragglers
511 # $letter->{content} =~ s/<<[^>]*>>//go;
516 sub _substitute_tables
{
517 my ( $letter, $tables ) = @_;
518 while ( my ($table, $param) = each %$tables ) {
521 my $ref = ref $param;
524 if ($ref && $ref eq 'HASH') {
529 my $sth = _parseletter_sth
($table);
531 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
534 $sth->execute( $ref ? @
$param : $param );
536 $values = $sth->fetchrow_hashref;
539 _parseletter
( $letter, $table, $values );
544 sub _parseletter_sth
{
547 carp
"ERROR: _parseletter_sth() called without argument (table)";
551 (defined $handles{$table}) and return $handles{$table};
553 ($table eq 'biblio' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
554 ($table eq 'biblioitems' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
555 ($table eq 'items' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
556 ($table eq 'issues' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
557 ($table eq 'reserves' ) ?
"SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
558 ($table eq 'borrowers' ) ?
"SELECT * FROM $table WHERE borrowernumber = ?" :
559 ($table eq 'branches' ) ?
"SELECT * FROM $table WHERE branchcode = ?" :
560 ($table eq 'suggestions' ) ?
"SELECT * FROM $table WHERE suggestionid = ?" :
561 ($table eq 'aqbooksellers') ?
"SELECT * FROM $table WHERE id = ?" :
562 ($table eq 'aqorders' ) ?
"SELECT * FROM $table WHERE ordernumber = ?" :
563 ($table eq 'opac_news' ) ?
"SELECT * FROM $table WHERE idnew = ?" :
566 warn "ERROR: No _parseletter_sth query for table '$table'";
567 return; # nothing to get
569 unless ($handles{$table} = C4
::Context
->dbh->prepare($query)) {
570 warn "ERROR: Failed to prepare query: '$query'";
573 return $handles{$table}; # now cache is populated for that $table
576 =head2 _parseletter($letter, $table, $values)
579 - $letter : a hash to letter fields (title & content useful)
580 - $table : the Koha table to parse.
581 - $values : table record hashref
582 parse all fields from a table, and replace values in title & content with the appropriate value
583 (not exported sub, used only internally)
589 my ( $letter, $table, $values ) = @_;
591 # TEMPORARY hack until the expirationdate column is added to reserves
592 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
593 my @waitingdate = split /-/, $values->{'waitingdate'};
595 $values->{'expirationdate'} = C4
::Dates
->new(
598 Add_Delta_Days
( @waitingdate, C4
::Context
->preference( 'ReservesMaxPickUpDelay' ) )
604 if ($letter->{content
} && $letter->{content
} =~ /<<today>>/) {
605 my @da = localtime();
606 my $todaysdate = "$da[2]:$da[1] " . C4
::Dates
->today();
607 $letter->{content
} =~ s/<<today>>/$todaysdate/go;
610 # and get all fields from the table
611 # my $columns = $columns{$table};
612 # unless ($columns) {
613 # $columns = $columns{$table} = C4::Context->dbh->selectcol_arrayref("SHOW COLUMNS FROM $table");
615 # foreach my $field (@$columns) {
617 while ( my ($field, $val) = each %$values ) {
618 my $replacetablefield = "<<$table.$field>>";
619 my $replacefield = "<<$field>>";
620 $val =~ s/\p{P}(?=$)//g if $val;
621 my $replacedby = defined ($val) ?
$val : '';
622 ($letter->{title
} ) and do {
623 $letter->{title
} =~ s/$replacetablefield/$replacedby/g;
624 $letter->{title
} =~ s/$replacefield/$replacedby/g;
626 ($letter->{content
}) and do {
627 $letter->{content
} =~ s/$replacetablefield/$replacedby/g;
628 $letter->{content
} =~ s/$replacefield/$replacedby/g;
632 if ($table eq 'borrowers' && $letter->{content
}) {
633 if ( my $attributes = GetBorrowerAttributes
($values->{borrowernumber
}) ) {
635 foreach (@
$attributes) {
636 my $code = $_->{code
};
637 my $val = $_->{value_description
} || $_->{value
};
638 $val =~ s/\p{P}(?=$)//g if $val;
639 next unless $val gt '';
641 push @
{ $attr{$code} }, $val;
643 while ( my ($code, $val_ar) = each %attr ) {
644 my $replacefield = "<<borrower-attribute:$code>>";
645 my $replacedby = join ',', @
$val_ar;
646 $letter->{content
} =~ s/$replacefield/$replacedby/g;
655 my $success = EnqueueLetter( { letter => $letter,
656 borrowernumber => '12', message_transport_type => 'email' } )
658 places a letter in the message_queue database table, which will
659 eventually get processed (sent) by the process_message_queue.pl
660 cronjob when it calls SendQueuedMessages.
662 return true on success
666 sub EnqueueLetter
($) {
667 my $params = shift or return undef;
669 return unless exists $params->{'letter'};
670 return unless exists $params->{'borrowernumber'};
671 return unless exists $params->{'message_transport_type'};
673 # If we have any attachments we should encode then into the body.
674 if ( $params->{'attachments'} ) {
675 $params->{'letter'} = _add_attachments
(
676 { letter
=> $params->{'letter'},
677 attachments
=> $params->{'attachments'},
678 message
=> MIME
::Lite
->new( Type
=> 'multipart/mixed' ),
683 my $dbh = C4
::Context
->dbh();
684 my $statement = << 'ENDSQL';
685 INSERT INTO message_queue
686 ( borrowernumber
, subject
, content
, metadata
, letter_code
, message_transport_type
, status
, time_queued
, to_address
, from_address
, content_type
)
688 ( ?
, ?
, ?
, ?
, ?
, ?
, ?
, NOW
(), ?
, ?
, ?
)
691 my $sth = $dbh->prepare($statement);
692 my $result = $sth->execute(
693 $params->{'borrowernumber'}, # borrowernumber
694 $params->{'letter'}->{'title'}, # subject
695 $params->{'letter'}->{'content'}, # content
696 $params->{'letter'}->{'metadata'} || '', # metadata
697 $params->{'letter'}->{'code'} || '', # letter_code
698 $params->{'message_transport_type'}, # message_transport_type
700 $params->{'to_address'}, # to_address
701 $params->{'from_address'}, # from_address
702 $params->{'letter'}->{'content-type'}, # content_type
707 =head2 SendQueuedMessages ([$hashref])
709 my $sent = SendQueuedMessages( { verbose => 1 } );
711 sends all of the 'pending' items in the message queue.
713 returns number of messages sent.
717 sub SendQueuedMessages
(;$) {
720 my $unsent_messages = _get_unsent_messages
();
721 MESSAGE
: foreach my $message ( @
$unsent_messages ) {
722 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
723 warn sprintf( 'sending %s message to patron: %s',
724 $message->{'message_transport_type'},
725 $message->{'borrowernumber'} || 'Admin' )
726 if $params->{'verbose'} or $debug;
727 # This is just begging for subclassing
728 next MESSAGE
if ( lc($message->{'message_transport_type'}) eq 'rss' );
729 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
730 _send_message_by_email
( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
732 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
733 _send_message_by_sms
( $message );
736 return scalar( @
$unsent_messages );
739 =head2 GetRSSMessages
741 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
743 returns a listref of all queued RSS messages for a particular person.
750 return unless $params;
751 return unless ref $params;
752 return unless $params->{'borrowernumber'};
754 return _get_unsent_messages
( { message_transport_type
=> 'rss',
755 limit
=> $params->{'limit'},
756 borrowernumber
=> $params->{'borrowernumber'}, } );
759 =head2 GetPrintMessages
761 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
763 Returns a arrayref of all queued print messages (optionally, for a particular
768 sub GetPrintMessages
{
769 my $params = shift || {};
771 return _get_unsent_messages
( { message_transport_type
=> 'print',
772 borrowernumber
=> $params->{'borrowernumber'}, } );
775 =head2 GetQueuedMessages ([$hashref])
777 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
779 fetches messages out of the message queue.
782 list of hashes, each has represents a message in the message queue.
786 sub GetQueuedMessages
{
789 my $dbh = C4
::Context
->dbh();
790 my $statement = << 'ENDSQL';
791 SELECT message_id
, borrowernumber
, subject
, content
, message_transport_type
, status
, time_queued
797 if ( exists $params->{'borrowernumber'} ) {
798 push @whereclauses, ' borrowernumber = ? ';
799 push @query_params, $params->{'borrowernumber'};
802 if ( @whereclauses ) {
803 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
806 if ( defined $params->{'limit'} ) {
807 $statement .= ' LIMIT ? ';
808 push @query_params, $params->{'limit'};
811 my $sth = $dbh->prepare( $statement );
812 my $result = $sth->execute( @query_params );
813 return $sth->fetchall_arrayref({});
816 =head2 _add_attachements
819 letter - the standard letter hashref
820 attachments - listref of attachments. each attachment is a hashref of:
821 type - the mime type, like 'text/plain'
822 content - the actual attachment
823 filename - the name of the attachment.
824 message - a MIME::Lite object to attach these to.
826 returns your letter object, with the content updated.
830 sub _add_attachments
{
833 my $letter = $params->{'letter'};
834 my $attachments = $params->{'attachments'};
835 return $letter unless @
$attachments;
836 my $message = $params->{'message'};
838 # First, we have to put the body in as the first attachment
840 Type
=> $letter->{'content-type'} || 'TEXT',
841 Data
=> $letter->{'is_html'}
842 ? _wrap_html
($letter->{'content'}, $letter->{'title'})
843 : $letter->{'content'},
846 foreach my $attachment ( @
$attachments ) {
848 Type
=> $attachment->{'type'},
849 Data
=> $attachment->{'content'},
850 Filename
=> $attachment->{'filename'},
853 # we're forcing list context here to get the header, not the count back from grep.
854 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
855 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
856 $letter->{'content'} = $message->body_as_string;
862 sub _get_unsent_messages
(;$) {
865 my $dbh = C4
::Context
->dbh();
866 my $statement = << 'ENDSQL';
867 SELECT message_id
, borrowernumber
, subject
, content
, message_transport_type
, status
, time_queued
, from_address
, to_address
, content_type
872 my @query_params = ('pending');
874 if ( $params->{'message_transport_type'} ) {
875 $statement .= ' AND message_transport_type = ? ';
876 push @query_params, $params->{'message_transport_type'};
878 if ( $params->{'borrowernumber'} ) {
879 $statement .= ' AND borrowernumber = ? ';
880 push @query_params, $params->{'borrowernumber'};
882 if ( $params->{'limit'} ) {
883 $statement .= ' limit ? ';
884 push @query_params, $params->{'limit'};
887 $debug and warn "_get_unsent_messages SQL: $statement";
888 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
889 my $sth = $dbh->prepare( $statement );
890 my $result = $sth->execute( @query_params );
891 return $sth->fetchall_arrayref({});
894 sub _send_message_by_email
($;$$$) {
895 my $message = shift or return;
896 my ($username, $password, $method) = @_;
898 my $to_address = $message->{to_address
};
899 unless ($to_address) {
900 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
902 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
903 _set_message_status
( { message_id
=> $message->{'message_id'},
904 status
=> 'failed' } );
907 my $which_address = C4
::Context
->preference('AutoEmailPrimaryAddress');
908 # If the system preference is set to 'first valid' (value == OFF), look up email address
909 if ($which_address eq 'OFF') {
910 $to_address = GetFirstValidEmailAddress
( $message->{'borrowernumber'} );
912 $to_address = $member->{$which_address};
914 unless ($to_address) {
915 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
916 # warning too verbose for this more common case?
917 _set_message_status
( { message_id
=> $message->{'message_id'},
918 status
=> 'failed' } );
923 my $utf8 = decode
('MIME-Header', $message->{'subject'} );
924 $message->{subject
}= encode
('MIME-Header', $utf8);
925 my $subject = encode
('utf8', $message->{'subject'});
926 my $content = encode
('utf8', $message->{'content'});
927 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
928 my $is_html = $content_type =~ m/html/io;
929 my %sendmail_params = (
931 From
=> $message->{'from_address'} || C4
::Context
->preference('KohaAdminEmailAddress'),
934 Message
=> $is_html ? _wrap_html
($content, $subject) : $content,
935 'content-type' => $content_type,
937 $sendmail_params{'Auth'} = {user
=> $username, pass
=> $password, method
=> $method} if $username;
938 if ( my $bcc = C4
::Context
->preference('OverdueNoticeBcc') ) {
939 $sendmail_params{ Bcc
} = $bcc;
942 _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
943 if ( sendmail
( %sendmail_params ) ) {
944 _set_message_status
( { message_id
=> $message->{'message_id'},
945 status
=> 'sent' } );
948 _set_message_status
( { message_id
=> $message->{'message_id'},
949 status
=> 'failed' } );
950 carp
$Mail::Sendmail
::error
;
956 my ($content, $title) = @_;
958 my $css = C4
::Context
->preference("NoticeCSS") || '';
959 $css = qq{<link rel
="stylesheet" type
="text/css" href
="$css">} if $css;
961 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
962 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
963 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
965 <title>$title</title>
966 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
976 sub _send_message_by_sms
($) {
977 my $message = shift or return undef;
978 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
979 return unless $member->{'smsalertnumber'};
981 my $success = C4
::SMS
->send_sms( { destination
=> $member->{'smsalertnumber'},
982 message
=> $message->{'content'},
984 _set_message_status
( { message_id
=> $message->{'message_id'},
985 status
=> ($success ?
'sent' : 'failed') } );
989 sub _update_message_to_address
{
991 my $dbh = C4
::Context
->dbh();
992 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
995 sub _set_message_status
($) {
996 my $params = shift or return undef;
998 foreach my $required_parameter ( qw( message_id status ) ) {
999 return undef unless exists $params->{ $required_parameter };
1002 my $dbh = C4
::Context
->dbh();
1003 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1004 my $sth = $dbh->prepare( $statement );
1005 my $result = $sth->execute( $params->{'status'},
1006 $params->{'message_id'} );