4 use vars qw ( @ISA @EXPORT_OK $DEBUG );
8 use IPC::Run qw( run timeout ); # for _pslatex
9 use IPC::Run3; # for do_print... should just use IPC::Run i guess
13 #do NOT depend on any FS:: modules here, causes weird (sometimes unreproducable
14 #until on client machine) dependancy loops. put them in FS::Misc::Something
17 @ISA = qw( Exporter );
18 @EXPORT_OK = qw( send_email generate_email send_fax
19 states_hash counties cities state_label
22 generate_ps generate_pdf do_print
31 FS::Misc - Miscellaneous subroutines
35 use FS::Misc qw(send_email);
41 Miscellaneous subroutines. This module contains miscellaneous subroutines
42 called from multiple other modules. These are not OO or necessarily related,
43 but are collected here to eliminate code duplication.
49 =item send_email OPTION => VALUE ...
61 (required) comma-separated scalar or arrayref of recipients
69 (optional) MIME type for the body
73 (required unless I<nobody> is true) arrayref of body text lines
77 (optional, but required if I<nobody> is true) arrayref of MIME::Entity->build PARAMHASH refs or MIME::Entity objects. These will be passed as arguments to MIME::Entity->attach().
81 (optional) when set true, send_email will ignore the I<body> option and simply construct a message with the given I<mimeparts>. In this case,
82 I<content-type>, if specified, overrides the default "multipart/mixed" for the outermost MIME container.
84 =item content-encoding
86 (optional) when using nobody, optional top-level MIME
87 encoding which, if specified, overrides the default "7bit".
91 (optional) type parameter for multipart/related messages
95 (optional) L<FS::cust_main> key; if passed, the message will be logged
96 (if logging is enabled) with this custnum.
100 (optional) L<FS::msg_template> key, for logging.
106 use vars qw( $conf );
109 use Email::Sender::Simple qw(sendmail);
110 use Email::Sender::Transport::SMTP;
111 use Email::Sender::Transport::SMTP::TLS 0.11;
114 FS::UID->install_callback( sub {
115 $conf = new FS::Conf;
121 my %doptions = %options;
122 $doptions{'body'} = '(full body not shown in debug)';
123 warn "FS::Misc::send_email called with options:\n ". Dumper(\%doptions);
124 # join("\n", map { " $_: ". $options{$_} } keys %options ). "\n"
127 my @to = ref($options{to}) ? @{ $options{to} } : ( $options{to} );
131 if ( $options{'nobody'} ) {
133 croak "'mimeparts' option required when 'nobody' option given\n"
134 unless $options{'mimeparts'};
136 @mimeparts = @{$options{'mimeparts'}};
139 'Type' => ( $options{'content-type'} || 'multipart/mixed' ),
140 'Encoding' => ( $options{'content-encoding'} || '7bit' ),
145 @mimeparts = @{$options{'mimeparts'}}
146 if ref($options{'mimeparts'}) eq 'ARRAY';
148 if (scalar(@mimeparts)) {
151 'Type' => 'multipart/mixed',
152 'Encoding' => '7bit',
155 unshift @mimeparts, {
156 'Type' => ( $options{'content-type'} || 'text/plain' ),
157 'Data' => $options{'body'},
158 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
159 'Disposition' => 'inline',
165 'Type' => ( $options{'content-type'} || 'text/plain' ),
166 'Data' => $options{'body'},
167 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
175 if ( $options{'from'} =~ /\@([\w\.\-]+)/ ) {
178 warn 'no domain found in invoice from address '. $options{'from'}.
179 '; constructing Message-ID (and saying HELO) @example.com';
180 $domain = 'example.com';
182 my $message_id = join('.', rand()*(2**32), $$, time). "\@$domain";
185 my $message = MIME::Entity->build(
186 'From' => $options{'from'},
187 'To' => join(', ', @to),
188 'Sender' => $options{'from'},
189 'Reply-To' => $options{'from'},
190 'Date' => time2str("%a, %d %b %Y %X %z", $time),
191 'Subject' => Encode::encode('MIME-Header', $options{'subject'}),
192 'Message-ID' => "<$message_id>",
196 if ( $options{'type'} ) {
197 #false laziness w/cust_bill::generate_email
198 $message->head->replace('Content-type',
200 '; boundary="'. $message->head->multipart_boundary. '"'.
201 '; type='. $options{'type'}
205 foreach my $part (@mimeparts) {
207 if ( UNIVERSAL::isa($part, 'MIME::Entity') ) {
209 warn "attaching MIME part from MIME::Entity object\n"
211 $message->add_part($part);
213 } elsif ( ref($part) eq 'HASH' ) {
215 warn "attaching MIME part from hashref:\n".
216 join("\n", map " $_: ".$part->{$_}, keys %$part ). "\n"
218 $message->attach(%$part);
221 croak "mimepart $part isn't a hashref or MIME::Entity object!";
228 my %smtp_opt = ( 'host' => $conf->config('smtpmachine'),
232 my($port, $enc) = split('-', ($conf->config('smtp-encryption') || '25') );
233 $smtp_opt{'port'} = $port;
236 if ( defined($enc) && $enc eq 'starttls' ) {
237 $smtp_opt{$_} = $conf->config("smtp-$_") for qw(username password);
238 $transport = Email::Sender::Transport::SMTP::TLS->new( %smtp_opt );
240 if ( $conf->exists('smtp-username') && $conf->exists('smtp-password') ) {
241 $smtp_opt{"sasl_$_"} = $conf->config("smtp-$_") for qw(username password);
243 $smtp_opt{'ssl'} = 1 if defined($enc) && $enc eq 'tls';
244 $transport = Email::Sender::Transport::SMTP->new( %smtp_opt );
247 push @to, $options{bcc} if defined($options{bcc});
248 local $@; # just in case
249 eval { sendmail($message, { transport => $transport,
250 from => $options{from},
254 if(ref($@) and $@->isa('Email::Sender::Failure')) {
255 $error = $@->code.' ' if $@->code;
256 $error .= $@->message;
263 if ( $conf->exists('log_sent_mail') and $options{'custnum'} ) {
264 my $cust_msg = FS::cust_msg->new({
265 'env_from' => $options{'from'},
266 'env_to' => join(', ', @to),
267 'header' => $message->header_as_string,
268 'body' => $message->body_as_string,
271 'custnum' => $options{'custnum'},
272 'msgnum' => $options{'msgnum'},
273 'status' => ($error ? 'failed' : 'sent'),
275 $cust_msg->insert; # ignore errors
280 =item generate_email OPTION => VALUE ...
288 Sender address, required
292 Recipient address, required
296 Blind copy address, optional
300 email subject, required
304 Email body (HTML alternative). Arrayref of lines, or scalar.
306 Will be placed inside an HTML <BODY> tag.
310 Email body (Text alternative). Arrayref of lines, or scalar.
312 =item custnum, msgnum (optional)
314 Customer and template numbers, passed through to send_email for logging.
318 Constructs a multipart message from text_body and html_body.
322 #false laziness w/FS::cust_bill::generate_email
330 my $me = '[FS::Misc::generate_email]';
332 my @fields = qw(from to bcc subject custnum msgnum);
334 @return{@fields} = @args{@fields};
336 warn "$me creating HTML/text multipart message"
339 $return{'nobody'} = 1;
341 my $alternative = build MIME::Entity
342 'Type' => 'multipart/alternative',
343 'Encoding' => '7bit',
344 'Disposition' => 'inline'
348 if ( ref($args{'text_body'}) eq 'ARRAY' ) {
349 $data = join("\n", @{ $args{'text_body'} });
351 $data = $args{'text_body'};
354 $alternative->attach(
355 'Type' => 'text/plain',
356 'Encoding' => 'quoted-printable',
357 #'Encoding' => '7bit',
359 'Disposition' => 'inline',
363 if ( ref($args{'html_body'}) eq 'ARRAY' ) {
364 @html_data = @{ $args{'html_body'} };
366 @html_data = split(/\n/, $args{'html_body'});
369 $alternative->attach(
370 'Type' => 'text/html',
371 'Encoding' => 'quoted-printable',
372 'Data' => [ '<html>',
375 ' '. encode_entities($return{'subject'}),
378 ' <body bgcolor="#ffffff">',
383 'Disposition' => 'inline',
384 #'Filename' => 'invoice.pdf',
387 #no other attachment:
389 # multipart/alternative
393 $return{'content-type'} = 'multipart/related';
394 $return{'mimeparts'} = [ $alternative ];
395 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
396 #$return{'disposition'} = 'inline';
402 =item process_send_email OPTION => VALUE ...
404 Takes arguments as per generate_email() and sends the message. This
405 will die on any error and can be used in the job queue.
409 sub process_send_email {
411 my $error = send_email(generate_email(%message));
412 die "$error\n" if $error;
416 =item send_fax OPTION => VALUE ...
420 I<dialstring> - (required) 10-digit phone number w/ area code
422 I<docdata> - (required) Array ref containing PostScript or TIFF Class F document
426 I<docfile> - (required) Filename of PostScript TIFF Class F document
428 ...any other options will be passed to L<Fax::Hylafax::Client::sendfax>
437 die 'HylaFAX support has not been configured.'
438 unless $conf->exists('hylafax');
441 require Fax::Hylafax::Client;
445 if ($@ =~ /^Can't locate Fax.*/) {
446 die "You must have Fax::Hylafax::Client installed to use invoice faxing."
452 my %hylafax_opts = map { split /\s+/ } $conf->config('hylafax');
454 die 'Called send_fax without a \'dialstring\'.'
455 unless exists($options{'dialstring'});
457 if (exists($options{'docdata'}) and ref($options{'docdata'}) eq 'ARRAY') {
458 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
459 my $fh = new File::Temp(
460 TEMPLATE => 'faxdoc.'. $options{'dialstring'} . '.XXXXXXXX',
463 ) or die "can't open temp file: $!\n";
465 $options{docfile} = $fh->filename;
467 print $fh @{$options{'docdata'}};
470 delete $options{'docdata'};
473 die 'Called send_fax without a \'docfile\' or \'docdata\'.'
474 unless exists($options{'docfile'});
476 #FIXME: Need to send canonical dialstring to HylaFAX, but this only
479 $options{'dialstring'} =~ s/[^\d\+]//g;
480 if ($options{'dialstring'} =~ /^\d{10}$/) {
481 $options{dialstring} = '+1' . $options{'dialstring'};
483 return 'Invalid dialstring ' . $options{'dialstring'} . '.';
486 my $faxjob = &Fax::Hylafax::Client::sendfax(%options, %hylafax_opts);
488 if ($faxjob->success) {
489 warn "Successfully queued fax to '$options{dialstring}' with jobid " .
494 return 'Error while sending FAX: ' . $faxjob->trace;
499 =item states_hash COUNTRY
501 Returns a list of key/value pairs containing state (or other sub-country
502 division) abbriviations and names.
506 use FS::Record qw(qsearch);
507 use Locale::SubCountry;
514 map { s/[\n\r]//g; $_; }
518 'table' => 'cust_main_county',
519 'hashref' => { 'country' => $country },
520 'extra_sql' => 'GROUP BY state',
523 #it could throw a fatal "Invalid country code" error (for example "AX")
524 my $subcountry = eval { new Locale::SubCountry($country) }
525 or return ( '', '(n/a)' );
527 #"i see your schwartz is as big as mine!"
528 map { ( $_->[0] => $_->[1] ) }
529 sort { $a->[1] cmp $b->[1] }
530 map { [ $_ => state_label($_, $subcountry) ] }
534 =item counties STATE COUNTRY
536 Returns a list of counties for this state and country.
541 my( $state, $country ) = @_;
543 map { $_ } #return num_counties($state, $country) unless wantarray;
544 sort map { s/[\n\r]//g; $_; }
547 'select' => 'DISTINCT county',
548 'table' => 'cust_main_county',
549 'hashref' => { 'state' => $state,
550 'country' => $country,
555 =item cities COUNTY STATE COUNTRY
557 Returns a list of cities for this county, state and country.
562 my( $county, $state, $country ) = @_;
564 map { $_ } #return num_cities($county, $state, $country) unless wantarray;
565 sort map { s/[\n\r]//g; $_; }
568 'select' => 'DISTINCT city',
569 'table' => 'cust_main_county',
570 'hashref' => { 'county' => $county,
572 'country' => $country,
577 =item state_label STATE COUNTRY_OR_LOCALE_SUBCOUNRY_OBJECT
582 my( $state, $country ) = @_;
584 unless ( ref($country) ) {
585 $country = eval { new Locale::SubCountry($country) }
590 # US kludge to avoid changing existing behaviour
591 # also we actually *use* the abbriviations...
592 my $full_name = $country->country_code eq 'US'
594 : $country->full_name($state);
596 $full_name = '' if $full_name eq 'unknown';
597 $full_name =~ s/\(see also.*\)\s*$//;
598 $full_name .= " ($state)" if $full_name;
600 $full_name || $state || '(n/a)';
606 Returns a hash reference of the accepted credit card types. Keys are shorter
607 identifiers and values are the longer strings used by the system (see
608 L<Business::CreditCard>).
615 my $conf = new FS::Conf;
618 #displayname #value (Business::CreditCard)
619 "VISA" => "VISA card",
620 "MasterCard" => "MasterCard",
621 "Discover" => "Discover card",
622 "American Express" => "American Express card",
623 "Diner's Club/Carte Blanche" => "Diner's Club/Carte Blanche",
624 "enRoute" => "enRoute",
626 "BankCard" => "BankCard",
627 "Switch" => "Switch",
630 my @conf_card_types = grep { ! /^\s*$/ } $conf->config('card-types');
631 if ( @conf_card_types ) {
632 #perhaps the hash is backwards for this, but this way works better for
633 #usage in selfservice
634 %card_types = map { $_ => $card_types{$_} }
637 grep { $card_types{$d} eq $_ } @conf_card_types
647 Returns a hash reference of allowed package billing frequencies.
652 tie my %freq, 'Tie::IxHash', (
653 '0' => '(no recurring fee)',
656 '2d' => 'every two days',
657 '3d' => 'every three days',
659 '2w' => 'biweekly (every 2 weeks)',
661 '45d' => 'every 45 days',
662 '2' => 'bimonthly (every 2 months)',
663 '3' => 'quarterly (every 3 months)',
664 '4' => 'every 4 months',
665 '137d' => 'every 4 1/2 months (137 days)',
666 '6' => 'semiannually (every 6 months)',
668 '13' => 'every 13 months (annually +1 month)',
669 '24' => 'biannually (every 2 years)',
670 '36' => 'triannually (every 3 years)',
671 '48' => '(every 4 years)',
672 '60' => '(every 5 years)',
673 '120' => '(every 10 years)',
678 =item generate_ps FILENAME
680 Returns an postscript rendition of the LaTex file, as a scalar.
681 FILENAME does not contain the .tex suffix and is unlinked by this function.
685 use String::ShellQuote;
690 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
695 system('dvips', '-q', '-t', 'letter', "$file.dvi", '-o', "$file.ps" ) == 0
696 or die "dvips failed";
698 open(POSTSCRIPT, "<$file.ps")
699 or die "can't open $file.ps: $! (error in LaTeX template?)\n";
701 unlink("$file.dvi", "$file.log", "$file.aux", "$file.ps", "$file.tex")
702 unless $FS::CurrentUser::CurrentUser->option('save_tmp_typesetting');
706 if ( $conf->exists('lpr-postscript_prefix') ) {
707 my $prefix = $conf->config('lpr-postscript_prefix');
708 $ps .= eval qq("$prefix");
711 while (<POSTSCRIPT>) {
717 if ( $conf->exists('lpr-postscript_suffix') ) {
718 my $suffix = $conf->config('lpr-postscript_suffix');
719 $ps .= eval qq("$suffix");
726 =item generate_pdf FILENAME
728 Returns an PDF rendition of the LaTex file, as a scalar. FILENAME does not
729 contain the .tex suffix and is unlinked by this function.
733 use String::ShellQuote;
738 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
741 #system('pdflatex', "$file.tex");
742 #system('pdflatex', "$file.tex");
743 #! LaTeX Error: Unknown graphics extension: .eps.
747 my $sfile = shell_quote $file;
749 #system('dvipdf', "$file.dvi", "$file.pdf" );
751 "dvips -q -t letter -f $sfile.dvi ".
752 "| gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$sfile.pdf ".
755 or die "dvips | gs failed: $!";
757 open(PDF, "<$file.pdf")
758 or die "can't open $file.pdf: $! (error in LaTeX template?)\n";
760 unlink("$file.dvi", "$file.log", "$file.aux", "$file.pdf", "$file.tex")
761 unless $FS::CurrentUser::CurrentUser->option('save_tmp_typesetting');
777 #my $sfile = shell_quote $file;
781 '-interaction=batchmode',
782 '\AtBeginDocument{\RequirePackage{pslatex}}',
783 '\def\PSLATEXTMP{\futurelet\PSLATEXTMP\PSLATEXTMPB}',
784 '\def\PSLATEXTMPB{\ifx\PSLATEXTMP\nonstopmode\else\input\fi}',
789 my $timeout = 30; #? should be more than enough
793 local($SIG{CHLD}) = sub {};
794 run( \@cmd, '>'=>'/dev/null', '2>'=>'/dev/null', timeout($timeout) )
795 or warn "bad exit status from pslatex pass $_\n";
799 return if -e "$file.dvi" && -s "$file.dvi";
800 die "pslatex $file.tex failed; see $file.log for details?\n";
804 =item do_print ARRAYREF [, OPTION => VALUE ... ]
806 Sends the lines in ARRAYREF to the printer.
808 Options available are:
814 Uses this agent's 'lpr' configuration setting override instead of the global
819 Uses this command instead of the configured lpr command (overrides both the
820 global value and agentnum).
825 my( $data, %opt ) = @_;
827 my $lpr = ( exists($opt{'lpr'}) && $opt{'lpr'} )
829 : $conf->config('lpr', $opt{'agentnum'} );
832 run3 $lpr, $data, \$outerr, \$outerr;
834 $outerr = ": $outerr" if length($outerr);
835 die "Error from $lpr (exit status ". ($?>>8). ")$outerr\n";
840 =item csv_from_fixed, FILEREF COUNTREF, [ LENGTH_LISTREF, [ CALLBACKS_LISTREF ] ]
842 Converts the filehandle referenced by FILEREF from fixed length record
843 lines to a CSV file according to the lengths specified in LENGTH_LISTREF.
844 The CALLBACKS_LISTREF refers to a correpsonding list of coderefs. Each
845 should return the value to be substituted in place of its single argument.
847 Returns false on success or an error if one occurs.
852 my( $fhref, $countref, $lengths, $callbacks) = @_;
854 eval { require Text::CSV_XS; };
858 my $unpacker = new Text::CSV_XS;
860 my $template = join('', map {$total += $_; "A$_"} @$lengths) if $lengths;
862 my $dir = "%%%FREESIDE_CACHE%%%/cache.$FS::UID::datasrc";
863 my $fh = new File::Temp( TEMPLATE => "FILE.csv.XXXXXXXX",
866 ) or return "can't open temp file: $!\n"
869 while ( defined(my $line=<$ofh>) ) {
875 return "unexpected input at line $$countref: $line".
876 " -- expected $total but received ". length($line)
877 unless length($line) == $total;
879 $unpacker->combine( map { my $i = $column++;
880 defined( $callbacks->[$i] )
881 ? &{ $callbacks->[$i] }( $_ )
883 } unpack( $template, $line )
885 or return "invalid data for CSV: ". $unpacker->error_input;
887 print $fh $unpacker->string(), "\n"
888 or return "can't write temp file: $!\n";
892 if ( $template ) { close $$fhref; $$fhref = $fh }
898 =item ocr_image IMAGE_SCALAR
900 Runs OCR on the provided image data and returns a list of text lines.
905 my $logo_data = shift;
907 #XXX use conf dir location from Makefile
908 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
909 my $fh = new File::Temp(
910 TEMPLATE => 'bizcard.XXXXXXXX',
911 SUFFIX => '.png', #XXX assuming, but should handle jpg, gif, etc. too
914 ) or die "can't open temp file: $!\n";
916 my $filename = $fh->filename;
918 print $fh $logo_data;
921 run( [qw(ocroscript recognize), $filename], '>'=>"$filename.hocr" )
922 or die "ocroscript recognize failed\n";
924 run( [qw(ocroscript hocr-to-text), "$filename.hocr"], '>pipe'=>\*OUT )
925 or die "ocroscript hocr-to-text failed\n";
927 my @lines = split(/\n/, <OUT> );
929 foreach (@lines) { s/\.c0m\s*$/.com/; }
942 L<FS::UID>, L<FS::CGI>, L<FS::Record>, the base documentation.
944 L<Fax::Hylafax::Client>