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
33 FS::Misc - Miscellaneous subroutines
37 use FS::Misc qw(send_email);
43 Miscellaneous subroutines. This module contains miscellaneous subroutines
44 called from multiple other modules. These are not OO or necessarily related,
45 but are collected here to eliminate code duplication.
51 =item send_email OPTION => VALUE ...
63 (required) comma-separated scalar or arrayref of recipients
71 (optional) MIME type for the body
75 (required unless I<nobody> is true) arrayref of body text lines
79 (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().
83 (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,
84 I<content-type>, if specified, overrides the default "multipart/mixed" for the outermost MIME container.
86 =item content-encoding
88 (optional) when using nobody, optional top-level MIME
89 encoding which, if specified, overrides the default "7bit".
93 (optional) type parameter for multipart/related messages
97 (optional) L<FS::cust_main> key; if passed, the message will be logged
98 (if logging is enabled) with this custnum.
102 (optional) L<FS::msg_template> key, for logging.
108 use vars qw( $conf );
111 use Email::Sender::Simple qw(sendmail);
112 use Email::Sender::Transport::SMTP;
113 use Email::Sender::Transport::SMTP::TLS 0.11;
116 FS::UID->install_callback( sub {
117 $conf = new FS::Conf;
123 my %doptions = %options;
124 $doptions{'body'} = '(full body not shown in debug)';
125 warn "FS::Misc::send_email called with options:\n ". Dumper(\%doptions);
126 # join("\n", map { " $_: ". $options{$_} } keys %options ). "\n"
129 my @to = ref($options{to}) ? @{ $options{to} } : ( $options{to} );
133 if ( $options{'nobody'} ) {
135 croak "'mimeparts' option required when 'nobody' option given\n"
136 unless $options{'mimeparts'};
138 @mimeparts = @{$options{'mimeparts'}};
141 'Type' => ( $options{'content-type'} || 'multipart/mixed' ),
142 'Encoding' => ( $options{'content-encoding'} || '7bit' ),
147 @mimeparts = @{$options{'mimeparts'}}
148 if ref($options{'mimeparts'}) eq 'ARRAY';
150 if (scalar(@mimeparts)) {
153 'Type' => 'multipart/mixed',
154 'Encoding' => '7bit',
157 unshift @mimeparts, {
158 'Type' => ( $options{'content-type'} || 'text/plain' ),
159 'Charset' => 'UTF-8',
160 'Data' => $options{'body'},
161 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
162 'Disposition' => 'inline',
168 'Type' => ( $options{'content-type'} || 'text/plain' ),
169 'Data' => $options{'body'},
170 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
171 'Charset' => 'UTF-8',
178 my $from = $options{from};
179 $from =~ s/^\s*//; $from =~ s/\s*$//;
180 if ( $from =~ /^(.*)\s*<(.*@.*)>$/ ) {
186 if ( $from =~ /\@([\w\.\-]+)/ ) {
189 warn 'no domain found in invoice from address '. $options{'from'}.
190 '; constructing Message-ID (and saying HELO) @example.com';
191 $domain = 'example.com';
193 my $message_id = join('.', rand()*(2**32), $$, time). "\@$domain";
196 my $message = MIME::Entity->build(
197 'From' => $options{'from'},
198 'To' => join(', ', @to),
199 'Sender' => $options{'from'},
200 'Reply-To' => $options{'from'},
201 'Date' => time2str("%a, %d %b %Y %X %z", $time),
202 'Subject' => Encode::encode('MIME-Header', $options{'subject'}),
203 'Message-ID' => "<$message_id>",
207 if ( $options{'type'} ) {
208 #false laziness w/cust_bill::generate_email
209 $message->head->replace('Content-type',
211 '; boundary="'. $message->head->multipart_boundary. '"'.
212 '; type='. $options{'type'}
216 foreach my $part (@mimeparts) {
218 if ( UNIVERSAL::isa($part, 'MIME::Entity') ) {
220 warn "attaching MIME part from MIME::Entity object\n"
222 $message->add_part($part);
224 } elsif ( ref($part) eq 'HASH' ) {
226 warn "attaching MIME part from hashref:\n".
227 join("\n", map " $_: ".$part->{$_}, keys %$part ). "\n"
229 $message->attach(%$part);
232 croak "mimepart $part isn't a hashref or MIME::Entity object!";
239 my %smtp_opt = ( 'host' => $conf->config('smtpmachine'),
243 my($port, $enc) = split('-', ($conf->config('smtp-encryption') || '25') );
244 $smtp_opt{'port'} = $port;
247 if ( defined($enc) && $enc eq 'starttls' ) {
248 $smtp_opt{$_} = $conf->config("smtp-$_") for qw(username password);
249 $transport = Email::Sender::Transport::SMTP::TLS->new( %smtp_opt );
251 if ( $conf->exists('smtp-username') && $conf->exists('smtp-password') ) {
252 $smtp_opt{"sasl_$_"} = $conf->config("smtp-$_") for qw(username password);
254 $smtp_opt{'ssl'} = 1 if defined($enc) && $enc eq 'tls';
255 $transport = Email::Sender::Transport::SMTP->new( %smtp_opt );
258 push @to, $options{bcc} if defined($options{bcc});
259 local $@; # just in case
260 eval { sendmail($message, { transport => $transport,
265 if(ref($@) and $@->isa('Email::Sender::Failure')) {
266 $error = $@->code.' ' if $@->code;
267 $error .= $@->message;
274 if ( $conf->exists('log_sent_mail') ) {
275 my $cust_msg = FS::cust_msg->new({
276 'env_from' => $options{'from'},
277 'env_to' => join(', ', @to),
278 'header' => $message->header_as_string,
279 'body' => $message->body_as_string,
282 'custnum' => $options{'custnum'},
283 'msgnum' => $options{'msgnum'},
284 'status' => ($error ? 'failed' : 'sent'),
285 'msgtype' => $options{'msgtype'},
287 my $log_error = $cust_msg->insert;
288 warn "Error logging message: $log_error\n" if $log_error; # at least warn
294 =item generate_email OPTION => VALUE ...
302 Sender address, required
306 Recipient address, required
310 Blind copy address, optional
314 email subject, required
318 Email body (HTML alternative). Arrayref of lines, or scalar.
320 Will be placed inside an HTML <BODY> tag.
324 Email body (Text alternative). Arrayref of lines, or scalar.
326 =item custnum, msgnum (optional)
328 Customer and template numbers, passed through to send_email for logging.
332 Constructs a multipart message from text_body and html_body.
336 #false laziness w/FS::cust_bill::generate_email
344 my $me = '[FS::Misc::generate_email]';
346 my @fields = qw(from to bcc subject custnum msgnum msgtype);
348 @return{@fields} = @args{@fields};
350 warn "$me creating HTML/text multipart message"
353 $return{'nobody'} = 1;
355 my $alternative = build MIME::Entity
356 'Type' => 'multipart/alternative',
357 'Encoding' => '7bit',
358 'Disposition' => 'inline'
362 if ( ref($args{'text_body'}) eq 'ARRAY' ) {
363 $data = join("\n", @{ $args{'text_body'} });
365 $data = $args{'text_body'};
368 $alternative->attach(
369 'Type' => 'text/plain',
370 'Encoding' => 'quoted-printable',
371 'Charset' => 'UTF-8',
372 #'Encoding' => '7bit',
374 'Disposition' => 'inline',
378 if ( ref($args{'html_body'}) eq 'ARRAY' ) {
379 @html_data = @{ $args{'html_body'} };
381 @html_data = split(/\n/, $args{'html_body'});
384 $alternative->attach(
385 'Type' => 'text/html',
386 'Encoding' => 'quoted-printable',
387 'Data' => [ '<html>',
390 ' '. encode_entities($return{'subject'}),
393 ' <body bgcolor="#ffffff">',
398 'Disposition' => 'inline',
399 #'Filename' => 'invoice.pdf',
402 #no other attachment:
404 # multipart/alternative
408 $return{'content-type'} = 'multipart/related';
409 $return{'mimeparts'} = [ $alternative ];
410 $return{'type'} = 'multipart/alternative'; #Content-Type of first part...
411 #$return{'disposition'} = 'inline';
417 =item send_fax OPTION => VALUE ...
421 I<dialstring> - (required) 10-digit phone number w/ area code
423 I<docdata> - (required) Array ref containing PostScript or TIFF Class F document
427 I<docfile> - (required) Filename of PostScript TIFF Class F document
429 ...any other options will be passed to L<Fax::Hylafax::Client::sendfax>
438 die 'HylaFAX support has not been configured.'
439 unless $conf->exists('hylafax');
442 require Fax::Hylafax::Client;
446 if ($@ =~ /^Can't locate Fax.*/) {
447 die "You must have Fax::Hylafax::Client installed to use invoice faxing."
453 my %hylafax_opts = map { split /\s+/ } $conf->config('hylafax');
455 die 'Called send_fax without a \'dialstring\'.'
456 unless exists($options{'dialstring'});
458 if (exists($options{'docdata'}) and ref($options{'docdata'}) eq 'ARRAY') {
459 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
460 my $fh = new File::Temp(
461 TEMPLATE => 'faxdoc.'. $options{'dialstring'} . '.XXXXXXXX',
464 ) or die "can't open temp file: $!\n";
466 $options{docfile} = $fh->filename;
468 print $fh @{$options{'docdata'}};
471 delete $options{'docdata'};
474 die 'Called send_fax without a \'docfile\' or \'docdata\'.'
475 unless exists($options{'docfile'});
477 #FIXME: Need to send canonical dialstring to HylaFAX, but this only
480 $options{'dialstring'} =~ s/[^\d\+]//g;
481 if ($options{'dialstring'} =~ /^\d{10}$/) {
482 $options{dialstring} = '+1' . $options{'dialstring'};
484 return 'Invalid dialstring ' . $options{'dialstring'} . '.';
487 my $faxjob = &Fax::Hylafax::Client::sendfax(%options, %hylafax_opts);
489 if ($faxjob->success) {
490 warn "Successfully queued fax to '$options{dialstring}' with jobid " .
495 return 'Error while sending FAX: ' . $faxjob->trace;
500 =item states_hash COUNTRY
502 Returns a list of key/value pairs containing state (or other sub-country
503 division) abbriviations and names.
507 use FS::Record qw(qsearch);
508 use Locale::SubCountry;
515 map { s/[\n\r]//g; $_; }
519 'table' => 'cust_main_county',
520 'hashref' => { 'country' => $country },
521 'extra_sql' => 'GROUP BY state',
524 #it could throw a fatal "Invalid country code" error (for example "AX")
525 my $subcountry = eval { new Locale::SubCountry($country) }
526 or return (); # ( '', '(n/a)' );
528 #"i see your schwartz is as big as mine!"
529 map { ( $_->[0] => $_->[1] ) }
530 sort { $a->[1] cmp $b->[1] }
531 map { [ $_ => state_label($_, $subcountry) ] }
535 =item counties STATE COUNTRY
537 Returns a list of counties for this state and country.
542 my( $state, $country ) = @_;
544 map { $_ } #return num_counties($state, $country) unless wantarray;
545 sort map { s/[\n\r]//g; $_; }
548 'select' => 'DISTINCT county',
549 'table' => 'cust_main_county',
550 'hashref' => { 'state' => $state,
551 'country' => $country,
556 =item cities COUNTY STATE COUNTRY
558 Returns a list of cities for this county, state and country.
563 my( $county, $state, $country ) = @_;
565 map { $_ } #return num_cities($county, $state, $country) unless wantarray;
566 sort map { s/[\n\r]//g; $_; }
569 'select' => 'DISTINCT city',
570 'table' => 'cust_main_county',
571 'hashref' => { 'county' => $county,
573 'country' => $country,
578 =item state_label STATE COUNTRY_OR_LOCALE_SUBCOUNRY_OBJECT
583 my( $state, $country ) = @_;
585 unless ( ref($country) ) {
586 $country = eval { new Locale::SubCountry($country) }
591 # US kludge to avoid changing existing behaviour
592 # also we actually *use* the abbriviations...
593 my $full_name = $country->country_code eq 'US'
595 : $country->full_name($state);
597 $full_name = '' if $full_name eq 'unknown';
598 $full_name =~ s/\(see also.*\)\s*$//;
599 $full_name .= " ($state)" if $full_name;
601 $full_name || $state || '(n/a)';
607 Returns a hash reference of the accepted credit card types. Keys are shorter
608 identifiers and values are the longer strings used by the system (see
609 L<Business::CreditCard>).
616 my $conf = new FS::Conf;
619 #displayname #value (Business::CreditCard)
620 "VISA" => "VISA card",
621 "MasterCard" => "MasterCard",
622 "Discover" => "Discover card",
623 "American Express" => "American Express card",
624 "Diner's Club/Carte Blanche" => "Diner's Club/Carte Blanche",
625 "enRoute" => "enRoute",
627 "BankCard" => "BankCard",
628 "Switch" => "Switch",
631 my @conf_card_types = grep { ! /^\s*$/ } $conf->config('card-types');
632 if ( @conf_card_types ) {
633 #perhaps the hash is backwards for this, but this way works better for
634 #usage in selfservice
635 %card_types = map { $_ => $card_types{$_} }
638 grep { $card_types{$d} eq $_ } @conf_card_types
648 Returns a hash reference of allowed package billing frequencies.
653 tie my %freq, 'Tie::IxHash', (
654 '0' => '(no recurring fee)',
657 '2d' => 'every two days',
658 '3d' => 'every three days',
660 '2w' => 'biweekly (every 2 weeks)',
662 '45d' => 'every 45 days',
663 '2' => 'bimonthly (every 2 months)',
664 '3' => 'quarterly (every 3 months)',
665 '4' => 'every 4 months',
666 '137d' => 'every 4 1/2 months (137 days)',
667 '6' => 'semiannually (every 6 months)',
669 '13' => 'every 13 months (annually +1 month)',
670 '24' => 'biannually (every 2 years)',
671 '36' => 'triannually (every 3 years)',
672 '48' => '(every 4 years)',
673 '60' => '(every 5 years)',
674 '120' => '(every 10 years)',
679 =item generate_ps FILENAME
681 Returns an postscript rendition of the LaTex file, as a scalar.
682 FILENAME does not contain the .tex suffix and is unlinked by this function.
686 use String::ShellQuote;
691 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
696 my $papersize = $conf->config('papersize') || 'letter';
698 system('dvips', '-q', '-t', $papersize, "$file.dvi", '-o', "$file.ps" ) == 0
699 or die "dvips failed";
701 open(POSTSCRIPT, "<$file.ps")
702 or die "can't open $file.ps: $! (error in LaTeX template?)\n";
704 unlink("$file.dvi", "$file.log", "$file.aux", "$file.ps", "$file.tex")
705 unless $FS::CurrentUser::CurrentUser->option('save_tmp_typesetting');
709 if ( $conf->exists('lpr-postscript_prefix') ) {
710 my $prefix = $conf->config('lpr-postscript_prefix');
711 $ps .= eval qq("$prefix");
714 while (<POSTSCRIPT>) {
720 if ( $conf->exists('lpr-postscript_suffix') ) {
721 my $suffix = $conf->config('lpr-postscript_suffix');
722 $ps .= eval qq("$suffix");
729 =item generate_pdf FILENAME
731 Returns an PDF rendition of the LaTex file, as a scalar. FILENAME does not
732 contain the .tex suffix and is unlinked by this function.
736 use String::ShellQuote;
741 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
744 #system('pdflatex', "$file.tex");
745 #system('pdflatex', "$file.tex");
746 #! LaTeX Error: Unknown graphics extension: .eps.
750 my $sfile = shell_quote $file;
752 #system('dvipdf', "$file.dvi", "$file.pdf" );
753 my $papersize = $conf->config('papersize') || 'letter';
756 "dvips -q -f $sfile.dvi -t $papersize ".
757 "| gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=$sfile.pdf ".
760 or die "dvips | gs failed: $!";
762 open(PDF, "<$file.pdf")
763 or die "can't open $file.pdf: $! (error in LaTeX template?)\n";
765 unlink("$file.dvi", "$file.log", "$file.aux", "$file.pdf", "$file.tex")
766 unless $FS::CurrentUser::CurrentUser->option('save_tmp_typesetting');
782 #my $sfile = shell_quote $file;
786 '-interaction=batchmode',
787 '\AtBeginDocument{\RequirePackage{pslatex}}',
788 '\def\PSLATEXTMP{\futurelet\PSLATEXTMP\PSLATEXTMPB}',
789 '\def\PSLATEXTMPB{\ifx\PSLATEXTMP\nonstopmode\else\input\fi}',
794 my $timeout = 30; #? should be more than enough
798 local($SIG{CHLD}) = sub {};
799 run( \@cmd, '>'=>'/dev/null', '2>'=>'/dev/null', timeout($timeout) )
800 or warn "bad exit status from pslatex pass $_\n";
804 return if -e "$file.dvi" && -s "$file.dvi";
805 die "pslatex $file.tex failed, see $file.log for details?\n";
809 =item do_print ARRAYREF [, OPTION => VALUE ... ]
811 Sends the lines in ARRAYREF to the printer.
813 Options available are:
819 Uses this agent's 'lpr' configuration setting override instead of the global
824 Uses this command instead of the configured lpr command (overrides both the
825 global value and agentnum).
830 my( $data, %opt ) = @_;
832 my $lpr = ( exists($opt{'lpr'}) && $opt{'lpr'} )
834 : $conf->config('lpr', $opt{'agentnum'} );
837 run3 $lpr, $data, \$outerr, \$outerr;
839 $outerr = ": $outerr" if length($outerr);
840 die "Error from $lpr (exit status ". ($?>>8). ")$outerr\n";
845 =item csv_from_fixed, FILEREF COUNTREF, [ LENGTH_LISTREF, [ CALLBACKS_LISTREF ] ]
847 Converts the filehandle referenced by FILEREF from fixed length record
848 lines to a CSV file according to the lengths specified in LENGTH_LISTREF.
849 The CALLBACKS_LISTREF refers to a correpsonding list of coderefs. Each
850 should return the value to be substituted in place of its single argument.
852 Returns false on success or an error if one occurs.
857 my( $fhref, $countref, $lengths, $callbacks) = @_;
859 eval { require Text::CSV_XS; };
863 my $unpacker = new Text::CSV_XS;
865 my $template = join('', map {$total += $_; "A$_"} @$lengths) if $lengths;
867 my $dir = "%%%FREESIDE_CACHE%%%/cache.$FS::UID::datasrc";
868 my $fh = new File::Temp( TEMPLATE => "FILE.csv.XXXXXXXX",
871 ) or return "can't open temp file: $!\n"
874 while ( defined(my $line=<$ofh>) ) {
880 return "unexpected input at line $$countref: $line".
881 " -- expected $total but received ". length($line)
882 unless length($line) == $total;
884 $unpacker->combine( map { my $i = $column++;
885 defined( $callbacks->[$i] )
886 ? &{ $callbacks->[$i] }( $_ )
888 } unpack( $template, $line )
890 or return "invalid data for CSV: ". $unpacker->error_input;
892 print $fh $unpacker->string(), "\n"
893 or return "can't write temp file: $!\n";
897 if ( $template ) { close $$fhref; $$fhref = $fh }
903 =item ocr_image IMAGE_SCALAR
905 Runs OCR on the provided image data and returns a list of text lines.
910 my $logo_data = shift;
912 #XXX use conf dir location from Makefile
913 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
914 my $fh = new File::Temp(
915 TEMPLATE => 'bizcard.XXXXXXXX',
916 SUFFIX => '.png', #XXX assuming, but should handle jpg, gif, etc. too
919 ) or die "can't open temp file: $!\n";
921 my $filename = $fh->filename;
923 print $fh $logo_data;
926 run( [qw(ocroscript recognize), $filename], '>'=>"$filename.hocr" )
927 or die "ocroscript recognize failed\n";
929 run( [qw(ocroscript hocr-to-text), "$filename.hocr"], '>pipe'=>\*OUT )
930 or die "ocroscript hocr-to-text failed\n";
932 my @lines = split(/\n/, <OUT> );
934 foreach (@lines) { s/\.c0m\s*$/.com/; }
939 =item bytes_substr STRING, OFFSET[, LENGTH[, REPLACEMENT] ]
941 A replacement for "substr" that counts raw bytes rather than logical
942 characters. Unlike "bytes::substr", will suppress fragmented UTF-8 characters
943 rather than output them. Unlike real "substr", is not an lvalue.
948 my ($string, $offset, $length, $repl) = @_;
950 Encode::encode('utf8', $string),
953 Encode::encode('utf8', $repl)
955 my $chk = $DEBUG ? Encode::FB_WARN : Encode::FB_QUIET;
956 return Encode::decode('utf8', $bytes, $chk);
961 Accepts a postive or negative numerical value.
962 Returns amount formatted for display,
963 including money character.
969 my $money_char = $conf->{'money_char'} || '$';
970 $amount = sprintf("%0.2f",$amount);
971 $amount =~ s/^(-?)/$1$money_char/;
983 L<FS::UID>, L<FS::CGI>, L<FS::Record>, the base documentation.
985 L<Fax::Hylafax::Client>