4 use vars qw ( @ISA @EXPORT_OK $DEBUG );
8 #do NOT depend on any FS:: modules here, causes weird (sometimes unreproducable
9 #until on client machine) dependancy loops. put them in FS::Misc::Something
12 @ISA = qw( Exporter );
13 @EXPORT_OK = qw( send_email send_fax
14 states_hash counties state_label
23 FS::Misc - Miscellaneous subroutines
27 use FS::Misc qw(send_email);
33 Miscellaneous subroutines. This module contains miscellaneous subroutines
34 called from multiple other modules. These are not OO or necessarily related,
35 but are collected here to elimiate code duplication.
41 =item send_email OPTION => VALUE ...
47 I<to> - (required) comma-separated scalar or arrayref of recipients
49 I<subject> - (required)
51 I<content-type> - (optional) MIME type for the body
53 I<body> - (required unless I<nobody> is true) arrayref of body text lines
55 I<mimeparts> - (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().
57 I<nobody> - (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,
58 I<content-type>, if specified, overrides the default "multipart/mixed" for the outermost MIME container.
60 I<content-encoding> - (optional) when using nobody, optional top-level MIME
61 encoding which, if specified, overrides the default "7bit".
63 I<type> - (optional) type parameter for multipart/related messages
70 use Mail::Internet 2.00;
74 FS::UID->install_callback( sub {
81 my %doptions = %options;
82 $doptions{'body'} = '(full body not shown in debug)';
83 warn "FS::Misc::send_email called with options:\n ". Dumper(\%doptions);
84 # join("\n", map { " $_: ". $options{$_} } keys %options ). "\n"
87 $ENV{MAILADDRESS} = $options{'from'};
88 my $to = ref($options{to}) ? join(', ', @{ $options{to} } ) : $options{to};
92 if ( $options{'nobody'} ) {
94 croak "'mimeparts' option required when 'nobody' option given\n"
95 unless $options{'mimeparts'};
97 @mimeparts = @{$options{'mimeparts'}};
100 'Type' => ( $options{'content-type'} || 'multipart/mixed' ),
101 'Encoding' => ( $options{'content-encoding'} || '7bit' ),
106 @mimeparts = @{$options{'mimeparts'}}
107 if ref($options{'mimeparts'}) eq 'ARRAY';
109 if (scalar(@mimeparts)) {
112 'Type' => 'multipart/mixed',
113 'Encoding' => '7bit',
116 unshift @mimeparts, {
117 'Type' => ( $options{'content-type'} || 'text/plain' ),
118 'Data' => $options{'body'},
119 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
120 'Disposition' => 'inline',
126 'Type' => ( $options{'content-type'} || 'text/plain' ),
127 'Data' => $options{'body'},
128 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
136 if ( $options{'from'} =~ /\@([\w\.\-]+)/ ) {
139 warn 'no domain found in invoice from address '. $options{'from'}.
140 '; constructing Message-ID @example.com';
141 $domain = 'example.com';
143 my $message_id = join('.', rand()*(2**32), $$, time). "\@$domain";
145 my $message = MIME::Entity->build(
146 'From' => $options{'from'},
148 'Sender' => $options{'from'},
149 'Reply-To' => $options{'from'},
150 'Date' => time2str("%a, %d %b %Y %X %z", time),
151 'Subject' => $options{'subject'},
152 'Message-ID' => "<$message_id>",
156 if ( $options{'type'} ) {
157 #false laziness w/cust_bill::generate_email
158 $message->head->replace('Content-type',
160 '; boundary="'. $message->head->multipart_boundary. '"'.
161 '; type='. $options{'type'}
165 foreach my $part (@mimeparts) {
167 if ( UNIVERSAL::isa($part, 'MIME::Entity') ) {
169 warn "attaching MIME part from MIME::Entity object\n"
171 $message->add_part($part);
173 } elsif ( ref($part) eq 'HASH' ) {
175 warn "attaching MIME part from hashref:\n".
176 join("\n", map " $_: ".$part->{$_}, keys %$part ). "\n"
178 $message->attach(%$part);
181 croak "mimepart $part isn't a hashref or MIME::Entity object!";
186 my $smtpmachine = $conf->config('smtpmachine');
189 $message->mysmtpsend( 'Host' => $smtpmachine,
190 'MailFrom' => $options{'from'},
195 #this kludges a "mysmtpsend" method into Mail::Internet for send_email above
196 #now updated for MailTools v2!
197 package Mail::Internet;
203 sub Mail::Internet::mysmtpsend($@) {
204 my ($self, %opt) = @_;
206 my $host = $opt{Host};
207 my $envelope = $opt{MailFrom}; # || mailaddress();
212 push @hello, Hello => $opt{Hello}
213 if defined $opt{Hello};
215 push @hello, Port => $opt{Port}
216 if exists $opt{Port};
218 push @hello, Debug => $opt{Debug}
219 if exists $opt{Debug};
222 # { local $SIG{__DIE__};
223 # my @hosts = qw(mailhost localhost);
224 # unshift @hosts, split /\:/, $ENV{SMTPHOSTS}
225 # if defined $ENV{SMTPHOSTS};
227 # foreach $host (@hosts)
228 # { $smtp = eval { Net::SMTP->new($host, @hello) };
229 # last if defined $smtp;
232 # elsif(ref($host) && UNIVERSAL::isa($host,'Net::SMTP'))
233 if(ref($host) && UNIVERSAL::isa($host,'Net::SMTP'))
238 { #local $SIG{__DIE__};
239 #$smtp = eval { Net::SMTP->new($host, @hello) };
240 $smtp = Net::SMTP->new($host, @hello);
243 unless ( defined($smtp) ) {
245 $err =~ s/Invalid argument/Unknown host/;
246 return "can't connect to $host: $err"
249 my $head = $self->cleaned_header_dup;
251 $head->delete('Bcc');
255 my @rcpt = map { ref $_ ? @$_ : $_ } grep { defined } @opt{'To','Cc','Bcc'};
256 @rcpt = map { $head->get($_) } qw(To Cc Bcc)
259 my @addr = map {$_->address} Mail::Address->parse(@rcpt);
261 return 'No valid destination addresses found!'
266 my $ok = $smtp->mail($envelope)
268 && $smtp->data(join("", @{$head->header}, "\n", @{$self->body}));
270 #$quit && $smtp->quit;
273 $quit && $smtp->quit;
276 return $smtp->code. ' '. $smtp->message;
282 =item send_fax OPTION => VALUE ...
286 I<dialstring> - (required) 10-digit phone number w/ area code
288 I<docdata> - (required) Array ref containing PostScript or TIFF Class F document
292 I<docfile> - (required) Filename of PostScript TIFF Class F document
294 ...any other options will be passed to L<Fax::Hylafax::Client::sendfax>
303 die 'HylaFAX support has not been configured.'
304 unless $conf->exists('hylafax');
307 require Fax::Hylafax::Client;
311 if ($@ =~ /^Can't locate Fax.*/) {
312 die "You must have Fax::Hylafax::Client installed to use invoice faxing."
318 my %hylafax_opts = map { split /\s+/ } $conf->config('hylafax');
320 die 'Called send_fax without a \'dialstring\'.'
321 unless exists($options{'dialstring'});
323 if (exists($options{'docdata'}) and ref($options{'docdata'}) eq 'ARRAY') {
324 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
325 my $fh = new File::Temp(
326 TEMPLATE => 'faxdoc.'. $options{'dialstring'} . '.XXXXXXXX',
329 ) or die "can't open temp file: $!\n";
331 $options{docfile} = $fh->filename;
333 print $fh @{$options{'docdata'}};
336 delete $options{'docdata'};
339 die 'Called send_fax without a \'docfile\' or \'docdata\'.'
340 unless exists($options{'docfile'});
342 #FIXME: Need to send canonical dialstring to HylaFAX, but this only
345 $options{'dialstring'} =~ s/[^\d\+]//g;
346 if ($options{'dialstring'} =~ /^\d{10}$/) {
347 $options{dialstring} = '+1' . $options{'dialstring'};
349 return 'Invalid dialstring ' . $options{'dialstring'} . '.';
352 my $faxjob = &Fax::Hylafax::Client::sendfax(%options, %hylafax_opts);
354 if ($faxjob->success) {
355 warn "Successfully queued fax to '$options{dialstring}' with jobid " .
360 return 'Error while sending FAX: ' . $faxjob->trace;
365 =item states_hash COUNTRY
367 Returns a list of key/value pairs containing state (or other sub-country
368 division) abbriviations and names.
372 use FS::Record qw(qsearch);
373 use Locale::SubCountry;
380 map { s/[\n\r]//g; $_; }
384 'table' => 'cust_main_county',
385 'hashref' => { 'country' => $country },
386 'extra_sql' => 'GROUP BY state',
389 #it could throw a fatal "Invalid country code" error (for example "AX")
390 my $subcountry = eval { new Locale::SubCountry($country) }
391 or return ( '', '(n/a)' );
393 #"i see your schwartz is as big as mine!"
394 map { ( $_->[0] => $_->[1] ) }
395 sort { $a->[1] cmp $b->[1] }
396 map { [ $_ => state_label($_, $subcountry) ] }
400 =item counties STATE COUNTRY
402 Returns a list of counties for this state and country.
407 my( $state, $country ) = @_;
409 sort map { s/[\n\r]//g; $_; }
412 'select' => 'DISTINCT county',
413 'table' => 'cust_main_county',
414 'hashref' => { 'state' => $state,
415 'country' => $country,
420 =item state_label STATE COUNTRY_OR_LOCALE_SUBCOUNRY_OBJECT
425 my( $state, $country ) = @_;
427 unless ( ref($country) ) {
428 $country = eval { new Locale::SubCountry($country) }
433 # US kludge to avoid changing existing behaviour
434 # also we actually *use* the abbriviations...
435 my $full_name = $country->country_code eq 'US'
437 : $country->full_name($state);
439 $full_name = '' if $full_name eq 'unknown';
440 $full_name =~ s/\(see also.*\)\s*$//;
441 $full_name .= " ($state)" if $full_name;
443 $full_name || $state || '(n/a)';
449 Returns a hash reference of the accepted credit card types. Keys are shorter
450 identifiers and values are the longer strings used by the system (see
451 L<Business::CreditCard>).
458 my $conf = new FS::Conf;
461 #displayname #value (Business::CreditCard)
462 "VISA" => "VISA card",
463 "MasterCard" => "MasterCard",
464 "Discover" => "Discover card",
465 "American Express" => "American Express card",
466 "Diner's Club/Carte Blanche" => "Diner's Club/Carte Blanche",
467 "enRoute" => "enRoute",
469 "BankCard" => "BankCard",
470 "Switch" => "Switch",
473 my @conf_card_types = grep { ! /^\s*$/ } $conf->config('card-types');
474 if ( @conf_card_types ) {
475 #perhaps the hash is backwards for this, but this way works better for
476 #usage in selfservice
477 %card_types = map { $_ => $card_types{$_} }
480 grep { $card_types{$d} eq $_ } @conf_card_types
488 =item generate_ps FILENAME
490 Returns an postscript rendition of the LaTex file, as a scalar.
491 FILENAME does not contain the .tex suffix and is unlinked by this function.
495 use String::ShellQuote;
500 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
503 my $sfile = shell_quote $file;
505 system("pslatex $sfile.tex >/dev/null 2>&1") == 0
506 or die "pslatex $file.tex failed; see $file.log for details?\n";
507 system("pslatex $sfile.tex >/dev/null 2>&1") == 0
508 or die "pslatex $file.tex failed; see $file.log for details?\n";
510 system('dvips', '-q', '-t', 'letter', "$file.dvi", '-o', "$file.ps" ) == 0
511 or die "dvips failed";
513 open(POSTSCRIPT, "<$file.ps")
514 or die "can't open $file.ps: $! (error in LaTeX template?)\n";
516 unlink("$file.dvi", "$file.log", "$file.aux", "$file.ps", "$file.tex");
520 if ( $conf->exists('lpr-postscript_prefix') ) {
521 my $prefix = $conf->config('lpr-postscript_prefix');
522 $ps .= eval qq("$prefix");
525 while (<POSTSCRIPT>) {
531 if ( $conf->exists('lpr-postscript_suffix') ) {
532 my $suffix = $conf->config('lpr-postscript_suffix');
533 $ps .= eval qq("$suffix");
542 Sends the lines in ARRAYREF to the printer.
551 my $lpr = $conf->config('lpr');
554 run3 $lpr, $data, \$outerr, \$outerr;
556 $outerr = ": $outerr" if length($outerr);
557 die "Error from $lpr (exit status ". ($?>>8). ")$outerr\n";
570 L<FS::UID>, L<FS::CGI>, L<FS::Record>, the base documentation.
572 L<Fax::Hylafax::Client>