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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
26 use C4
::Koha
qw(GetAuthorisedValueByCode);
28 use C4
::Members
::Attributes
qw(GetBorrowerAttributes);
34 use Koha
::SMS
::Providers
;
36 use Date
::Calc
qw( Add_Delta_Days );
40 use Koha
::DateUtils
qw( format_sqldatetime );
42 use vars
qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
48 &GetLetters &GetLettersAvailableForALibrary &GetLetterTemplates &DelLetter &GetPreparedLetter &GetWrappedLetter &addalert &getalert &delalert &findrelatedto &SendAlerts &GetPrintMessages &GetMessageTransportTypes
54 C4::Letters - Give functions for Letters management
62 "Letters" is the tool used in Koha to manage informations sent to the patrons and/or the library. This include some cron jobs like
63 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)
65 Letters are managed through "alerts" sent by Koha on some events. All "alert" related functions are in this module too.
67 =head2 GetLetters([$module])
69 $letters = &GetLetters($module);
70 returns informations about letters.
71 if needed, $module filters for letters given module
77 my $module = $filters->{module
};
78 my $code = $filters->{code
};
79 my $branchcode = $filters->{branchcode
};
80 my $dbh = C4
::Context
->dbh;
81 my $letters = $dbh->selectall_arrayref(
83 SELECT module
, code
, branchcode
, name
87 . ( $module ? q
| AND module
= ?
| : q
|| )
88 . ( $code ? q
| AND code
= ?
| : q
|| )
89 . ( defined $branchcode ? q
| AND branchcode
= ?
| : q
|| )
90 . q
| GROUP BY code ORDER BY name
|, { Slice
=> {} }
91 , ( $module ?
$module : () )
92 , ( $code ?
$code : () )
93 , ( defined $branchcode ?
$branchcode : () )
99 =head2 GetLetterTemplates
101 my $letter_templates = GetLetterTemplates(
103 module => 'circulation',
105 branchcode => 'CPL', # '' for default,
109 Return a hashref of letter templates.
110 The key will be the message transport type.
114 sub GetLetterTemplates
{
117 my $module = $params->{module
};
118 my $code = $params->{code
};
119 my $branchcode = $params->{branchcode
} // '';
120 my $dbh = C4
::Context
->dbh;
121 my $letters = $dbh->selectall_hashref(
123 SELECT module
, code
, branchcode
, name
, is_html
, title
, content
, message_transport_type
129 , 'message_transport_type'
131 , $module, $code, $branchcode
137 =head2 GetLettersAvailableForALibrary
139 my $letters = GetLettersAvailableForALibrary(
141 branchcode => 'CPL', # '' for default
142 module => 'circulation',
146 Return an arrayref of letters, sorted by name.
147 If a specific letter exist for the given branchcode, it will be retrieve.
148 Otherwise the default letter will be.
152 sub GetLettersAvailableForALibrary
{
154 my $branchcode = $filters->{branchcode
};
155 my $module = $filters->{module
};
157 croak
"module should be provided" unless $module;
159 my $dbh = C4
::Context
->dbh;
160 my $default_letters = $dbh->selectall_arrayref(
162 SELECT module
, code
, branchcode
, name
166 . q
| AND branchcode
= ''|
167 . ( $module ? q
| AND module
= ?
| : q
|| )
168 . q
| ORDER BY name
|, { Slice
=> {} }
169 , ( $module ?
$module : () )
172 my $specific_letters;
174 $specific_letters = $dbh->selectall_arrayref(
176 SELECT module
, code
, branchcode
, name
180 . q
| AND branchcode
= ?
|
181 . ( $module ? q
| AND module
= ?
| : q
|| )
182 . q
| ORDER BY name
|, { Slice
=> {} }
184 , ( $module ?
$module : () )
189 for my $l (@
$default_letters) {
190 $letters{ $l->{code
} } = $l;
192 for my $l (@
$specific_letters) {
193 # Overwrite the default letter with the specific one.
194 $letters{ $l->{code
} } = $l;
197 return [ map { $letters{$_} }
198 sort { $letters{$a}->{name
} cmp $letters{$b}->{name
} }
204 my ( $module, $code, $branchcode, $message_transport_type ) = @_;
205 $message_transport_type //= '%';
207 if ( C4
::Context
->preference('IndependentBranches')
209 and C4
::Context
->userenv ) {
211 $branchcode = C4
::Context
->userenv->{'branch'};
215 my $dbh = C4
::Context
->dbh;
216 my $sth = $dbh->prepare(q{
219 WHERE module=? AND code=? AND (branchcode = ? OR branchcode = '')
220 AND message_transport_type LIKE ?
221 ORDER BY branchcode DESC LIMIT 1
223 $sth->execute( $module, $code, $branchcode, $message_transport_type );
224 my $line = $sth->fetchrow_hashref
226 $line->{'content-type'} = 'text/html; charset="UTF-8"' if $line->{is_html
};
236 module => 'circulation',
242 Delete the letter. The mtt parameter is facultative.
243 If not given, all templates mathing the other parameters will be removed.
249 my $branchcode = $params->{branchcode
};
250 my $module = $params->{module
};
251 my $code = $params->{code
};
252 my $mtt = $params->{mtt
};
253 my $dbh = C4
::Context
->dbh;
259 | . ( $mtt ? q
| AND message_transport_type
= ?
| : q
|| )
260 , undef, $branchcode, $module, $code, ( $mtt ?
$mtt : () ) );
263 =head2 addalert ($borrowernumber, $type, $externalid)
266 - $borrowernumber : the number of the borrower subscribing to the alert
267 - $type : the type of alert.
268 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
270 create an alert and return the alertid (primary key)
275 my ( $borrowernumber, $type, $externalid ) = @_;
276 my $dbh = C4
::Context
->dbh;
279 "insert into alert (borrowernumber, type, externalid) values (?,?,?)");
280 $sth->execute( $borrowernumber, $type, $externalid );
282 # get the alert number newly created and return it
283 my $alertid = $dbh->{'mysql_insertid'};
287 =head2 delalert ($alertid)
290 - alertid : the alert id
296 my $alertid = shift or die "delalert() called without valid argument (alertid)"; # it's gonna die anyway.
297 $debug and warn "delalert: deleting alertid $alertid";
298 my $sth = C4
::Context
->dbh->prepare("delete from alert where alertid=?");
299 $sth->execute($alertid);
302 =head2 getalert ([$borrowernumber], [$type], [$externalid])
305 - $borrowernumber : the number of the borrower subscribing to the alert
306 - $type : the type of alert.
307 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
308 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.
313 my ( $borrowernumber, $type, $externalid ) = @_;
314 my $dbh = C4
::Context
->dbh;
315 my $query = "SELECT a.*, b.branchcode FROM alert a JOIN borrowers b USING(borrowernumber) WHERE 1";
317 if ($borrowernumber and $borrowernumber =~ /^\d+$/) {
318 $query .= " AND borrowernumber=?";
319 push @bind, $borrowernumber;
322 $query .= " AND type=?";
326 $query .= " AND externalid=?";
327 push @bind, $externalid;
329 my $sth = $dbh->prepare($query);
330 $sth->execute(@bind);
331 return $sth->fetchall_arrayref({});
334 =head2 findrelatedto($type, $externalid)
337 - $type : the type of alert
338 - $externalid : the id of the "object" to query
340 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.
341 When type=issue, the id is related to a subscriptionid and this sub returns the name of the biblio.
346 # When type=virtual, the id is related to a virtual shelf and this sub returns the name of the sub
349 my $type = shift or return;
350 my $externalid = shift or return;
351 my $q = ($type eq 'issue' ) ?
352 "select title as result from subscription left join biblio on subscription.biblionumber=biblio.biblionumber where subscriptionid=?" :
353 ($type eq 'borrower') ?
354 "select concat(firstname,' ',surname) from borrowers where borrowernumber=?" : undef;
356 warn "findrelatedto(): Illegal type '$type'";
359 my $sth = C4
::Context
->dbh->prepare($q);
360 $sth->execute($externalid);
361 my ($result) = $sth->fetchrow;
368 - $type : the type of alert
369 - $externalid : the id of the "object" to query
370 - $letter_code : the letter to send.
372 send an alert to all borrowers having put an alert on a given subject.
377 my ( $type, $externalid, $letter_code ) = @_;
378 my $dbh = C4
::Context
->dbh;
379 if ( $type eq 'issue' ) {
381 # prepare the letter...
382 # search the subscriptionid
385 "SELECT subscriptionid FROM serial WHERE serialid=?");
386 $sth->execute($externalid);
387 my ($subscriptionid) = $sth->fetchrow
388 or warn( "No subscription for '$externalid'" ),
391 # search the biblionumber
394 "SELECT biblionumber FROM subscription WHERE subscriptionid=?");
395 $sth->execute($subscriptionid);
396 my ($biblionumber) = $sth->fetchrow
397 or warn( "No biblionumber for '$subscriptionid'" ),
401 # find the list of borrowers to alert
402 my $alerts = getalert
( '', 'issue', $subscriptionid );
404 my $borinfo = C4
::Members
::GetMember
('borrowernumber' => $_->{'borrowernumber'});
405 my $email = $borinfo->{email
} or next;
407 # warn "sending issues...";
408 my $userenv = C4
::Context
->userenv;
409 my $library = Koha
::Libraries
->find( $_->{branchcode
} );
410 my $letter = GetPreparedLetter
(
412 letter_code
=> $letter_code,
413 branchcode
=> $userenv->{branch
},
415 'branches' => $_->{branchcode
},
416 'biblio' => $biblionumber,
417 'biblioitems' => $biblionumber,
418 'borrowers' => $borinfo,
419 'subscription' => $subscriptionid,
420 'serial' => $externalid,
426 my $message = Koha
::Email
->new();
427 my %mail = $message->create_message_headers(
430 from
=> $library->branchemail,
431 replyto
=> $library->branchreplyto,
432 sender
=> $library->branchreturnpath,
433 subject
=> Encode
::encode
( "UTF-8", "" . $letter->{title
} ),
434 message
=> $letter->{'is_html'}
435 ? _wrap_html
( Encode
::encode
( "UTF-8", $letter->{'content'} ),
436 Encode
::encode
( "UTF-8", "" . $letter->{'title'} ))
437 : Encode
::encode
( "UTF-8", "" . $letter->{'content'} ),
438 contenttype
=> $letter->{'is_html'}
439 ?
'text/html; charset="utf-8"'
440 : 'text/plain; charset="utf-8"',
443 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
446 elsif ( $type eq 'claimacquisition' or $type eq 'claimissues' ) {
448 # prepare the letter...
449 # search the biblionumber
450 my $strsth = $type eq 'claimacquisition'
452 SELECT aqorders
.*,aqbasket
.*,biblio
.*,biblioitems
.*
454 LEFT JOIN aqbasket ON aqbasket
.basketno
=aqorders
.basketno
455 LEFT JOIN biblio ON aqorders
.biblionumber
=biblio
.biblionumber
456 LEFT JOIN biblioitems ON aqorders
.biblionumber
=biblioitems
.biblionumber
457 WHERE aqorders
.ordernumber IN
(
460 SELECT serial
.*,subscription
.*, biblio
.*, aqbooksellers
.*,
461 aqbooksellers
.id AS booksellerid
463 LEFT JOIN subscription ON serial
.subscriptionid
=subscription
.subscriptionid
464 LEFT JOIN biblio ON serial
.biblionumber
=biblio
.biblionumber
465 LEFT JOIN aqbooksellers ON subscription
.aqbooksellerid
=aqbooksellers
.id
466 WHERE serial
.serialid IN
(
470 carp
"No Order seleted";
471 return { error
=> "no_order_seleted" };
474 $strsth .= join( ",", @
$externalid ) . ")";
475 my $sthorders = $dbh->prepare($strsth);
477 my $dataorders = $sthorders->fetchall_arrayref( {} );
480 $dbh->prepare("select * from aqbooksellers where id=?");
481 $sthbookseller->execute( $dataorders->[0]->{booksellerid
} );
482 my $databookseller = $sthbookseller->fetchrow_hashref;
483 my $addressee = $type eq 'claimacquisition' ?
'acqprimary' : 'serialsprimary';
485 $dbh->prepare("SELECT * FROM aqcontacts WHERE booksellerid=? AND $type=1 ORDER BY $addressee DESC");
486 $sthcontact->execute( $dataorders->[0]->{booksellerid
} );
487 my $datacontact = $sthcontact->fetchrow_hashref;
491 push @email, $databookseller->{bookselleremail
} if $databookseller->{bookselleremail
};
492 push @email, $datacontact->{email
} if ( $datacontact && $datacontact->{email
} );
494 warn "Bookseller $dataorders->[0]->{booksellerid} without emails";
495 return { error
=> "no_email" };
498 while ($addlcontact = $sthcontact->fetchrow_hashref) {
499 push @cc, $addlcontact->{email
} if ( $addlcontact && $addlcontact->{email
} );
502 my $userenv = C4
::Context
->userenv;
503 my $letter = GetPreparedLetter
(
505 letter_code
=> $letter_code,
506 branchcode
=> $userenv->{branch
},
508 'branches' => $userenv->{branch
},
509 'aqbooksellers' => $databookseller,
510 'aqcontacts' => $datacontact,
512 repeat
=> $dataorders,
516 # Remove the order tag
517 $letter->{content
} =~ s/<order>(.*?)<\/order>/$1/gxms
;
521 To
=> join( ',', @email),
522 Cc
=> join( ',', @cc),
523 From
=> $userenv->{emailaddress
},
524 Subject
=> Encode
::encode
( "UTF-8", "" . $letter->{title
} ),
525 Message
=> $letter->{'is_html'}
526 ? _wrap_html
( Encode
::encode
( "UTF-8", $letter->{'content'} ),
527 Encode
::encode
( "UTF-8", "" . $letter->{'title'} ))
528 : Encode
::encode
( "UTF-8", "" . $letter->{'content'} ),
529 'Content-Type' => $letter->{'is_html'}
530 ?
'text/html; charset="utf-8"'
531 : 'text/plain; charset="utf-8"',
534 $mail{'Reply-to'} = C4
::Context
->preference('ReplytoDefault')
535 if C4
::Context
->preference('ReplytoDefault');
536 $mail{'Sender'} = C4
::Context
->preference('ReturnpathDefault')
537 if C4
::Context
->preference('ReturnpathDefault');
538 $mail{'Bcc'} = $userenv->{emailaddress
}
539 if C4
::Context
->preference("ClaimsBccCopy");
541 unless ( sendmail
(%mail) ) {
542 carp
$Mail::Sendmail
::error
;
543 return { error
=> $Mail::Sendmail
::error
};
548 $type eq 'claimissues' ?
"CLAIM ISSUE" : "ACQUISITION CLAIM",
551 . join( ',', @email )
556 ) if C4
::Context
->preference("LetterLog");
558 # send an "account details" notice to a newly created user
559 elsif ( $type eq 'members' ) {
560 my $library = Koha
::Libraries
->find( $externalid->{branchcode
} )->unblessed;
561 my $letter = GetPreparedLetter
(
563 letter_code
=> $letter_code,
564 branchcode
=> $externalid->{'branchcode'},
566 'branches' => $library,
567 'borrowers' => $externalid->{'borrowernumber'},
569 substitute
=> { 'borrowers.password' => $externalid->{'password'} },
572 return { error
=> "no_email" } unless $externalid->{'emailaddr'};
573 my $email = Koha
::Email
->new();
574 my %mail = $email->create_message_headers(
576 to
=> $externalid->{'emailaddr'},
577 from
=> $library->{branchemail
},
578 replyto
=> $library->{branchreplyto
},
579 sender
=> $library->{branchreturnpath
},
580 subject
=> Encode
::encode
( "UTF-8", "" . $letter->{'title'} ),
581 message
=> $letter->{'is_html'}
582 ? _wrap_html
( Encode
::encode
( "UTF-8", $letter->{'content'} ),
583 Encode
::encode
( "UTF-8", "" . $letter->{'title'} ) )
584 : Encode
::encode
( "UTF-8", "" . $letter->{'content'} ),
585 contenttype
=> $letter->{'is_html'}
586 ?
'text/html; charset="utf-8"'
587 : 'text/plain; charset="utf-8"',
590 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
594 =head2 GetPreparedLetter( %params )
597 module => letter module, mandatory
598 letter_code => letter code, mandatory
599 branchcode => for letter selection, if missing default system letter taken
600 tables => a hashref with table names as keys. Values are either:
601 - a scalar - primary key value
602 - an arrayref - primary key values
603 - a hashref - full record
604 substitute => custom substitution key/value pairs
605 repeat => records to be substituted on consecutive lines:
606 - an arrayref - tries to guess what needs substituting by
607 taking remaining << >> tokensr; not recommended
608 - a hashref token => @tables - replaces <token> << >> << >> </token>
609 subtemplate for each @tables row; table is a hashref as above
610 want_librarian => boolean, if set to true triggers librarian details
611 substitution from the userenv
613 letter fields hashref (title & content useful)
617 sub GetPreparedLetter
{
620 my $module = $params{module
} or croak
"No module";
621 my $letter_code = $params{letter_code
} or croak
"No letter_code";
622 my $branchcode = $params{branchcode
} || '';
623 my $mtt = $params{message_transport_type
} || 'email';
625 my $letter = getletter
( $module, $letter_code, $branchcode, $mtt )
626 or warn( "No $module $letter_code letter transported by " . $mtt ),
629 my $tables = $params{tables
};
630 my $substitute = $params{substitute
};
631 my $repeat = $params{repeat
};
632 $tables || $substitute || $repeat
633 or carp
( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
635 my $want_librarian = $params{want_librarian
};
638 while ( my ($token, $val) = each %$substitute ) {
639 if ( $token eq 'items.content' ) {
640 $val =~ s
|\n|<br
/>|g
if $letter->{is_html
};
643 $letter->{title
} =~ s/<<$token>>/$val/g;
644 $letter->{content
} =~ s/<<$token>>/$val/g;
648 my $OPACBaseURL = C4
::Context
->preference('OPACBaseURL');
649 $letter->{content
} =~ s/<<OPACBaseURL>>/$OPACBaseURL/go;
651 if ($want_librarian) {
652 # parsing librarian name
653 my $userenv = C4
::Context
->userenv;
654 $letter->{content
} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
655 $letter->{content
} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
656 $letter->{content
} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
659 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
662 if (ref ($repeat) eq 'ARRAY' ) {
663 $repeat_no_enclosing_tags = $repeat;
665 $repeat_enclosing_tags = $repeat;
669 if ($repeat_enclosing_tags) {
670 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
671 if ( $letter->{content
} =~ m!<$tag>(.*)</$tag>!s ) {
674 my %subletter = ( title
=> '', content
=> $subcontent );
675 _substitute_tables
( \
%subletter, $_ );
678 $letter->{content
} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
684 _substitute_tables
( $letter, $tables );
687 if ($repeat_no_enclosing_tags) {
688 if ( $letter->{content
} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
693 $c =~ s/<<count>>/$i/go;
694 foreach my $field ( keys %{$_} ) {
695 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
699 } @
$repeat_no_enclosing_tags;
701 my $replaceby = join( "\n", @lines );
702 $letter->{content
} =~ s/\Q$line\E/$replaceby/s;
706 $letter->{content
} =~ s/<<\S*>>//go; #remove any stragglers
707 # $letter->{content} =~ s/<<[^>]*>>//go;
712 sub _substitute_tables
{
713 my ( $letter, $tables ) = @_;
714 while ( my ($table, $param) = each %$tables ) {
717 my $ref = ref $param;
720 if ($ref && $ref eq 'HASH') {
724 my $sth = _parseletter_sth
($table);
726 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
729 $sth->execute( $ref ? @
$param : $param );
731 $values = $sth->fetchrow_hashref;
735 _parseletter
( $letter, $table, $values );
739 sub _parseletter_sth
{
743 carp
"ERROR: _parseletter_sth() called without argument (table)";
746 # NOTE: we used to check whether we had a statement handle cached in
747 # a %handles module-level variable. This was a dumb move and
748 # broke things for the rest of us. prepare_cached is a better
749 # way to cache statement handles anyway.
751 ($table eq 'biblio' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
752 ($table eq 'biblioitems' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
753 ($table eq 'items' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
754 ($table eq 'issues' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
755 ($table eq 'old_issues' ) ?
"SELECT * FROM $table WHERE itemnumber = ? ORDER BY timestamp DESC LIMIT 1" :
756 ($table eq 'reserves' ) ?
"SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
757 ($table eq 'borrowers' ) ?
"SELECT * FROM $table WHERE borrowernumber = ?" :
758 ($table eq 'branches' ) ?
"SELECT * FROM $table WHERE branchcode = ?" :
759 ($table eq 'suggestions' ) ?
"SELECT * FROM $table WHERE suggestionid = ?" :
760 ($table eq 'aqbooksellers') ?
"SELECT * FROM $table WHERE id = ?" :
761 ($table eq 'aqorders' ) ?
"SELECT * FROM $table WHERE ordernumber = ?" :
762 ($table eq 'opac_news' ) ?
"SELECT * FROM $table WHERE idnew = ?" :
763 ($table eq 'borrower_modifications') ?
"SELECT * FROM $table WHERE verification_token = ?" :
764 ($table eq 'subscription') ?
"SELECT * FROM $table WHERE subscriptionid = ?" :
765 ($table eq 'serial') ?
"SELECT * FROM $table WHERE serialid = ?" :
768 warn "ERROR: No _parseletter_sth query for table '$table'";
769 return; # nothing to get
771 unless ($sth = C4
::Context
->dbh->prepare_cached($query)) {
772 warn "ERROR: Failed to prepare query: '$query'";
775 return $sth; # now cache is populated for that $table
778 =head2 _parseletter($letter, $table, $values)
781 - $letter : a hash to letter fields (title & content useful)
782 - $table : the Koha table to parse.
783 - $values_in : table record hashref
784 parse all fields from a table, and replace values in title & content with the appropriate value
785 (not exported sub, used only internally)
790 my ( $letter, $table, $values_in ) = @_;
792 # Work on a local copy of $values_in (passed by reference) to avoid side effects
793 # in callers ( by changing / formatting values )
794 my $values = $values_in ?
{ %$values_in } : {};
796 if ( $table eq 'borrowers' && $values->{'dateexpiry'} ){
797 $values->{'dateexpiry'} = format_sqldatetime
( $values->{'dateexpiry'} );
800 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
801 my @waitingdate = split /-/, $values->{'waitingdate'};
803 $values->{'expirationdate'} = '';
804 if ( C4
::Context
->preference('ReservesMaxPickUpDelay') ) {
805 my $dt = dt_from_string
();
806 $dt->add( days
=> C4
::Context
->preference('ReservesMaxPickUpDelay') );
807 $values->{'expirationdate'} = output_pref
( { dt
=> $dt, dateonly
=> 1 } );
810 $values->{'waitingdate'} = output_pref
({ dt
=> dt_from_string
( $values->{'waitingdate'} ), dateonly
=> 1 });
814 if ($letter->{content
} && $letter->{content
} =~ /<<today>>/) {
815 my $todaysdate = output_pref
( DateTime
->now() );
816 $letter->{content
} =~ s/<<today>>/$todaysdate/go;
819 while ( my ($field, $val) = each %$values ) {
820 $val =~ s/\p{P}$// if $val && $table=~/biblio/;
821 #BZ 9886: Assuming that we want to eliminate ISBD punctuation here
822 #Therefore adding the test on biblio. This includes biblioitems,
823 #but excludes items. Removed unneeded global and lookahead.
825 $val = GetAuthorisedValueByCode
('ROADTYPE', $val, 0) if $table=~/^borrowers$/ && $field=~/^streettype$/;
828 my $replacedby = defined ($val) ?
$val : '';
830 and not $replacedby =~ m
|0000-00-00|
831 and not $replacedby =~ m
|9999-12-31|
832 and $replacedby =~ m
|^\d
{4}-\d
{2}-\d
{2}( \d
{2}:\d
{2}:\d
{2})?
$| )
834 # If the value is XXXX-YY-ZZ[ AA:BB:CC] we assume it is a date
835 my $dateonly = defined $1 ?
0 : 1; #$1 refers to the capture group wrapped in parentheses. In this case, that's the hours, minutes, seconds.
836 my $re_dateonly_filter = qr{ $field( \s* \| \s* dateonly\s*)?>> }xms;
838 for my $letter_field ( qw( title content ) ) {
839 my $filter_string_used = q{};
840 if ( $letter->{ $letter_field } =~ $re_dateonly_filter ) {
841 # We overwrite $dateonly if the filter exists and we have a time in the datetime
842 $filter_string_used = $1 || q{};
843 $dateonly = $1 unless $dateonly;
845 my $replacedby_date = eval {
846 output_pref
({ dt
=> dt_from_string
( $replacedby ), dateonly
=> $dateonly });
849 if ( $letter->{ $letter_field } ) {
850 $letter->{ $letter_field } =~ s/\Q<<$table.$field$filter_string_used>>\E/$replacedby_date/g;
851 $letter->{ $letter_field } =~ s/\Q<<$field$filter_string_used>>\E/$replacedby_date/g;
855 # Other fields replacement
857 for my $letter_field ( qw( title content ) ) {
858 if ( $letter->{ $letter_field } ) {
859 $letter->{ $letter_field } =~ s/<<$table.$field>>/$replacedby/g;
860 $letter->{ $letter_field } =~ s/<<$field>>/$replacedby/g;
866 if ($table eq 'borrowers' && $letter->{content
}) {
867 if ( my $attributes = GetBorrowerAttributes
($values->{borrowernumber
}) ) {
869 foreach (@
$attributes) {
870 my $code = $_->{code
};
871 my $val = $_->{value_description
} || $_->{value
};
872 $val =~ s/\p{P}(?=$)//g if $val;
873 next unless $val gt '';
875 push @
{ $attr{$code} }, $val;
877 while ( my ($code, $val_ar) = each %attr ) {
878 my $replacefield = "<<borrower-attribute:$code>>";
879 my $replacedby = join ',', @
$val_ar;
880 $letter->{content
} =~ s/$replacefield/$replacedby/g;
889 my $success = EnqueueLetter( { letter => $letter,
890 borrowernumber => '12', message_transport_type => 'email' } )
892 places a letter in the message_queue database table, which will
893 eventually get processed (sent) by the process_message_queue.pl
894 cronjob when it calls SendQueuedMessages.
896 return message_id on success
901 my $params = shift or return;
903 return unless exists $params->{'letter'};
904 # return unless exists $params->{'borrowernumber'};
905 return unless exists $params->{'message_transport_type'};
907 my $content = $params->{letter
}->{content
};
908 $content =~ s/\s+//g if(defined $content);
909 if ( not defined $content or $content eq '' ) {
910 warn "Trying to add an empty message to the message queue" if $debug;
914 # If we have any attachments we should encode then into the body.
915 if ( $params->{'attachments'} ) {
916 $params->{'letter'} = _add_attachments
(
917 { letter
=> $params->{'letter'},
918 attachments
=> $params->{'attachments'},
919 message
=> MIME
::Lite
->new( Type
=> 'multipart/mixed' ),
924 my $dbh = C4
::Context
->dbh();
925 my $statement = << 'ENDSQL';
926 INSERT INTO message_queue
927 ( borrowernumber
, subject
, content
, metadata
, letter_code
, message_transport_type
, status
, time_queued
, to_address
, from_address
, content_type
)
929 ( ?
, ?
, ?
, ?
, ?
, ?
, ?
, NOW
(), ?
, ?
, ?
)
932 my $sth = $dbh->prepare($statement);
933 my $result = $sth->execute(
934 $params->{'borrowernumber'}, # borrowernumber
935 $params->{'letter'}->{'title'}, # subject
936 $params->{'letter'}->{'content'}, # content
937 $params->{'letter'}->{'metadata'} || '', # metadata
938 $params->{'letter'}->{'code'} || '', # letter_code
939 $params->{'message_transport_type'}, # message_transport_type
941 $params->{'to_address'}, # to_address
942 $params->{'from_address'}, # from_address
943 $params->{'letter'}->{'content-type'}, # content_type
945 return $dbh->last_insert_id(undef,undef,'message_queue', undef);
948 =head2 SendQueuedMessages ([$hashref])
950 my $sent = SendQueuedMessages( { verbose => 1 } );
952 sends all of the 'pending' items in the message queue.
954 returns number of messages sent.
958 sub SendQueuedMessages
{
961 my $unsent_messages = _get_unsent_messages
();
962 MESSAGE
: foreach my $message ( @
$unsent_messages ) {
963 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
964 warn sprintf( 'sending %s message to patron: %s',
965 $message->{'message_transport_type'},
966 $message->{'borrowernumber'} || 'Admin' )
967 if $params->{'verbose'} or $debug;
968 # This is just begging for subclassing
969 next MESSAGE
if ( lc($message->{'message_transport_type'}) eq 'rss' );
970 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
971 _send_message_by_email
( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
973 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
974 if ( C4
::Context
->preference('SMSSendDriver') eq 'Email' ) {
975 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
976 my $sms_provider = Koha
::SMS
::Providers
->find( $member->{'sms_provider_id'} );
977 $message->{to_address
} .= '@' . $sms_provider->domain();
978 _send_message_by_email
( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
980 _send_message_by_sms
( $message );
984 return scalar( @
$unsent_messages );
987 =head2 GetRSSMessages
989 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
991 returns a listref of all queued RSS messages for a particular person.
998 return unless $params;
999 return unless ref $params;
1000 return unless $params->{'borrowernumber'};
1002 return _get_unsent_messages
( { message_transport_type
=> 'rss',
1003 limit
=> $params->{'limit'},
1004 borrowernumber
=> $params->{'borrowernumber'}, } );
1007 =head2 GetPrintMessages
1009 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
1011 Returns a arrayref of all queued print messages (optionally, for a particular
1016 sub GetPrintMessages
{
1017 my $params = shift || {};
1019 return _get_unsent_messages
( { message_transport_type
=> 'print',
1020 borrowernumber
=> $params->{'borrowernumber'},
1024 =head2 GetQueuedMessages ([$hashref])
1026 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
1028 fetches messages out of the message queue.
1031 list of hashes, each has represents a message in the message queue.
1035 sub GetQueuedMessages
{
1038 my $dbh = C4
::Context
->dbh();
1039 my $statement = << 'ENDSQL';
1040 SELECT message_id
, borrowernumber
, subject
, content
, message_transport_type
, status
, time_queued
1046 if ( exists $params->{'borrowernumber'} ) {
1047 push @whereclauses, ' borrowernumber = ? ';
1048 push @query_params, $params->{'borrowernumber'};
1051 if ( @whereclauses ) {
1052 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
1055 if ( defined $params->{'limit'} ) {
1056 $statement .= ' LIMIT ? ';
1057 push @query_params, $params->{'limit'};
1060 my $sth = $dbh->prepare( $statement );
1061 my $result = $sth->execute( @query_params );
1062 return $sth->fetchall_arrayref({});
1065 =head2 GetMessageTransportTypes
1067 my @mtt = GetMessageTransportTypes();
1069 returns an arrayref of transport types
1073 sub GetMessageTransportTypes
{
1074 my $dbh = C4
::Context
->dbh();
1075 my $mtts = $dbh->selectcol_arrayref("
1076 SELECT message_transport_type
1077 FROM message_transport_types
1078 ORDER BY message_transport_type
1085 my $message = C4::Letters::Message($message_id);
1090 my ( $message_id ) = @_;
1091 return unless $message_id;
1092 my $dbh = C4
::Context
->dbh;
1093 return $dbh->selectrow_hashref(q
|
1094 SELECT message_id
, borrowernumber
, subject
, content
, metadata
, letter_code
, message_transport_type
, status
, time_queued
, to_address
, from_address
, content_type
1096 WHERE message_id
= ?
1097 |, {}, $message_id );
1100 =head2 ResendMessage
1102 Attempt to resend a message which has failed previously.
1104 my $has_been_resent = C4::Letters::ResendMessage($message_id);
1106 Updates the message to 'pending' status so that
1107 it will be resent later on.
1109 returns 1 on success, 0 on failure, undef if no message was found
1114 my $message_id = shift;
1115 return unless $message_id;
1117 my $message = GetMessage
( $message_id );
1118 return unless $message;
1120 if ( $message->{status
} ne 'pending' ) {
1121 $rv = C4
::Letters
::_set_message_status
({
1122 message_id
=> $message_id,
1123 status
=> 'pending',
1125 $rv = $rv > 0?
1: 0;
1126 # Clear destination email address to force address update
1127 _update_message_to_address
( $message_id, undef ) if $rv &&
1128 $message->{message_transport_type
} eq 'email';
1133 =head2 _add_attachements
1136 letter - the standard letter hashref
1137 attachments - listref of attachments. each attachment is a hashref of:
1138 type - the mime type, like 'text/plain'
1139 content - the actual attachment
1140 filename - the name of the attachment.
1141 message - a MIME::Lite object to attach these to.
1143 returns your letter object, with the content updated.
1147 sub _add_attachments
{
1150 my $letter = $params->{'letter'};
1151 my $attachments = $params->{'attachments'};
1152 return $letter unless @
$attachments;
1153 my $message = $params->{'message'};
1155 # First, we have to put the body in as the first attachment
1157 Type
=> $letter->{'content-type'} || 'TEXT',
1158 Data
=> $letter->{'is_html'}
1159 ? _wrap_html
($letter->{'content'}, $letter->{'title'})
1160 : $letter->{'content'},
1163 foreach my $attachment ( @
$attachments ) {
1165 Type
=> $attachment->{'type'},
1166 Data
=> $attachment->{'content'},
1167 Filename
=> $attachment->{'filename'},
1170 # we're forcing list context here to get the header, not the count back from grep.
1171 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
1172 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
1173 $letter->{'content'} = $message->body_as_string;
1179 sub _get_unsent_messages
{
1182 my $dbh = C4
::Context
->dbh();
1183 my $statement = << 'ENDSQL';
1184 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
1185 FROM message_queue mq
1186 LEFT JOIN borrowers b ON b
.borrowernumber
= mq
.borrowernumber
1190 my @query_params = ('pending');
1191 if ( ref $params ) {
1192 if ( $params->{'message_transport_type'} ) {
1193 $statement .= ' AND message_transport_type = ? ';
1194 push @query_params, $params->{'message_transport_type'};
1196 if ( $params->{'borrowernumber'} ) {
1197 $statement .= ' AND borrowernumber = ? ';
1198 push @query_params, $params->{'borrowernumber'};
1200 if ( $params->{'limit'} ) {
1201 $statement .= ' limit ? ';
1202 push @query_params, $params->{'limit'};
1206 $debug and warn "_get_unsent_messages SQL: $statement";
1207 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
1208 my $sth = $dbh->prepare( $statement );
1209 my $result = $sth->execute( @query_params );
1210 return $sth->fetchall_arrayref({});
1213 sub _send_message_by_email
{
1214 my $message = shift or return;
1215 my ($username, $password, $method) = @_;
1217 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
1218 my $to_address = $message->{'to_address'};
1219 unless ($to_address) {
1221 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
1222 _set_message_status
( { message_id
=> $message->{'message_id'},
1223 status
=> 'failed' } );
1226 $to_address = C4
::Members
::GetNoticeEmailAddress
( $message->{'borrowernumber'} );
1227 unless ($to_address) {
1228 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
1229 # warning too verbose for this more common case?
1230 _set_message_status
( { message_id
=> $message->{'message_id'},
1231 status
=> 'failed' } );
1236 my $utf8 = decode
('MIME-Header', $message->{'subject'} );
1237 $message->{subject
}= encode
('MIME-Header', $utf8);
1238 my $subject = encode
('UTF-8', $message->{'subject'});
1239 my $content = encode
('UTF-8', $message->{'content'});
1240 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
1241 my $is_html = $content_type =~ m/html/io;
1242 my $branch_email = undef;
1243 my $branch_replyto = undef;
1244 my $branch_returnpath = undef;
1246 my $library = Koha
::Libraries
->find( $member->{branchcode
} );
1247 $branch_email = $library->branchemail;
1248 $branch_replyto = $library->branchreplyto;
1249 $branch_returnpath = $library->branchreturnpath;
1251 my $email = Koha
::Email
->new();
1252 my %sendmail_params = $email->create_message_headers(
1255 from
=> $message->{'from_address'} || $branch_email,
1256 replyto
=> $branch_replyto,
1257 sender
=> $branch_returnpath,
1258 subject
=> $subject,
1259 message
=> $is_html ? _wrap_html
( $content, $subject ) : $content,
1260 contenttype
=> $content_type
1264 $sendmail_params{'Auth'} = {user
=> $username, pass
=> $password, method
=> $method} if $username;
1265 if ( my $bcc = C4
::Context
->preference('OverdueNoticeBcc') ) {
1266 $sendmail_params{ Bcc
} = $bcc;
1269 _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
1271 if ( sendmail
( %sendmail_params ) ) {
1272 _set_message_status
( { message_id
=> $message->{'message_id'},
1273 status
=> 'sent' } );
1276 _set_message_status
( { message_id
=> $message->{'message_id'},
1277 status
=> 'failed' } );
1278 carp
$Mail::Sendmail
::error
;
1284 my ($content, $title) = @_;
1286 my $css = C4
::Context
->preference("NoticeCSS") || '';
1287 $css = qq{<link rel
="stylesheet" type
="text/css" href
="$css">} if $css;
1289 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1290 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1291 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
1293 <title>$title</title>
1294 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1305 my ( $message ) = @_;
1306 my $dbh = C4
::Context
->dbh;
1307 my $count = $dbh->selectrow_array(q
|
1310 WHERE message_transport_type
= ?
1311 AND borrowernumber
= ?
1313 AND CAST
(time_queued AS date
) = CAST
(NOW
() AS date
)
1316 |, {}, $message->{message_transport_type
}, $message->{borrowernumber
}, $message->{letter_code
}, $message->{content
} );
1320 sub _send_message_by_sms
{
1321 my $message = shift or return;
1322 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
1324 unless ( $member->{smsalertnumber
} ) {
1325 _set_message_status
( { message_id
=> $message->{'message_id'},
1326 status
=> 'failed' } );
1330 if ( _is_duplicate
( $message ) ) {
1331 _set_message_status
( { message_id
=> $message->{'message_id'},
1332 status
=> 'failed' } );
1336 my $success = C4
::SMS
->send_sms( { destination
=> $member->{'smsalertnumber'},
1337 message
=> $message->{'content'},
1339 _set_message_status
( { message_id
=> $message->{'message_id'},
1340 status
=> ($success ?
'sent' : 'failed') } );
1344 sub _update_message_to_address
{
1346 my $dbh = C4
::Context
->dbh();
1347 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
1350 sub _set_message_status
{
1351 my $params = shift or return;
1353 foreach my $required_parameter ( qw( message_id status ) ) {
1354 return unless exists $params->{ $required_parameter };
1357 my $dbh = C4
::Context
->dbh();
1358 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1359 my $sth = $dbh->prepare( $statement );
1360 my $result = $sth->execute( $params->{'status'},
1361 $params->{'message_id'} );