4 use vars qw ( @ISA @EXPORT_OK $DEBUG );
10 @EXPORT_OK = qw( send_email send_fax
11 states_hash counties state_label
19 FS::Misc - Miscellaneous subroutines
23 use FS::Misc qw(send_email);
29 Miscellaneous subroutines. This module contains miscellaneous subroutines
30 called from multiple other modules. These are not OO or necessarily related,
31 but are collected here to elimiate code duplication.
37 =item send_email OPTION => VALUE ...
43 I<to> - (required) comma-separated scalar or arrayref of recipients
45 I<subject> - (required)
47 I<content-type> - (optional) MIME type for the body
49 I<body> - (required unless I<nobody> is true) arrayref of body text lines
51 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().
53 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,
54 I<content-type>, if specified, overrides the default "multipart/mixed" for the outermost MIME container.
56 I<content-encoding> - (optional) when using nobody, optional top-level MIME
57 encoding which, if specified, overrides the default "7bit".
59 I<type> - (optional) type parameter for multipart/related messages
66 use Mail::Internet 1.44;
70 FS::UID->install_callback( sub {
77 my %doptions = %options;
78 $doptions{'body'} = '(full body not shown in debug)';
79 warn "FS::Misc::send_email called with options:\n ". Dumper(\%doptions);
80 # join("\n", map { " $_: ". $options{$_} } keys %options ). "\n"
83 $ENV{MAILADDRESS} = $options{'from'};
84 my $to = ref($options{to}) ? join(', ', @{ $options{to} } ) : $options{to};
88 if ( $options{'nobody'} ) {
90 croak "'mimeparts' option required when 'nobody' option given\n"
91 unless $options{'mimeparts'};
93 @mimeparts = @{$options{'mimeparts'}};
96 'Type' => ( $options{'content-type'} || 'multipart/mixed' ),
97 'Encoding' => ( $options{'content-encoding'} || '7bit' ),
102 @mimeparts = @{$options{'mimeparts'}}
103 if ref($options{'mimeparts'}) eq 'ARRAY';
105 if (scalar(@mimeparts)) {
108 'Type' => 'multipart/mixed',
109 'Encoding' => '7bit',
112 unshift @mimeparts, {
113 'Type' => ( $options{'content-type'} || 'text/plain' ),
114 'Data' => $options{'body'},
115 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
116 'Disposition' => 'inline',
122 'Type' => ( $options{'content-type'} || 'text/plain' ),
123 'Data' => $options{'body'},
124 'Encoding' => ( $options{'content-type'} ? '-SUGGEST' : '7bit' ),
132 if ( $options{'from'} =~ /\@([\w\.\-]+)/ ) {
135 warn 'no domain found in invoice from address '. $options{'from'}.
136 '; constructing Message-ID @example.com';
137 $domain = 'example.com';
139 my $message_id = join('.', rand()*(2**32), $$, time). "\@$domain";
141 my $message = MIME::Entity->build(
142 'From' => $options{'from'},
144 'Sender' => $options{'from'},
145 'Reply-To' => $options{'from'},
146 'Date' => time2str("%a, %d %b %Y %X %z", time),
147 'Subject' => $options{'subject'},
148 'Message-ID' => "<$message_id>",
152 if ( $options{'type'} ) {
153 #false laziness w/cust_bill::generate_email
154 $message->head->replace('Content-type',
156 '; boundary="'. $message->head->multipart_boundary. '"'.
157 '; type='. $options{'type'}
161 foreach my $part (@mimeparts) {
163 if ( UNIVERSAL::isa($part, 'MIME::Entity') ) {
165 warn "attaching MIME part from MIME::Entity object\n"
167 $message->add_part($part);
169 } elsif ( ref($part) eq 'HASH' ) {
171 warn "attaching MIME part from hashref:\n".
172 join("\n", map " $_: ".$part->{$_}, keys %$part ). "\n"
174 $message->attach(%$part);
177 croak "mimepart $part isn't a hashref or MIME::Entity object!";
182 my $smtpmachine = $conf->config('smtpmachine');
185 $message->mysmtpsend( 'Host' => $smtpmachine,
186 'MailFrom' => $options{'from'},
191 #this kludges a "mysmtpsend" method into Mail::Internet for send_email above
192 package Mail::Internet;
197 sub Mail::Internet::mysmtpsend {
200 my $host = $opt{Host};
201 my $envelope = $opt{MailFrom};
204 my @hello = defined $opt{Hello} ? (Hello => $opt{Hello}) : ();
206 push(@hello, 'Port', $opt{'Port'})
207 if exists $opt{'Port'};
209 push(@hello, 'Debug', $opt{'Debug'})
210 if exists $opt{'Debug'};
212 if(ref($host) && UNIVERSAL::isa($host,'Net::SMTP')) {
217 #local $SIG{__DIE__};
218 #$smtp = eval { Net::SMTP->new($host, @hello) };
219 $smtp = new Net::SMTP $host, @hello;
222 unless ( defined($smtp) ) {
224 $err =~ s/Invalid argument/Unknown host/;
225 return "can't connect to $host: $err"
228 my $hdr = $src->head->dup;
234 my @rcpt = map { ref($_) ? @$_ : $_ } grep { defined } @opt{'To','Cc','Bcc'};
235 @rcpt = map { $hdr->get($_) } qw(To Cc Bcc)
237 my @addr = map($_->address, Mail::Address->parse(@rcpt));
239 return 'No valid destination addresses found!'
242 $hdr->delete('Bcc'); # Remove blind Cc's
246 #warn "Headers: \n" . join('',@{$hdr->header});
247 #warn "Body: \n" . join('',@{$src->body});
249 my $ok = $smtp->mail( $envelope ) &&
251 $smtp->data(join("", @{$hdr->header},"\n",@{$src->body}));
258 return $smtp->code. ' '. $smtp->message;
265 =item send_fax OPTION => VALUE ...
269 I<dialstring> - (required) 10-digit phone number w/ area code
271 I<docdata> - (required) Array ref containing PostScript or TIFF Class F document
275 I<docfile> - (required) Filename of PostScript TIFF Class F document
277 ...any other options will be passed to L<Fax::Hylafax::Client::sendfax>
286 die 'HylaFAX support has not been configured.'
287 unless $conf->exists('hylafax');
290 require Fax::Hylafax::Client;
294 if ($@ =~ /^Can't locate Fax.*/) {
295 die "You must have Fax::Hylafax::Client installed to use invoice faxing."
301 my %hylafax_opts = map { split /\s+/ } $conf->config('hylafax');
303 die 'Called send_fax without a \'dialstring\'.'
304 unless exists($options{'dialstring'});
306 if (exists($options{'docdata'}) and ref($options{'docdata'}) eq 'ARRAY') {
307 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
308 my $fh = new File::Temp(
309 TEMPLATE => 'faxdoc.'. $options{'dialstring'} . '.XXXXXXXX',
312 ) or die "can't open temp file: $!\n";
314 $options{docfile} = $fh->filename;
316 print $fh @{$options{'docdata'}};
319 delete $options{'docdata'};
322 die 'Called send_fax without a \'docfile\' or \'docdata\'.'
323 unless exists($options{'docfile'});
325 #FIXME: Need to send canonical dialstring to HylaFAX, but this only
328 $options{'dialstring'} =~ s/[^\d\+]//g;
329 if ($options{'dialstring'} =~ /^\d{10}$/) {
330 $options{dialstring} = '+1' . $options{'dialstring'};
332 return 'Invalid dialstring ' . $options{'dialstring'} . '.';
335 my $faxjob = &Fax::Hylafax::Client::sendfax(%options, %hylafax_opts);
337 if ($faxjob->success) {
338 warn "Successfully queued fax to '$options{dialstring}' with jobid " .
343 return 'Error while sending FAX: ' . $faxjob->trace;
348 =item states_hash COUNTRY
350 Returns a list of key/value pairs containing state (or other sub-country
351 division) abbriviations and names.
355 use FS::Record qw(qsearch);
356 use Locale::SubCountry;
363 map { s/[\n\r]//g; $_; }
367 'table' => 'cust_main_county',
368 'hashref' => { 'country' => $country },
369 'extra_sql' => 'GROUP BY state',
372 #it could throw a fatal "Invalid country code" error (for example "AX")
373 my $subcountry = eval { new Locale::SubCountry($country) }
374 or return ( '', '(n/a)' );
376 #"i see your schwartz is as big as mine!"
377 map { ( $_->[0] => $_->[1] ) }
378 sort { $a->[1] cmp $b->[1] }
379 map { [ $_ => state_label($_, $subcountry) ] }
383 =item counties STATE COUNTRY
385 Returns a list of counties for this state and country.
390 my( $state, $country ) = @_;
392 sort map { s/[\n\r]//g; $_; }
395 'select' => 'DISTINCT county',
396 'table' => 'cust_main_county',
397 'hashref' => { 'state' => $state,
398 'country' => $country,
403 =item state_label STATE COUNTRY_OR_LOCALE_SUBCOUNRY_OBJECT
408 my( $state, $country ) = @_;
410 unless ( ref($country) ) {
411 $country = eval { new Locale::SubCountry($country) }
416 # US kludge to avoid changing existing behaviour
417 # also we actually *use* the abbriviations...
418 my $full_name = $country->country_code eq 'US'
420 : $country->full_name($state);
422 $full_name = '' if $full_name eq 'unknown';
423 $full_name =~ s/\(see also.*\)\s*$//;
424 $full_name .= " ($state)" if $full_name;
426 $full_name || $state || '(n/a)';
432 Returns a hash reference of the accepted credit card types. Keys are shorter
433 identifiers and values are the longer strings used by the system (see
434 L<Business::CreditCard).
441 my $conf = new FS::Conf;
444 #displayname #value (Business::CreditCard)
445 "VISA" => "VISA card",
446 "MasterCard" => "MasterCard",
447 "Discover" => "Discover card",
448 "American Express" => "American Express card",
449 "Diner's Club/Carte Blanche" => "Diner's Club/Carte Blanche",
450 "enRoute" => "enRoute",
452 "BankCard" => "BankCard",
453 "Switch" => "Switch",
456 my @conf_card_types = grep { ! /^\s*$/ } $conf->config('card-types');
457 if ( @conf_card_types ) {
458 #perhaps the hash is backwards for this, but this way works better for
459 #usage in selfservice
460 %card_types = map { $_ => $card_types{$_} }
463 grep { $card_types{$d} eq $_ } @conf_card_types
479 L<FS::UID>, L<FS::CGI>, L<FS::Record>, the base documentation.
481 L<Fax::Hylafax::Client>