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 1.44;
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 package Mail::Internet;
201 sub Mail::Internet::mysmtpsend {
204 my $host = $opt{Host};
205 my $envelope = $opt{MailFrom};
208 my @hello = defined $opt{Hello} ? (Hello => $opt{Hello}) : ();
210 push(@hello, 'Port', $opt{'Port'})
211 if exists $opt{'Port'};
213 push(@hello, 'Debug', $opt{'Debug'})
214 if exists $opt{'Debug'};
216 if(ref($host) && UNIVERSAL::isa($host,'Net::SMTP')) {
221 #local $SIG{__DIE__};
222 #$smtp = eval { Net::SMTP->new($host, @hello) };
223 $smtp = new Net::SMTP $host, @hello;
226 unless ( defined($smtp) ) {
228 $err =~ s/Invalid argument/Unknown host/;
229 return "can't connect to $host: $err"
232 my $hdr = $src->head->dup;
238 my @rcpt = map { ref($_) ? @$_ : $_ } grep { defined } @opt{'To','Cc','Bcc'};
239 @rcpt = map { $hdr->get($_) } qw(To Cc Bcc)
241 my @addr = map($_->address, Mail::Address->parse(@rcpt));
243 return 'No valid destination addresses found!'
246 $hdr->delete('Bcc'); # Remove blind Cc's
250 #warn "Headers: \n" . join('',@{$hdr->header});
251 #warn "Body: \n" . join('',@{$src->body});
253 my $ok = $smtp->mail( $envelope ) &&
255 $smtp->data(join("", @{$hdr->header},"\n",@{$src->body}));
262 return $smtp->code. ' '. $smtp->message;
269 =item send_fax OPTION => VALUE ...
273 I<dialstring> - (required) 10-digit phone number w/ area code
275 I<docdata> - (required) Array ref containing PostScript or TIFF Class F document
279 I<docfile> - (required) Filename of PostScript TIFF Class F document
281 ...any other options will be passed to L<Fax::Hylafax::Client::sendfax>
290 die 'HylaFAX support has not been configured.'
291 unless $conf->exists('hylafax');
294 require Fax::Hylafax::Client;
298 if ($@ =~ /^Can't locate Fax.*/) {
299 die "You must have Fax::Hylafax::Client installed to use invoice faxing."
305 my %hylafax_opts = map { split /\s+/ } $conf->config('hylafax');
307 die 'Called send_fax without a \'dialstring\'.'
308 unless exists($options{'dialstring'});
310 if (exists($options{'docdata'}) and ref($options{'docdata'}) eq 'ARRAY') {
311 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
312 my $fh = new File::Temp(
313 TEMPLATE => 'faxdoc.'. $options{'dialstring'} . '.XXXXXXXX',
316 ) or die "can't open temp file: $!\n";
318 $options{docfile} = $fh->filename;
320 print $fh @{$options{'docdata'}};
323 delete $options{'docdata'};
326 die 'Called send_fax without a \'docfile\' or \'docdata\'.'
327 unless exists($options{'docfile'});
329 #FIXME: Need to send canonical dialstring to HylaFAX, but this only
332 $options{'dialstring'} =~ s/[^\d\+]//g;
333 if ($options{'dialstring'} =~ /^\d{10}$/) {
334 $options{dialstring} = '+1' . $options{'dialstring'};
336 return 'Invalid dialstring ' . $options{'dialstring'} . '.';
339 my $faxjob = &Fax::Hylafax::Client::sendfax(%options, %hylafax_opts);
341 if ($faxjob->success) {
342 warn "Successfully queued fax to '$options{dialstring}' with jobid " .
347 return 'Error while sending FAX: ' . $faxjob->trace;
352 =item states_hash COUNTRY
354 Returns a list of key/value pairs containing state (or other sub-country
355 division) abbriviations and names.
359 use FS::Record qw(qsearch);
360 use Locale::SubCountry;
367 map { s/[\n\r]//g; $_; }
371 'table' => 'cust_main_county',
372 'hashref' => { 'country' => $country },
373 'extra_sql' => 'GROUP BY state',
376 #it could throw a fatal "Invalid country code" error (for example "AX")
377 my $subcountry = eval { new Locale::SubCountry($country) }
378 or return ( '', '(n/a)' );
380 #"i see your schwartz is as big as mine!"
381 map { ( $_->[0] => $_->[1] ) }
382 sort { $a->[1] cmp $b->[1] }
383 map { [ $_ => state_label($_, $subcountry) ] }
387 =item counties STATE COUNTRY
389 Returns a list of counties for this state and country.
394 my( $state, $country ) = @_;
396 sort map { s/[\n\r]//g; $_; }
399 'select' => 'DISTINCT county',
400 'table' => 'cust_main_county',
401 'hashref' => { 'state' => $state,
402 'country' => $country,
407 =item state_label STATE COUNTRY_OR_LOCALE_SUBCOUNRY_OBJECT
412 my( $state, $country ) = @_;
414 unless ( ref($country) ) {
415 $country = eval { new Locale::SubCountry($country) }
420 # US kludge to avoid changing existing behaviour
421 # also we actually *use* the abbriviations...
422 my $full_name = $country->country_code eq 'US'
424 : $country->full_name($state);
426 $full_name = '' if $full_name eq 'unknown';
427 $full_name =~ s/\(see also.*\)\s*$//;
428 $full_name .= " ($state)" if $full_name;
430 $full_name || $state || '(n/a)';
436 Returns a hash reference of the accepted credit card types. Keys are shorter
437 identifiers and values are the longer strings used by the system (see
438 L<Business::CreditCard>).
445 my $conf = new FS::Conf;
448 #displayname #value (Business::CreditCard)
449 "VISA" => "VISA card",
450 "MasterCard" => "MasterCard",
451 "Discover" => "Discover card",
452 "American Express" => "American Express card",
453 "Diner's Club/Carte Blanche" => "Diner's Club/Carte Blanche",
454 "enRoute" => "enRoute",
456 "BankCard" => "BankCard",
457 "Switch" => "Switch",
460 my @conf_card_types = grep { ! /^\s*$/ } $conf->config('card-types');
461 if ( @conf_card_types ) {
462 #perhaps the hash is backwards for this, but this way works better for
463 #usage in selfservice
464 %card_types = map { $_ => $card_types{$_} }
467 grep { $card_types{$d} eq $_ } @conf_card_types
475 =item generate_ps FILENAME
477 Returns an postscript rendition of the LaTex file, as a scalar.
478 FILENAME does not contain the .tex suffix and is unlinked by this function.
482 use String::ShellQuote;
487 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
490 my $sfile = shell_quote $file;
492 system("pslatex $sfile.tex >/dev/null 2>&1") == 0
493 or die "pslatex $file.tex failed; see $file.log for details?\n";
494 system("pslatex $sfile.tex >/dev/null 2>&1") == 0
495 or die "pslatex $file.tex failed; see $file.log for details?\n";
497 system('dvips', '-q', '-t', 'letter', "$file.dvi", '-o', "$file.ps" ) == 0
498 or die "dvips failed";
500 open(POSTSCRIPT, "<$file.ps")
501 or die "can't open $file.ps: $! (error in LaTeX template?)\n";
503 unlink("$file.dvi", "$file.log", "$file.aux", "$file.ps", "$file.tex");
507 if ( $conf->exists('lpr-postscript_prefix') ) {
508 my $prefix = $conf->config('lpr-postscript_prefix');
509 $ps .= eval qq("$prefix");
512 while (<POSTSCRIPT>) {
518 if ( $conf->exists('lpr-postscript_suffix') ) {
519 my $suffix = $conf->config('lpr-postscript_suffix');
520 $ps .= eval qq("$suffix");
529 Sends the lines in ARRAYREF to the printer.
538 my $lpr = $conf->config('lpr');
541 run3 $lpr, $data, \$outerr, \$outerr;
543 $outerr = ": $outerr" if length($outerr);
544 die "Error from $lpr (exit status ". ($?>>8). ")$outerr\n";
557 L<FS::UID>, L<FS::CGI>, L<FS::Record>, the base documentation.
559 L<Fax::Hylafax::Client>