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 Date
::Calc
qw( Add_Delta_Days );
39 use vars
qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
43 # set the version for version checking
44 $VERSION = 3.07.00.049;
47 &GetLetters &GetLettersAvailableForALibrary &GetLetterTemplates &DelLetter &GetPreparedLetter &GetWrappedLetter &addalert &getalert &delalert &findrelatedto &SendAlerts &GetPrintMessages &GetMessageTransportTypes
53 C4::Letters - Give functions for Letters management
61 "Letters" is the tool used in Koha to manage informations sent to the patrons and/or the library. This include some cron jobs like
62 late issues, as well as other tasks like sending a mail to users that have subscribed to a "serial issue alert" (= being warned every time a new issue has arrived at the library)
64 Letters are managed through "alerts" sent by Koha on some events. All "alert" related functions are in this module too.
66 =head2 GetLetters([$module])
68 $letters = &GetLetters($module);
69 returns informations about letters.
70 if needed, $module filters for letters given module
76 my $module = $filters->{module
};
77 my $code = $filters->{code
};
78 my $branchcode = $filters->{branchcode
};
79 my $dbh = C4
::Context
->dbh;
80 my $letters = $dbh->selectall_arrayref(
82 SELECT module
, code
, branchcode
, name
86 . ( $module ? q
| AND module
= ?
| : q
|| )
87 . ( $code ? q
| AND code
= ?
| : q
|| )
88 . ( defined $branchcode ? q
| AND branchcode
= ?
| : q
|| )
89 . q
| GROUP BY code ORDER BY name
|, { Slice
=> {} }
90 , ( $module ?
$module : () )
91 , ( $code ?
$code : () )
92 , ( defined $branchcode ?
$branchcode : () )
98 =head2 GetLetterTemplates
100 my $letter_templates = GetLetterTemplates(
102 module => 'circulation',
104 branchcode => 'CPL', # '' for default,
108 Return a hashref of letter templates.
109 The key will be the message transport type.
113 sub GetLetterTemplates
{
116 my $module = $params->{module
};
117 my $code = $params->{code
};
118 my $branchcode = $params->{branchcode
} // '';
119 my $dbh = C4
::Context
->dbh;
120 my $letters = $dbh->selectall_hashref(
122 SELECT module
, code
, branchcode
, name
, is_html
, title
, content
, message_transport_type
128 , 'message_transport_type'
130 , $module, $code, $branchcode
136 =head2 GetLettersAvailableForALibrary
138 my $letters = GetLettersAvailableForALibrary(
140 branchcode => 'CPL', # '' for default
141 module => 'circulation',
145 Return an arrayref of letters, sorted by name.
146 If a specific letter exist for the given branchcode, it will be retrieve.
147 Otherwise the default letter will be.
151 sub GetLettersAvailableForALibrary
{
153 my $branchcode = $filters->{branchcode
};
154 my $module = $filters->{module
};
156 croak
"module should be provided" unless $module;
158 my $dbh = C4
::Context
->dbh;
159 my $default_letters = $dbh->selectall_arrayref(
161 SELECT module
, code
, branchcode
, name
165 . q
| AND branchcode
= ''|
166 . ( $module ? q
| AND module
= ?
| : q
|| )
167 . q
| ORDER BY name
|, { Slice
=> {} }
168 , ( $module ?
$module : () )
171 my $specific_letters;
173 $specific_letters = $dbh->selectall_arrayref(
175 SELECT module
, code
, branchcode
, name
179 . q
| AND branchcode
= ?
|
180 . ( $module ? q
| AND module
= ?
| : q
|| )
181 . q
| ORDER BY name
|, { Slice
=> {} }
183 , ( $module ?
$module : () )
188 for my $l (@
$default_letters) {
189 $letters{ $l->{code
} } = $l;
191 for my $l (@
$specific_letters) {
192 # Overwrite the default letter with the specific one.
193 $letters{ $l->{code
} } = $l;
196 return [ map { $letters{$_} }
197 sort { $letters{$a}->{name
} cmp $letters{$b}->{name
} }
202 # FIXME: using our here means that a Plack server will need to be
203 # restarted fairly regularly when working with this routine.
204 # A better option would be to use Koha::Cache and use a cache
205 # that actually works in a persistent environment, but as a
206 # short-term fix, our will work.
209 my ( $module, $code, $branchcode, $message_transport_type ) = @_;
210 $message_transport_type //= '%';
212 if ( C4
::Context
->preference('IndependentBranches')
214 and C4
::Context
->userenv ) {
216 $branchcode = C4
::Context
->userenv->{'branch'};
220 if ( my $l = $letter{$module}{$code}{$branchcode}{$message_transport_type} ) {
221 return { %$l }; # deep copy
224 my $dbh = C4
::Context
->dbh;
225 my $sth = $dbh->prepare(q{
228 WHERE module=? AND code=? AND (branchcode = ? OR branchcode = '')
229 AND message_transport_type LIKE ?
230 ORDER BY branchcode DESC LIMIT 1
232 $sth->execute( $module, $code, $branchcode, $message_transport_type );
233 my $line = $sth->fetchrow_hashref
235 $line->{'content-type'} = 'text/html; charset="UTF-8"' if $line->{is_html
};
236 $letter{$module}{$code}{$branchcode}{$message_transport_type} = $line;
246 module => 'circulation',
252 Delete the letter. The mtt parameter is facultative.
253 If not given, all templates mathing the other parameters will be removed.
259 my $branchcode = $params->{branchcode
};
260 my $module = $params->{module
};
261 my $code = $params->{code
};
262 my $mtt = $params->{mtt
};
263 my $dbh = C4
::Context
->dbh;
269 | . ( $mtt ? q
| AND message_transport_type
= ?
| : q
|| )
270 , undef, $branchcode, $module, $code, ( $mtt ?
$mtt : () ) );
273 =head2 addalert ($borrowernumber, $type, $externalid)
276 - $borrowernumber : the number of the borrower subscribing to the alert
277 - $type : the type of alert.
278 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
280 create an alert and return the alertid (primary key)
285 my ( $borrowernumber, $type, $externalid ) = @_;
286 my $dbh = C4
::Context
->dbh;
289 "insert into alert (borrowernumber, type, externalid) values (?,?,?)");
290 $sth->execute( $borrowernumber, $type, $externalid );
292 # get the alert number newly created and return it
293 my $alertid = $dbh->{'mysql_insertid'};
297 =head2 delalert ($alertid)
300 - alertid : the alert id
306 my $alertid = shift or die "delalert() called without valid argument (alertid)"; # it's gonna die anyway.
307 $debug and warn "delalert: deleting alertid $alertid";
308 my $sth = C4
::Context
->dbh->prepare("delete from alert where alertid=?");
309 $sth->execute($alertid);
312 =head2 getalert ([$borrowernumber], [$type], [$externalid])
315 - $borrowernumber : the number of the borrower subscribing to the alert
316 - $type : the type of alert.
317 - $externalid : the primary key of the object to put alert on. For issues, the alert is made on subscriptionid.
318 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.
323 my ( $borrowernumber, $type, $externalid ) = @_;
324 my $dbh = C4
::Context
->dbh;
325 my $query = "SELECT a.*, b.branchcode FROM alert a JOIN borrowers b USING(borrowernumber) WHERE";
327 if ($borrowernumber and $borrowernumber =~ /^\d+$/) {
328 $query .= " borrowernumber=? AND ";
329 push @bind, $borrowernumber;
332 $query .= " type=? AND ";
336 $query .= " externalid=? AND ";
337 push @bind, $externalid;
339 $query =~ s/ AND $//;
340 my $sth = $dbh->prepare($query);
341 $sth->execute(@bind);
342 return $sth->fetchall_arrayref({});
345 =head2 findrelatedto($type, $externalid)
348 - $type : the type of alert
349 - $externalid : the id of the "object" to query
351 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.
352 When type=issue, the id is related to a subscriptionid and this sub returns the name of the biblio.
357 # When type=virtual, the id is related to a virtual shelf and this sub returns the name of the sub
360 my $type = shift or return;
361 my $externalid = shift or return;
362 my $q = ($type eq 'issue' ) ?
363 "select title as result from subscription left join biblio on subscription.biblionumber=biblio.biblionumber where subscriptionid=?" :
364 ($type eq 'borrower') ?
365 "select concat(firstname,' ',surname) from borrowers where borrowernumber=?" : undef;
367 warn "findrelatedto(): Illegal type '$type'";
370 my $sth = C4
::Context
->dbh->prepare($q);
371 $sth->execute($externalid);
372 my ($result) = $sth->fetchrow;
379 - $type : the type of alert
380 - $externalid : the id of the "object" to query
381 - $letter_code : the letter to send.
383 send an alert to all borrowers having put an alert on a given subject.
388 my ( $type, $externalid, $letter_code ) = @_;
389 my $dbh = C4
::Context
->dbh;
390 if ( $type eq 'issue' ) {
392 # prepare the letter...
393 # search the biblionumber
396 "SELECT biblionumber FROM subscription WHERE subscriptionid=?");
397 $sth->execute($externalid);
398 my ($biblionumber) = $sth->fetchrow
399 or warn( "No subscription for '$externalid'" ),
403 # find the list of borrowers to alert
404 my $alerts = getalert
( '', 'issue', $externalid );
406 my $borinfo = C4
::Members
::GetMember
('borrowernumber' => $_->{'borrowernumber'});
407 my $email = $borinfo->{email
} or next;
409 # warn "sending issues...";
410 my $userenv = C4
::Context
->userenv;
411 my $branchdetails = GetBranchDetail
($_->{'branchcode'});
412 my $letter = GetPreparedLetter
(
414 letter_code
=> $letter_code,
415 branchcode
=> $userenv->{branch
},
417 'branches' => $_->{branchcode
},
418 'biblio' => $biblionumber,
419 'biblioitems' => $biblionumber,
420 'borrowers' => $borinfo,
426 my $message = Koha
::Email
->new();
427 my %mail = $message->create_message_headers(
430 from
=> $branchdetails->{'branchemail'},
431 replyto
=> $branchdetails->{'branchreplyto'},
432 sender
=> $branchdetails->{'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');
539 unless ( sendmail
(%mail) ) {
540 carp
$Mail::Sendmail
::error
;
541 return { error
=> $Mail::Sendmail
::error
};
546 $type eq 'claimissues' ?
"CLAIM ISSUE" : "ACQUISITION CLAIM",
549 . join( ',', @email )
554 ) if C4
::Context
->preference("LetterLog");
556 # send an "account details" notice to a newly created user
557 elsif ( $type eq 'members' ) {
558 my $branchdetails = GetBranchDetail
($externalid->{'branchcode'});
559 my $letter = GetPreparedLetter
(
561 letter_code
=> $letter_code,
562 branchcode
=> $externalid->{'branchcode'},
564 'branches' => $branchdetails,
565 'borrowers' => $externalid->{'borrowernumber'},
567 substitute
=> { 'borrowers.password' => $externalid->{'password'} },
570 return { error
=> "no_email" } unless $externalid->{'emailaddr'};
571 my $email = Koha
::Email
->new();
572 my %mail = $email->create_message_headers(
574 to
=> $externalid->{'emailaddr'},
575 from
=> $branchdetails->{'branchemail'},
576 replyto
=> $branchdetails->{'branchreplyto'},
577 sender
=> $branchdetails->{'branchreturnpath'},
578 subject
=> Encode
::encode
( "UTF-8", "" . $letter->{'title'} ),
579 message
=> $letter->{'is_html'}
580 ? _wrap_html
( Encode
::encode
( "UTF-8", $letter->{'content'} ),
581 Encode
::encode
( "UTF-8", "" . $letter->{'title'} ) )
582 : Encode
::encode
( "UTF-8", "" . $letter->{'content'} ),
583 contenttype
=> $letter->{'is_html'}
584 ?
'text/html; charset="utf-8"'
585 : 'text/plain; charset="utf-8"',
588 sendmail
(%mail) or carp
$Mail::Sendmail
::error
;
592 =head2 GetPreparedLetter( %params )
595 module => letter module, mandatory
596 letter_code => letter code, mandatory
597 branchcode => for letter selection, if missing default system letter taken
598 tables => a hashref with table names as keys. Values are either:
599 - a scalar - primary key value
600 - an arrayref - primary key values
601 - a hashref - full record
602 substitute => custom substitution key/value pairs
603 repeat => records to be substituted on consecutive lines:
604 - an arrayref - tries to guess what needs substituting by
605 taking remaining << >> tokensr; not recommended
606 - a hashref token => @tables - replaces <token> << >> << >> </token>
607 subtemplate for each @tables row; table is a hashref as above
608 want_librarian => boolean, if set to true triggers librarian details
609 substitution from the userenv
611 letter fields hashref (title & content useful)
615 sub GetPreparedLetter
{
618 my $module = $params{module
} or croak
"No module";
619 my $letter_code = $params{letter_code
} or croak
"No letter_code";
620 my $branchcode = $params{branchcode
} || '';
621 my $mtt = $params{message_transport_type
} || 'email';
623 my $letter = getletter
( $module, $letter_code, $branchcode, $mtt )
624 or warn( "No $module $letter_code letter transported by " . $mtt ),
627 my $tables = $params{tables
};
628 my $substitute = $params{substitute
};
629 my $repeat = $params{repeat
};
630 $tables || $substitute || $repeat
631 or carp
( "ERROR: nothing to substitute - both 'tables' and 'substitute' are empty" ),
633 my $want_librarian = $params{want_librarian
};
636 while ( my ($token, $val) = each %$substitute ) {
637 if ( $token eq 'items.content' ) {
638 $val =~ s
|\n|<br
/>|g
if $letter->{is_html
};
641 $letter->{title
} =~ s/<<$token>>/$val/g;
642 $letter->{content
} =~ s/<<$token>>/$val/g;
646 my $OPACBaseURL = C4
::Context
->preference('OPACBaseURL');
647 $letter->{content
} =~ s/<<OPACBaseURL>>/$OPACBaseURL/go;
649 if ($want_librarian) {
650 # parsing librarian name
651 my $userenv = C4
::Context
->userenv;
652 $letter->{content
} =~ s/<<LibrarianFirstname>>/$userenv->{firstname}/go;
653 $letter->{content
} =~ s/<<LibrarianSurname>>/$userenv->{surname}/go;
654 $letter->{content
} =~ s/<<LibrarianEmailaddress>>/$userenv->{emailaddress}/go;
657 my ($repeat_no_enclosing_tags, $repeat_enclosing_tags);
660 if (ref ($repeat) eq 'ARRAY' ) {
661 $repeat_no_enclosing_tags = $repeat;
663 $repeat_enclosing_tags = $repeat;
667 if ($repeat_enclosing_tags) {
668 while ( my ($tag, $tag_tables) = each %$repeat_enclosing_tags ) {
669 if ( $letter->{content
} =~ m!<$tag>(.*)</$tag>!s ) {
672 my %subletter = ( title
=> '', content
=> $subcontent );
673 _substitute_tables
( \
%subletter, $_ );
676 $letter->{content
} =~ s!<$tag>.*</$tag>!join( "\n", @lines )!se;
682 _substitute_tables
( $letter, $tables );
685 if ($repeat_no_enclosing_tags) {
686 if ( $letter->{content
} =~ m/[^\n]*<<.*>>[^\n]*/so ) {
691 $c =~ s/<<count>>/$i/go;
692 foreach my $field ( keys %{$_} ) {
693 $c =~ s/(<<[^\.]+.$field>>)/$_->{$field}/;
697 } @
$repeat_no_enclosing_tags;
699 my $replaceby = join( "\n", @lines );
700 $letter->{content
} =~ s/\Q$line\E/$replaceby/s;
704 $letter->{content
} =~ s/<<\S*>>//go; #remove any stragglers
705 # $letter->{content} =~ s/<<[^>]*>>//go;
710 sub _substitute_tables
{
711 my ( $letter, $tables ) = @_;
712 while ( my ($table, $param) = each %$tables ) {
715 my $ref = ref $param;
718 if ($ref && $ref eq 'HASH') {
722 my $sth = _parseletter_sth
($table);
724 warn "_parseletter_sth('$table') failed to return a valid sth. No substitution will be done for that table.";
727 $sth->execute( $ref ? @
$param : $param );
729 $values = $sth->fetchrow_hashref;
733 _parseletter
( $letter, $table, $values );
737 sub _parseletter_sth
{
741 carp
"ERROR: _parseletter_sth() called without argument (table)";
744 # NOTE: we used to check whether we had a statement handle cached in
745 # a %handles module-level variable. This was a dumb move and
746 # broke things for the rest of us. prepare_cached is a better
747 # way to cache statement handles anyway.
749 ($table eq 'biblio' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
750 ($table eq 'biblioitems' ) ?
"SELECT * FROM $table WHERE biblionumber = ?" :
751 ($table eq 'items' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
752 ($table eq 'issues' ) ?
"SELECT * FROM $table WHERE itemnumber = ?" :
753 ($table eq 'old_issues' ) ?
"SELECT * FROM $table WHERE itemnumber = ? ORDER BY timestamp DESC LIMIT 1" :
754 ($table eq 'reserves' ) ?
"SELECT * FROM $table WHERE borrowernumber = ? and biblionumber = ?" :
755 ($table eq 'borrowers' ) ?
"SELECT * FROM $table WHERE borrowernumber = ?" :
756 ($table eq 'branches' ) ?
"SELECT * FROM $table WHERE branchcode = ?" :
757 ($table eq 'suggestions' ) ?
"SELECT * FROM $table WHERE suggestionid = ?" :
758 ($table eq 'aqbooksellers') ?
"SELECT * FROM $table WHERE id = ?" :
759 ($table eq 'aqorders' ) ?
"SELECT * FROM $table WHERE ordernumber = ?" :
760 ($table eq 'opac_news' ) ?
"SELECT * FROM $table WHERE idnew = ?" :
761 ($table eq 'borrower_modifications') ?
"SELECT * FROM $table WHERE verification_token = ?" :
764 warn "ERROR: No _parseletter_sth query for table '$table'";
765 return; # nothing to get
767 unless ($sth = C4
::Context
->dbh->prepare_cached($query)) {
768 warn "ERROR: Failed to prepare query: '$query'";
771 return $sth; # now cache is populated for that $table
774 =head2 _parseletter($letter, $table, $values)
777 - $letter : a hash to letter fields (title & content useful)
778 - $table : the Koha table to parse.
779 - $values : table record hashref
780 parse all fields from a table, and replace values in title & content with the appropriate value
781 (not exported sub, used only internally)
786 my ( $letter, $table, $values ) = @_;
788 if ( $table eq 'reserves' && $values->{'waitingdate'} ) {
789 my @waitingdate = split /-/, $values->{'waitingdate'};
791 $values->{'expirationdate'} = '';
792 if ( C4
::Context
->preference('ReservesMaxPickUpDelay') ) {
793 my $dt = dt_from_string
();
794 $dt->add( days
=> C4
::Context
->preference('ReservesMaxPickUpDelay') );
795 $values->{'expirationdate'} = output_pref
( { dt
=> $dt, dateonly
=> 1 } );
798 $values->{'waitingdate'} = output_pref
({ dt
=> dt_from_string
( $values->{'waitingdate'} ), dateonly
=> 1 });
802 if ($letter->{content
} && $letter->{content
} =~ /<<today>>/) {
803 my $todaysdate = output_pref
( DateTime
->now() );
804 $letter->{content
} =~ s/<<today>>/$todaysdate/go;
807 while ( my ($field, $val) = each %$values ) {
808 my $replacetablefield = "<<$table.$field>>";
809 my $replacefield = "<<$field>>";
810 $val =~ s/\p{P}$// if $val && $table=~/biblio/;
811 #BZ 9886: Assuming that we want to eliminate ISBD punctuation here
812 #Therefore adding the test on biblio. This includes biblioitems,
813 #but excludes items. Removed unneeded global and lookahead.
815 $val = GetAuthorisedValueByCode
('ROADTYPE', $val, 0) if $table=~/^borrowers$/ && $field=~/^streettype$/;
816 my $replacedby = defined ($val) ?
$val : '';
818 and not $replacedby =~ m
|0000-00-00|
819 and not $replacedby =~ m
|9999-12-31|
820 and $replacedby =~ m
|^\d
{4}-\d
{2}-\d
{2}( \d
{2}:\d
{2}:\d
{2})?
$| )
822 # If the value is XXXX-YY-ZZ[ AA:BB:CC] we assume it is a date
823 my $dateonly = defined $1 ?
0 : 1; #$1 refers to the capture group wrapped in parentheses. In this case, that's the hours, minutes, seconds.
825 $replacedby = output_pref
({ dt
=> dt_from_string
( $replacedby ), dateonly
=> $dateonly });
827 warn "$replacedby seems to be a date but an error occurs on generating it ($@)" if $@
;
829 ($letter->{title
} ) and do {
830 $letter->{title
} =~ s/$replacetablefield/$replacedby/g;
831 $letter->{title
} =~ s/$replacefield/$replacedby/g;
833 ($letter->{content
}) and do {
834 $letter->{content
} =~ s/$replacetablefield/$replacedby/g;
835 $letter->{content
} =~ s/$replacefield/$replacedby/g;
839 if ($table eq 'borrowers' && $letter->{content
}) {
840 if ( my $attributes = GetBorrowerAttributes
($values->{borrowernumber
}) ) {
842 foreach (@
$attributes) {
843 my $code = $_->{code
};
844 my $val = $_->{value_description
} || $_->{value
};
845 $val =~ s/\p{P}(?=$)//g if $val;
846 next unless $val gt '';
848 push @
{ $attr{$code} }, $val;
850 while ( my ($code, $val_ar) = each %attr ) {
851 my $replacefield = "<<borrower-attribute:$code>>";
852 my $replacedby = join ',', @
$val_ar;
853 $letter->{content
} =~ s/$replacefield/$replacedby/g;
862 my $success = EnqueueLetter( { letter => $letter,
863 borrowernumber => '12', message_transport_type => 'email' } )
865 places a letter in the message_queue database table, which will
866 eventually get processed (sent) by the process_message_queue.pl
867 cronjob when it calls SendQueuedMessages.
869 return message_id on success
874 my $params = shift or return;
876 return unless exists $params->{'letter'};
877 # return unless exists $params->{'borrowernumber'};
878 return unless exists $params->{'message_transport_type'};
880 my $content = $params->{letter
}->{content
};
881 $content =~ s/\s+//g if(defined $content);
882 if ( not defined $content or $content eq '' ) {
883 warn "Trying to add an empty message to the message queue" if $debug;
887 # If we have any attachments we should encode then into the body.
888 if ( $params->{'attachments'} ) {
889 $params->{'letter'} = _add_attachments
(
890 { letter
=> $params->{'letter'},
891 attachments
=> $params->{'attachments'},
892 message
=> MIME
::Lite
->new( Type
=> 'multipart/mixed' ),
897 my $dbh = C4
::Context
->dbh();
898 my $statement = << 'ENDSQL';
899 INSERT INTO message_queue
900 ( borrowernumber
, subject
, content
, metadata
, letter_code
, message_transport_type
, status
, time_queued
, to_address
, from_address
, content_type
)
902 ( ?
, ?
, ?
, ?
, ?
, ?
, ?
, NOW
(), ?
, ?
, ?
)
905 my $sth = $dbh->prepare($statement);
906 my $result = $sth->execute(
907 $params->{'borrowernumber'}, # borrowernumber
908 $params->{'letter'}->{'title'}, # subject
909 $params->{'letter'}->{'content'}, # content
910 $params->{'letter'}->{'metadata'} || '', # metadata
911 $params->{'letter'}->{'code'} || '', # letter_code
912 $params->{'message_transport_type'}, # message_transport_type
914 $params->{'to_address'}, # to_address
915 $params->{'from_address'}, # from_address
916 $params->{'letter'}->{'content-type'}, # content_type
918 return $dbh->last_insert_id(undef,undef,'message_queue', undef);
921 =head2 SendQueuedMessages ([$hashref])
923 my $sent = SendQueuedMessages( { verbose => 1 } );
925 sends all of the 'pending' items in the message queue.
927 returns number of messages sent.
931 sub SendQueuedMessages
{
934 my $unsent_messages = _get_unsent_messages
();
935 MESSAGE
: foreach my $message ( @
$unsent_messages ) {
936 # warn Data::Dumper->Dump( [ $message ], [ 'message' ] );
937 warn sprintf( 'sending %s message to patron: %s',
938 $message->{'message_transport_type'},
939 $message->{'borrowernumber'} || 'Admin' )
940 if $params->{'verbose'} or $debug;
941 # This is just begging for subclassing
942 next MESSAGE
if ( lc($message->{'message_transport_type'}) eq 'rss' );
943 if ( lc( $message->{'message_transport_type'} ) eq 'email' ) {
944 _send_message_by_email
( $message, $params->{'username'}, $params->{'password'}, $params->{'method'} );
946 elsif ( lc( $message->{'message_transport_type'} ) eq 'sms' ) {
947 _send_message_by_sms
( $message );
950 return scalar( @
$unsent_messages );
953 =head2 GetRSSMessages
955 my $message_list = GetRSSMessages( { limit => 10, borrowernumber => '14' } )
957 returns a listref of all queued RSS messages for a particular person.
964 return unless $params;
965 return unless ref $params;
966 return unless $params->{'borrowernumber'};
968 return _get_unsent_messages
( { message_transport_type
=> 'rss',
969 limit
=> $params->{'limit'},
970 borrowernumber
=> $params->{'borrowernumber'}, } );
973 =head2 GetPrintMessages
975 my $message_list = GetPrintMessages( { borrowernumber => $borrowernumber } )
977 Returns a arrayref of all queued print messages (optionally, for a particular
982 sub GetPrintMessages
{
983 my $params = shift || {};
985 return _get_unsent_messages
( { message_transport_type
=> 'print',
986 borrowernumber
=> $params->{'borrowernumber'},
990 =head2 GetQueuedMessages ([$hashref])
992 my $messages = GetQueuedMessage( { borrowernumber => '123', limit => 20 } );
994 fetches messages out of the message queue.
997 list of hashes, each has represents a message in the message queue.
1001 sub GetQueuedMessages
{
1004 my $dbh = C4
::Context
->dbh();
1005 my $statement = << 'ENDSQL';
1006 SELECT message_id
, borrowernumber
, subject
, content
, message_transport_type
, status
, time_queued
1012 if ( exists $params->{'borrowernumber'} ) {
1013 push @whereclauses, ' borrowernumber = ? ';
1014 push @query_params, $params->{'borrowernumber'};
1017 if ( @whereclauses ) {
1018 $statement .= ' WHERE ' . join( 'AND', @whereclauses );
1021 if ( defined $params->{'limit'} ) {
1022 $statement .= ' LIMIT ? ';
1023 push @query_params, $params->{'limit'};
1026 my $sth = $dbh->prepare( $statement );
1027 my $result = $sth->execute( @query_params );
1028 return $sth->fetchall_arrayref({});
1031 =head2 GetMessageTransportTypes
1033 my @mtt = GetMessageTransportTypes();
1035 returns an arrayref of transport types
1039 sub GetMessageTransportTypes
{
1040 my $dbh = C4
::Context
->dbh();
1041 my $mtts = $dbh->selectcol_arrayref("
1042 SELECT message_transport_type
1043 FROM message_transport_types
1044 ORDER BY message_transport_type
1049 =head2 _add_attachements
1052 letter - the standard letter hashref
1053 attachments - listref of attachments. each attachment is a hashref of:
1054 type - the mime type, like 'text/plain'
1055 content - the actual attachment
1056 filename - the name of the attachment.
1057 message - a MIME::Lite object to attach these to.
1059 returns your letter object, with the content updated.
1063 sub _add_attachments
{
1066 my $letter = $params->{'letter'};
1067 my $attachments = $params->{'attachments'};
1068 return $letter unless @
$attachments;
1069 my $message = $params->{'message'};
1071 # First, we have to put the body in as the first attachment
1073 Type
=> $letter->{'content-type'} || 'TEXT',
1074 Data
=> $letter->{'is_html'}
1075 ? _wrap_html
($letter->{'content'}, $letter->{'title'})
1076 : $letter->{'content'},
1079 foreach my $attachment ( @
$attachments ) {
1081 Type
=> $attachment->{'type'},
1082 Data
=> $attachment->{'content'},
1083 Filename
=> $attachment->{'filename'},
1086 # we're forcing list context here to get the header, not the count back from grep.
1087 ( $letter->{'content-type'} ) = grep( /^Content-Type:/, split( /\n/, $params->{'message'}->header_as_string ) );
1088 $letter->{'content-type'} =~ s/^Content-Type:\s+//;
1089 $letter->{'content'} = $message->body_as_string;
1095 sub _get_unsent_messages
{
1098 my $dbh = C4
::Context
->dbh();
1099 my $statement = << 'ENDSQL';
1100 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
1101 FROM message_queue mq
1102 LEFT JOIN borrowers b ON b
.borrowernumber
= mq
.borrowernumber
1106 my @query_params = ('pending');
1107 if ( ref $params ) {
1108 if ( $params->{'message_transport_type'} ) {
1109 $statement .= ' AND message_transport_type = ? ';
1110 push @query_params, $params->{'message_transport_type'};
1112 if ( $params->{'borrowernumber'} ) {
1113 $statement .= ' AND borrowernumber = ? ';
1114 push @query_params, $params->{'borrowernumber'};
1116 if ( $params->{'limit'} ) {
1117 $statement .= ' limit ? ';
1118 push @query_params, $params->{'limit'};
1122 $debug and warn "_get_unsent_messages SQL: $statement";
1123 $debug and warn "_get_unsent_messages params: " . join(',',@query_params);
1124 my $sth = $dbh->prepare( $statement );
1125 my $result = $sth->execute( @query_params );
1126 return $sth->fetchall_arrayref({});
1129 sub _send_message_by_email
{
1130 my $message = shift or return;
1131 my ($username, $password, $method) = @_;
1133 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
1134 my $to_address = $message->{'to_address'};
1135 unless ($to_address) {
1137 warn "FAIL: No 'to_address' and INVALID borrowernumber ($message->{borrowernumber})";
1138 _set_message_status
( { message_id
=> $message->{'message_id'},
1139 status
=> 'failed' } );
1142 $to_address = C4
::Members
::GetNoticeEmailAddress
( $message->{'borrowernumber'} );
1143 unless ($to_address) {
1144 # warn "FAIL: No 'to_address' and no email for " . ($member->{surname} ||'') . ", borrowernumber ($message->{borrowernumber})";
1145 # warning too verbose for this more common case?
1146 _set_message_status
( { message_id
=> $message->{'message_id'},
1147 status
=> 'failed' } );
1152 my $utf8 = decode
('MIME-Header', $message->{'subject'} );
1153 $message->{subject
}= encode
('MIME-Header', $utf8);
1154 my $subject = encode
('UTF-8', $message->{'subject'});
1155 my $content = encode
('UTF-8', $message->{'content'});
1156 my $content_type = $message->{'content_type'} || 'text/plain; charset="UTF-8"';
1157 my $is_html = $content_type =~ m/html/io;
1158 my $branch_email = undef;
1159 my $branch_replyto = undef;
1160 my $branch_returnpath = undef;
1162 my $branchdetail = GetBranchDetail
( $member->{'branchcode'} );
1163 $branch_email = $branchdetail->{'branchemail'};
1164 $branch_replyto = $branchdetail->{'branchreplyto'};
1165 $branch_returnpath = $branchdetail->{'branchreturnpath'};
1167 my $email = Koha
::Email
->new();
1168 my %sendmail_params = $email->create_message_headers(
1171 from
=> $message->{'from_address'} || $branch_email,
1172 replyto
=> $branch_replyto,
1173 sender
=> $branch_returnpath,
1174 subject
=> $subject,
1175 message
=> $is_html ? _wrap_html
( $content, $subject ) : $content,
1176 contenttype
=> $content_type
1180 $sendmail_params{'Auth'} = {user
=> $username, pass
=> $password, method
=> $method} if $username;
1181 if ( my $bcc = C4
::Context
->preference('OverdueNoticeBcc') ) {
1182 $sendmail_params{ Bcc
} = $bcc;
1185 _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
1186 if ( sendmail
( %sendmail_params ) ) {
1187 _set_message_status
( { message_id
=> $message->{'message_id'},
1188 status
=> 'sent' } );
1191 _set_message_status
( { message_id
=> $message->{'message_id'},
1192 status
=> 'failed' } );
1193 carp
$Mail::Sendmail
::error
;
1199 my ($content, $title) = @_;
1201 my $css = C4
::Context
->preference("NoticeCSS") || '';
1202 $css = qq{<link rel
="stylesheet" type
="text/css" href
="$css">} if $css;
1204 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
1205 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1206 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
1208 <title>$title</title>
1209 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1220 my ( $message ) = @_;
1221 my $dbh = C4
::Context
->dbh;
1222 my $count = $dbh->selectrow_array(q
|
1225 WHERE message_transport_type
= ?
1226 AND borrowernumber
= ?
1228 AND CAST
(time_queued AS date
) = CAST
(NOW
() AS date
)
1231 |, {}, $message->{message_transport_type
}, $message->{borrowernumber
}, $message->{letter_code
}, $message->{content
} );
1235 sub _send_message_by_sms
{
1236 my $message = shift or return;
1237 my $member = C4
::Members
::GetMember
( 'borrowernumber' => $message->{'borrowernumber'} );
1239 unless ( $member->{smsalertnumber
} ) {
1240 _set_message_status
( { message_id
=> $message->{'message_id'},
1241 status
=> 'failed' } );
1245 if ( _is_duplicate
( $message ) ) {
1246 _set_message_status
( { message_id
=> $message->{'message_id'},
1247 status
=> 'failed' } );
1251 my $success = C4
::SMS
->send_sms( { destination
=> $member->{'smsalertnumber'},
1252 message
=> $message->{'content'},
1254 _set_message_status
( { message_id
=> $message->{'message_id'},
1255 status
=> ($success ?
'sent' : 'failed') } );
1259 sub _update_message_to_address
{
1261 my $dbh = C4
::Context
->dbh();
1262 $dbh->do('UPDATE message_queue SET to_address=? WHERE message_id=?',undef,($to,$id));
1265 sub _set_message_status
{
1266 my $params = shift or return;
1268 foreach my $required_parameter ( qw( message_id status ) ) {
1269 return unless exists $params->{ $required_parameter };
1272 my $dbh = C4
::Context
->dbh();
1273 my $statement = 'UPDATE message_queue SET status= ? WHERE message_id = ?';
1274 my $sth = $dbh->prepare( $statement );
1275 my $result = $sth->execute( $params->{'status'},
1276 $params->{'message_id'} );