4 use base qw( FS::svc_Domain_Mixin
11 use vars qw( $DEBUG $me $conf $skip_fuzzyfiles
12 $dir_prefix @shells $usernamemin
13 $usernamemax $passwordmin $passwordmax
14 $username_ampersand $username_letter $username_letterfirst
15 $username_noperiod $username_nounderscore $username_nodash
16 $username_uppercase $username_percent $username_colon
17 $username_slash $username_equals $username_pound
19 $password_noampersand $password_noexclamation
20 $warning_template $warning_from $warning_subject $warning_mimetype
23 $radius_password $radius_ip
26 use Scalar::Util qw( blessed );
31 use Crypt::PasswdMD5 1.2;
32 use Digest::SHA 'sha1_base64';
33 use Digest::MD5 'md5_base64';
36 use Authen::Passphrase;
37 use FS::UID qw( datasrc driver_name );
39 use FS::Record qw( qsearch qsearchs fields dbh dbdef );
40 use FS::Msgcat qw(gettext);
41 use FS::UI::bytecount;
43 use FS::PagedSearch qw( psearch ); # XXX in v4, replace with FS::Cursor
47 use FS::cust_main_invoice;
52 use FS::radius_usergroup;
64 $me = '[FS::svc_acct]';
66 #ask FS::UID to run this stuff for us later
67 FS::UID->install_callback( sub {
69 $dir_prefix = $conf->config('home');
70 @shells = $conf->config('shells');
71 $usernamemin = $conf->config('usernamemin') || 2;
72 $usernamemax = $conf->config('usernamemax');
73 $passwordmin = $conf->config('passwordmin'); # || 6;
75 $passwordmin = ( defined($passwordmin) && $passwordmin =~ /\d+/ )
78 $passwordmax = $conf->config('passwordmax') || 8;
79 $username_letter = $conf->exists('username-letter');
80 $username_letterfirst = $conf->exists('username-letterfirst');
81 $username_noperiod = $conf->exists('username-noperiod');
82 $username_nounderscore = $conf->exists('username-nounderscore');
83 $username_nodash = $conf->exists('username-nodash');
84 $username_uppercase = $conf->exists('username-uppercase');
85 $username_ampersand = $conf->exists('username-ampersand');
86 $username_percent = $conf->exists('username-percent');
87 $username_colon = $conf->exists('username-colon');
88 $username_slash = $conf->exists('username-slash');
89 $username_equals = $conf->exists('username-equals');
90 $username_pound = $conf->exists('username-pound');
91 $username_exclamation = $conf->exists('username-exclamation');
92 $password_noampersand = $conf->exists('password-noexclamation');
93 $password_noexclamation = $conf->exists('password-noexclamation');
94 $dirhash = $conf->config('dirhash') || 0;
95 if ( $conf->exists('warning_email') ) {
96 $warning_template = new Text::Template (
98 SOURCE => [ map "$_\n", $conf->config('warning_email') ]
99 ) or warn "can't create warning email template: $Text::Template::ERROR";
100 $warning_from = $conf->config('warning_email-from'); # || 'your-isp-is-dum'
101 $warning_subject = $conf->config('warning_email-subject') || 'Warning';
102 $warning_mimetype = $conf->config('warning_email-mimetype') || 'text/plain';
103 $warning_cc = $conf->config('warning_email-cc');
105 $warning_template = '';
107 $warning_subject = '';
108 $warning_mimetype = '';
111 $smtpmachine = $conf->config('smtpmachine');
112 $radius_password = $conf->config('radius-password') || 'Password';
113 $radius_ip = $conf->config('radius-ip') || 'Framed-IP-Address';
114 @pw_set = ( 'A'..'Z' ) if $conf->exists('password-generated-allcaps');
118 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '.' , '/' );
119 @pw_set = ( 'a'..'z', 'A'..'Z', '0'..'9', '(', ')', '#', '.', ',' );
123 my ( $hashref, $cache ) = @_;
124 if ( $hashref->{'svc_acct_svcnum'} ) {
125 $self->{'_domsvc'} = FS::svc_domain->new( {
126 'svcnum' => $hashref->{'domsvc'},
127 'domain' => $hashref->{'svc_acct_domain'},
128 'catchall' => $hashref->{'svc_acct_catchall'},
135 FS::svc_acct - Object methods for svc_acct records
141 $record = new FS::svc_acct \%hash;
142 $record = new FS::svc_acct { 'column' => 'value' };
144 $error = $record->insert;
146 $error = $new_record->replace($old_record);
148 $error = $record->delete;
150 $error = $record->check;
152 $error = $record->suspend;
154 $error = $record->unsuspend;
156 $error = $record->cancel;
158 %hash = $record->radius;
160 %hash = $record->radius_reply;
162 %hash = $record->radius_check;
164 $domain = $record->domain;
166 $svc_domain = $record->svc_domain;
168 $email = $record->email;
170 $seconds_since = $record->seconds_since($timestamp);
174 An FS::svc_acct object represents an account. FS::svc_acct inherits from
175 FS::svc_Common. The following fields are currently supported:
181 Primary key (assigned automatcially for new accounts)
189 =item _password_encoding
191 plain, crypt, ldap (or empty for autodetection)
199 Point of presence (see L<FS::svc_acct_pop>)
211 set automatically if blank (and uid is not)
231 svcnum from svc_domain
235 Optional svcnum from svc_pbx
237 =item radius_I<Radius_Attribute>
239 I<Radius-Attribute> (reply)
241 =item rc_I<Radius_Attribute>
243 I<Radius-Attribute> (check)
253 Creates a new account. To add the account to the database, see L<"insert">.
260 'longname_plural' => 'Access accounts and mailboxes',
261 'sorts' => [ 'username', 'uid', 'seconds', 'last_login' ],
262 'display_weight' => 10,
263 'cancel_weight' => 50,
264 'ip_field' => 'slipip',
265 'manual_require' => 1,
267 'dir' => 'Home directory',
270 def_info => 'set to fixed and blank for no UIDs',
273 'slipip' => 'IP address',
274 # 'popnum' => qq!<A HREF="$p/browse/svc_acct_pop.cgi/">POP number</A>!,
276 label => 'Access number',
278 select_table => 'svc_acct_pop',
279 select_key => 'popnum',
280 select_label => 'city',
286 disable_default => 1,
291 'password_selfchange' => { label => 'Password modification',
294 'password_recover' => { label => 'Password recovery',
298 label => 'Quota', #Mail storage limit
300 disable_inventory => 1,
303 label => 'File storage limit',
305 disable_inventory => 1,
308 label => 'Number of files limit',
310 disable_inventory => 1,
313 label => 'File size limit',
315 disable_inventory => 1,
317 '_password' => { label => 'Password',
322 def_info => 'when blank, defaults to UID',
327 def_info => 'set to blank for no shell tracking',
329 #select_list => [ $conf->config('shells') ],
330 select_list => [ $conf ? $conf->config('shells') : () ],
331 disable_inventory => 1,
334 'finger' => 'Real name', # (GECOS)',
338 select_table => 'svc_domain',
339 select_key => 'svcnum',
340 select_label => 'domain',
341 disable_inventory => 1,
344 'pbxsvc' => { label => 'PBX',
345 type => 'select-svc_pbx.html',
346 disable_inventory => 1,
347 disable_select => 1, #UI wonky, pry works otherwise
349 'sectornum' => 'Tower sector',
351 label => 'RADIUS groups',
352 type => 'select-radius_group.html',
353 disable_inventory => 1,
357 'seconds' => { label => 'Seconds',
358 label_sort => 'with Time Remaining',
360 disable_inventory => 1,
362 disable_part_svc_column => 1,
364 'upbytes' => { label => 'Upload',
366 disable_inventory => 1,
368 'format' => \&FS::UI::bytecount::display_bytecount,
369 'parse' => \&FS::UI::bytecount::parse_bytecount,
370 disable_part_svc_column => 1,
372 'downbytes' => { label => 'Download',
374 disable_inventory => 1,
376 'format' => \&FS::UI::bytecount::display_bytecount,
377 'parse' => \&FS::UI::bytecount::parse_bytecount,
378 disable_part_svc_column => 1,
380 'totalbytes'=> { label => 'Total up and download',
382 disable_inventory => 1,
384 'format' => \&FS::UI::bytecount::display_bytecount,
385 'parse' => \&FS::UI::bytecount::parse_bytecount,
386 disable_part_svc_column => 1,
388 'seconds_threshold' => { label => 'Seconds threshold',
390 disable_inventory => 1,
392 disable_part_svc_column => 1,
394 'upbytes_threshold' => { label => 'Upload threshold',
396 disable_inventory => 1,
398 'format' => \&FS::UI::bytecount::display_bytecount,
399 'parse' => \&FS::UI::bytecount::parse_bytecount,
400 disable_part_svc_column => 1,
402 'downbytes_threshold' => { label => 'Download threshold',
404 disable_inventory => 1,
406 'format' => \&FS::UI::bytecount::display_bytecount,
407 'parse' => \&FS::UI::bytecount::parse_bytecount,
408 disable_part_svc_column => 1,
410 'totalbytes_threshold'=> { label => 'Total up and download threshold',
412 disable_inventory => 1,
414 'format' => \&FS::UI::bytecount::display_bytecount,
415 'parse' => \&FS::UI::bytecount::parse_bytecount,
416 disable_part_svc_column => 1,
419 label => 'Last login',
423 label => 'Last logout',
428 label => 'Communigate aliases',
430 disable_inventory => 1,
435 label => 'Communigate account type',
437 select_list => [qw( MultiMailbox TextMailbox MailDirMailbox AGrade BGrade CGrade )],
438 disable_inventory => 1,
441 'cgp_accessmodes' => {
442 label => 'Communigate enabled services',
443 type => 'communigate_pro-accessmodes',
444 disable_inventory => 1,
447 'cgp_rulesallowed' => {
448 label => 'Allowed mail rules',
450 select_list => [ '', 'No', 'Filter Only', 'All But Exec', 'Any' ],
451 disable_inventory => 1,
454 'cgp_rpopallowed' => { label => 'RPOP modifications',
457 'cgp_mailtoall' => { label => 'Accepts mail to "all"',
460 'cgp_addmailtrailer' => { label => 'Add trailer to sent mail',
463 'cgp_archiveafter' => {
464 label => 'Archive messages after',
467 -2 => 'default(730 days)',
474 1209600 => '2 weeks',
475 2592000 => '30 days',
476 7776000 => '90 days',
477 15552000 => '180 days',
478 31536000 => '365 days',
479 63072000 => '730 days',
481 disable_inventory => 1,
487 'cgp_deletemode' => {
488 label => 'Communigate message delete method',
490 select_list => [ 'Move To Trash', 'Immediately', 'Mark' ],
491 disable_inventory => 1,
494 'cgp_emptytrash' => {
495 label => 'Communigate on logout remove trash',
497 select_list => __PACKAGE__->cgp_emptytrash_values,
498 disable_inventory => 1,
502 label => 'Communigate language',
504 select_list => [ '', qw( English Arabic Chinese Dutch French German Hebrew Italian Japanese Portuguese Russian Slovak Spanish Thai ) ],
505 disable_inventory => 1,
509 label => 'Communigate time zone',
511 select_list => __PACKAGE__->cgp_timezone_values,
512 disable_inventory => 1,
516 label => 'Communigate layout',
518 select_list => [ '', '***', 'GoldFleece', 'Skin2' ],
519 disable_inventory => 1,
522 'cgp_prontoskinname' => {
523 label => 'Communigate Pronto style',
525 select_list => [ '', 'Pronto', 'Pronto-darkflame', 'Pronto-steel', 'Pronto-twilight', ],
526 disable_inventory => 1,
529 'cgp_sendmdnmode' => {
530 label => 'Communigate send read receipts',
532 select_list => [ '', 'Never', 'Manually', 'Automatically' ],
533 disable_inventory => 1,
544 sub table { 'svc_acct'; }
546 sub table_dupcheck_fields { ( 'username', 'domsvc' ); }
549 shift->_lastlog('in', @_);
553 shift->_lastlog('out', @_);
557 my( $self, $op, $time ) = @_;
559 if ( defined($time) ) {
560 warn "$me last_log$op called on svcnum ". $self->svcnum.
561 ' ('. $self->email. "): $time\n"
566 my $sql = "UPDATE svc_acct SET last_log$op = ? WHERE svcnum = ?";
570 my $sth = $dbh->prepare( $sql )
571 or die "Error preparing $sql: ". $dbh->errstr;
572 my $rv = $sth->execute($time, $self->svcnum);
573 die "Error executing $sql: ". $sth->errstr
575 die "Can't update last_log$op for svcnum". $self->svcnum
578 $self->{'Hash'}->{"last_log$op"} = $time;
580 $self->getfield("last_log$op");
584 =item search_sql STRING
586 Class method which returns an SQL fragment to search for the given string.
591 my( $class, $string ) = @_;
592 if ( $string =~ /^([^@]+)@([^@]+)$/ ) {
593 my( $username, $domain ) = ( $1, $2 );
594 my $q_username = dbh->quote($username);
595 my @svc_domain = qsearch('svc_domain', { 'domain' => $domain } );
597 "svc_acct.username = $q_username AND ( ".
598 join( ' OR ', map { "svc_acct.domsvc = ". $_->svcnum; } @svc_domain ).
603 } elsif ( $string =~ /^(\d{1,3}\.){3}\d{1,3}$/ ) {
605 $class->search_sql_field('slipip', $string ).
607 $class->search_sql_field('username', $string ).
610 $class->search_sql_field('username', $string);
614 =item label [ END_TIMESTAMP [ START_TIMESTAMP ] ]
616 Returns the "username@domain" string for this account.
618 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
628 =item label_long [ END_TIMESTAMP [ START_TIMESTAMP ] ]
630 Returns a longer string label for this acccount ("Real Name <username@domain>"
631 if available, or "username@domain").
633 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
640 my $label = $self->label(@_);
641 my $finger = $self->finger;
642 return $label unless $finger =~ /\S/;
643 my $maxlen = 40 - length($label) - length($self->cust_svc->part_svc->svc);
644 $finger = substr($finger, 0, $maxlen-3).'...' if length($finger) > $maxlen;
648 =item insert [ , OPTION => VALUE ... ]
650 Adds this account to the database. If there is an error, returns the error,
651 otherwise returns false.
653 The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be
654 defined. An FS::cust_svc record will be created and inserted.
656 The additional field I<usergroup> can optionally be defined; if so it should
657 contain an arrayref of group names. See L<FS::radius_usergroup>.
659 The additional field I<child_objects> can optionally be defined; if so it
660 should contain an arrayref of FS::tablename objects. They will have their
661 svcnum fields set and will be inserted after this record, but before any
662 exports are run. Each element of the array can also optionally be a
663 two-element array reference containing the child object and the name of an
664 alternate field to be filled in with the newly-inserted svcnum, for example
665 C<[ $svc_forward, 'srcsvc' ]>
667 Currently available options are: I<depend_jobnum>
669 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
670 jobnums), all provisioning jobs will have a dependancy on the supplied
671 jobnum(s) (they will not run until the specific job(s) complete(s)).
673 (TODOC: L<FS::queue> and L<freeside-queued>)
675 (TODOC: new exports!)
684 warn "[$me] insert called on $self: ". Dumper($self).
685 "\nwith options: ". Dumper(%options);
688 local $SIG{HUP} = 'IGNORE';
689 local $SIG{INT} = 'IGNORE';
690 local $SIG{QUIT} = 'IGNORE';
691 local $SIG{TERM} = 'IGNORE';
692 local $SIG{TSTP} = 'IGNORE';
693 local $SIG{PIPE} = 'IGNORE';
695 my $oldAutoCommit = $FS::UID::AutoCommit;
696 local $FS::UID::AutoCommit = 0;
700 my $error = $self->SUPER::insert( # usergroup is here
701 'jobnums' => \@jobnums,
702 'child_objects' => $self->child_objects,
706 $dbh->rollback if $oldAutoCommit;
710 unless ( $skip_fuzzyfiles ) {
711 $error = $self->queue_fuzzyfiles_update;
713 $dbh->rollback if $oldAutoCommit;
714 return "updating fuzzy search cache: $error";
718 my $cust_pkg = $self->cust_svc->cust_pkg;
721 my $cust_main = $cust_pkg->cust_main;
722 my $agentnum = $cust_main->agentnum;
724 if ( $conf->exists('emailinvoiceautoalways')
725 || $conf->exists('emailinvoiceauto')
726 && ! $cust_main->invoicing_list_emailonly
728 my @invoicing_list = $cust_main->invoicing_list;
729 push @invoicing_list, $self->email;
730 $cust_main->invoicing_list(\@invoicing_list);
733 #welcome email/letter
734 my @welcome_exclude_svcparts = $conf->config('svc_acct_welcome_exclude');
735 unless ( grep { $_ eq $self->svcpart } @welcome_exclude_svcparts ) {
736 #indent skips a level for some reason
739 my $msgnum = $conf->config('welcome_msgnum', $agentnum);
741 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
742 $error = $msg_template->send('cust_main' => $cust_main,
746 my ($to,$welcome_template,$welcome_from,$welcome_subject,$welcome_subject_template,$welcome_mimetype)
747 = ('','','','','','');
749 if ( $conf->exists('welcome_email', $agentnum) ) {
750 $welcome_template = new Text::Template (
752 SOURCE => [ map "$_\n", $conf->config('welcome_email', $agentnum) ]
753 ) or warn "can't create welcome email template: $Text::Template::ERROR";
754 $welcome_from = $conf->config('welcome_email-from', $agentnum);
755 # || 'your-isp-is-dum'
756 $welcome_subject = $conf->config('welcome_email-subject', $agentnum)
758 $welcome_subject_template = new Text::Template (
760 SOURCE => $welcome_subject,
761 ) or warn "can't create welcome email subject template: $Text::Template::ERROR";
762 $welcome_mimetype = $conf->config('welcome_email-mimetype', $agentnum)
765 if ( $welcome_template ) {
766 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
770 'custnum' => $self->custnum,
771 'username' => $self->username,
772 'password' => $self->_password,
773 'first' => $cust_main->first,
774 'last' => $cust_main->getfield('last'),
775 'pkg' => $cust_pkg->part_pkg->pkg,
777 my $wqueue = new FS::queue {
778 'svcnum' => $self->svcnum,
779 'job' => 'FS::svc_acct::send_email'
781 my $error = $wqueue->insert(
783 'from' => $welcome_from,
784 'subject' => $welcome_subject_template->fill_in( HASH => \%hash, ),
785 'mimetype' => $welcome_mimetype,
786 'body' => $welcome_template->fill_in( HASH => \%hash, ),
789 $dbh->rollback if $oldAutoCommit;
790 return "error queuing welcome email: $error";
793 if ( $options{'depend_jobnum'} ) {
794 warn "$me depend_jobnum found; adding to welcome email dependancies"
796 if ( ref($options{'depend_jobnum'}) ) {
797 warn "$me adding jobs ". join(', ', @{$options{'depend_jobnum'}} ).
798 "to welcome email dependancies"
800 push @jobnums, @{ $options{'depend_jobnum'} };
802 warn "$me adding job $options{'depend_jobnum'} ".
803 "to welcome email dependancies"
805 push @jobnums, $options{'depend_jobnum'};
809 foreach my $jobnum ( @jobnums ) {
810 my $error = $wqueue->depend_insert($jobnum);
812 $dbh->rollback if $oldAutoCommit;
813 return "error queuing welcome email job dependancy: $error";
819 } # if $welcome_template
821 # print welcome letter
822 if ($conf->exists('svc_acct_welcome_letter')) {
823 my $queue = new FS::queue {
824 'job' => 'FS::svc_acct::process_print_welcome_letter',
826 $error = $queue->insert(
827 'svcnum' => $self->svcnum,
828 'template' => 'svc_acct_welcome_letter',
831 warn "can't send welcome letter: $error";
834 #indent skipped a level for some reason
835 } # unless in @welcome_exclude_svcparts
838 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
842 # set usage fields and thresholds if unset but set in a package def
843 # AND the package already has a last bill date (otherwise they get double added)
844 sub preinsert_hook_first {
847 return '' unless $self->pkgnum;
849 my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
850 return '' unless $cust_pkg && $cust_pkg->last_bill;
852 my $part_pkg = $cust_pkg->part_pkg;
853 return '' unless $part_pkg && $part_pkg->can('usage_valuehash');
855 my %values = $part_pkg->usage_valuehash;
856 my $multiplier = $conf->exists('svc_acct-usage_threshold')
857 ? 1 - $conf->config('svc_acct-usage_threshold')/100
858 : 0.20; #doesn't matter
860 foreach ( keys %values ) {
861 next if $self->getfield($_);
862 $self->setfield( $_, $values{$_} );
863 $self->setfield( $_. '_threshold', int( $values{$_} * $multiplier ) )
864 if $conf->exists('svc_acct-usage_threshold');
872 Deletes this account from the database. If there is an error, returns the
873 error, otherwise returns false.
875 The corresponding FS::cust_svc record will be deleted as well.
877 (TODOC: new exports!)
884 return "can't delete system account" if $self->_check_system;
886 return "Can't delete an account which is a (svc_forward) source!"
887 if qsearch( 'svc_forward', { 'srcsvc' => $self->svcnum } );
889 return "Can't delete an account which is a (svc_forward) destination!"
890 if qsearch( 'svc_forward', { 'dstsvc' => $self->svcnum } );
892 return "Can't delete an account with (svc_www) web service!"
893 if qsearch( 'svc_www', { 'usersvc' => $self->svcnum } );
895 # what about records in session ? (they should refer to history table)
897 local $SIG{HUP} = 'IGNORE';
898 local $SIG{INT} = 'IGNORE';
899 local $SIG{QUIT} = 'IGNORE';
900 local $SIG{TERM} = 'IGNORE';
901 local $SIG{TSTP} = 'IGNORE';
902 local $SIG{PIPE} = 'IGNORE';
904 my $oldAutoCommit = $FS::UID::AutoCommit;
905 local $FS::UID::AutoCommit = 0;
908 foreach my $cust_main_invoice (
909 qsearch( 'cust_main_invoice', { 'dest' => $self->svcnum } )
911 unless ( defined($cust_main_invoice) ) {
912 warn "WARNING: something's wrong with qsearch";
915 my %hash = $cust_main_invoice->hash;
916 $hash{'dest'} = $self->email;
917 my $new = new FS::cust_main_invoice \%hash;
918 my $error = $new->replace($cust_main_invoice);
920 $dbh->rollback if $oldAutoCommit;
925 foreach my $svc_domain (
926 qsearch( 'svc_domain', { 'catchall' => $self->svcnum } )
928 my %hash = new FS::svc_domain->hash;
929 $hash{'catchall'} = '';
930 my $new = new FS::svc_domain \%hash;
931 my $error = $new->replace($svc_domain);
933 $dbh->rollback if $oldAutoCommit;
938 my $error = $self->SUPER::delete; # usergroup here
940 $dbh->rollback if $oldAutoCommit;
944 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
948 =item replace OLD_RECORD
950 Replaces OLD_RECORD with this one in the database. If there is an error,
951 returns the error, otherwise returns false.
953 The additional field I<usergroup> can optionally be defined; if so it should
954 contain an arrayref of group names. See L<FS::radius_usergroup>.
962 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
966 warn "$me replacing $old with $new\n" if $DEBUG;
970 return "can't modify system account" if $old->_check_system;
973 #no warnings 'numeric'; #alas, a 5.006-ism
976 foreach my $xid (qw( uid gid )) {
978 return "Can't change $xid!"
979 if ! $conf->exists("svc_acct-edit_$xid")
980 && $old->$xid() != $new->$xid()
981 && $new->cust_svc->part_svc->part_svc_column($xid)->columnflag ne 'F'
986 return "can't change username"
987 if $old->username ne $new->username
988 && $conf->exists('svc_acct-no_edit_username');
990 #change homdir when we change username
991 $new->setfield('dir', '') if $old->username ne $new->username;
993 local $SIG{HUP} = 'IGNORE';
994 local $SIG{INT} = 'IGNORE';
995 local $SIG{QUIT} = 'IGNORE';
996 local $SIG{TERM} = 'IGNORE';
997 local $SIG{TSTP} = 'IGNORE';
998 local $SIG{PIPE} = 'IGNORE';
1000 my $oldAutoCommit = $FS::UID::AutoCommit;
1001 local $FS::UID::AutoCommit = 0;
1004 $error = $new->SUPER::replace($old, @_); # usergroup here
1006 $dbh->rollback if $oldAutoCommit;
1007 return $error if $error;
1010 if ( $new->username ne $old->username && ! $skip_fuzzyfiles ) {
1011 $error = $new->queue_fuzzyfiles_update;
1013 $dbh->rollback if $oldAutoCommit;
1014 return "updating fuzzy search cache: $error";
1018 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1022 =item queue_fuzzyfiles_update
1024 Used by insert & replace to update the fuzzy search cache
1028 sub queue_fuzzyfiles_update {
1031 local $SIG{HUP} = 'IGNORE';
1032 local $SIG{INT} = 'IGNORE';
1033 local $SIG{QUIT} = 'IGNORE';
1034 local $SIG{TERM} = 'IGNORE';
1035 local $SIG{TSTP} = 'IGNORE';
1036 local $SIG{PIPE} = 'IGNORE';
1038 my $oldAutoCommit = $FS::UID::AutoCommit;
1039 local $FS::UID::AutoCommit = 0;
1042 my $queue = new FS::queue {
1043 'svcnum' => $self->svcnum,
1044 'job' => 'FS::svc_acct::append_fuzzyfiles'
1046 my $error = $queue->insert($self->username);
1048 $dbh->rollback if $oldAutoCommit;
1049 return "queueing job (transaction rolled back): $error";
1052 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1060 Suspends this account by calling export-specific suspend hooks. If there is
1061 an error, returns the error, otherwise returns false.
1063 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1069 return "can't suspend system account" if $self->_check_system;
1070 $self->SUPER::suspend(@_);
1075 Unsuspends this account by by calling export-specific suspend hooks. If there
1076 is an error, returns the error, otherwise returns false.
1078 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1084 my %hash = $self->hash;
1085 if ( $hash{_password} =~ /^\*SUSPENDED\* (.*)$/ ) {
1086 $hash{_password} = $1;
1087 my $new = new FS::svc_acct ( \%hash );
1088 my $error = $new->replace($self);
1089 return $error if $error;
1092 $self->SUPER::unsuspend(@_);
1097 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
1099 If the B<auto_unset_catchall> configuration option is set, this method will
1100 automatically remove any references to the canceled service in the catchall
1101 field of svc_domain. This allows packages that contain both a svc_domain and
1102 its catchall svc_acct to be canceled in one step.
1107 # Only one thing to do at this level
1109 foreach my $svc_domain (
1110 qsearch( 'svc_domain', { catchall => $self->svcnum } ) ) {
1111 if($conf->exists('auto_unset_catchall')) {
1112 my %hash = $svc_domain->hash;
1113 $hash{catchall} = '';
1114 my $new = new FS::svc_domain ( \%hash );
1115 my $error = $new->replace($svc_domain);
1116 return $error if $error;
1118 return "cannot unprovision svc_acct #".$self->svcnum.
1119 " while assigned as catchall for svc_domain #".$svc_domain->svcnum;
1123 $self->SUPER::cancel(@_);
1129 Checks all fields to make sure this is a valid service. If there is an error,
1130 returns the error, otherwise returns false. Called by the insert and replace
1133 Sets any fixed values; see L<FS::part_svc>.
1140 my($recref) = $self->hashref;
1142 my $x = $self->setfixed;
1143 return $x unless ref($x);
1146 my $error = $self->ut_numbern('svcnum')
1147 #|| $self->ut_number('domsvc')
1148 || $self->ut_foreign_key( 'domsvc', 'svc_domain', 'svcnum' )
1149 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
1150 || $self->ut_foreign_keyn('sectornum','tower_sector','sectornum')
1151 || $self->ut_foreign_keyn('routernum','router','routernum')
1152 || $self->ut_foreign_keyn('blocknum','addr_block','blocknum')
1153 || $self->ut_textn('sec_phrase')
1154 || $self->ut_snumbern('seconds')
1155 || $self->ut_snumbern('upbytes')
1156 || $self->ut_snumbern('downbytes')
1157 || $self->ut_snumbern('totalbytes')
1158 || $self->ut_snumbern('seconds_threshold')
1159 || $self->ut_snumbern('upbytes_threshold')
1160 || $self->ut_snumbern('downbytes_threshold')
1161 || $self->ut_snumbern('totalbytes_threshold')
1162 || $self->ut_enum('_password_encoding', ['',qw(plain crypt ldap)])
1163 || $self->ut_enum('password_selfchange', [ '', 'Y' ])
1164 || $self->ut_enum('password_recover', [ '', 'Y' ])
1166 || $self->ut_anything('cf_privatekey')
1168 || $self->ut_textn('cgp_accessmodes')
1169 || $self->ut_alphan('cgp_type')
1170 || $self->ut_textn('cgp_aliases' ) #well
1172 || $self->ut_alphasn('cgp_rulesallowed')
1173 || $self->ut_enum('cgp_rpopallowed', [ '', 'Y' ])
1174 || $self->ut_enum('cgp_mailtoall', [ '', 'Y' ])
1175 || $self->ut_enum('cgp_addmailtrailer', [ '', 'Y' ])
1176 || $self->ut_snumbern('cgp_archiveafter')
1178 || $self->ut_alphasn('cgp_deletemode')
1179 || $self->ut_enum('cgp_emptytrash', $self->cgp_emptytrash_values)
1180 || $self->ut_alphan('cgp_language')
1181 || $self->ut_textn('cgp_timezone')
1182 || $self->ut_textn('cgp_skinname')
1183 || $self->ut_textn('cgp_prontoskinname')
1184 || $self->ut_alphan('cgp_sendmdnmode')
1186 return $error if $error;
1188 # assign IP address, etc.
1189 if ( $conf->exists('svc_acct-ip_addr') ) {
1190 my $error = $self->svc_ip_check;
1191 return $error if $error;
1192 } else { # I think this is correct
1193 $self->routernum('');
1194 $self->blocknum('');
1198 local $username_letter = $username_letter;
1199 local $username_uppercase = $username_uppercase;
1200 if ($self->svcnum) {
1201 my $cust_svc = $self->cust_svc
1202 or return "no cust_svc record found for svcnum ". $self->svcnum;
1203 my $cust_pkg = $cust_svc->cust_pkg;
1205 if ($self->pkgnum) {
1206 $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $self->pkgnum } );#complain?
1210 $conf->exists('username-letter', $cust_pkg->cust_main->agentnum);
1211 $username_uppercase =
1212 $conf->exists('username-uppercase', $cust_pkg->cust_main->agentnum);
1215 my $ulen = $usernamemax || $self->dbdef_table->column('username')->length;
1217 $recref->{username} =~ /^([a-z0-9_\-\.\&\%\:\/\=\#\!]{$usernamemin,$ulen})$/i
1218 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
1219 $recref->{username} = $1;
1221 my $uerror = gettext('illegal_username'). ': '. $recref->{username};
1223 unless ( $username_uppercase ) {
1224 $recref->{username} =~ /[A-Z]/ and return $uerror;
1226 if ( $username_letterfirst ) {
1227 $recref->{username} =~ /^[a-z]/ or return $uerror;
1228 } elsif ( $username_letter ) {
1229 $recref->{username} =~ /[a-z]/ or return $uerror;
1231 if ( $username_noperiod ) {
1232 $recref->{username} =~ /\./ and return $uerror;
1234 if ( $username_nounderscore ) {
1235 $recref->{username} =~ /_/ and return $uerror;
1237 if ( $username_nodash ) {
1238 $recref->{username} =~ /\-/ and return $uerror;
1240 unless ( $username_ampersand ) {
1241 $recref->{username} =~ /\&/ and return $uerror;
1243 unless ( $username_percent ) {
1244 $recref->{username} =~ /\%/ and return $uerror;
1246 unless ( $username_colon ) {
1247 $recref->{username} =~ /\:/ and return $uerror;
1249 unless ( $username_slash ) {
1250 $recref->{username} =~ /\// and return $uerror;
1252 unless ( $username_equals ) {
1253 $recref->{username} =~ /\=/ and return $uerror;
1255 unless ( $username_pound ) {
1256 $recref->{username} =~ /\#/ and return $uerror;
1258 unless ( $username_exclamation ) {
1259 $recref->{username} =~ /\!/ and return $uerror;
1263 $recref->{popnum} =~ /^(\d*)$/ or return "Illegal popnum: ".$recref->{popnum};
1264 $recref->{popnum} = $1;
1265 return "Unknown popnum" unless
1266 ! $recref->{popnum} ||
1267 qsearchs('svc_acct_pop',{'popnum'=> $recref->{popnum} } );
1269 unless ( $part_svc->part_svc_column('uid')->columnflag eq 'F' ) {
1271 $recref->{uid} =~ /^(\d*)$/ or return "Illegal uid";
1272 $recref->{uid} = $1 eq '' ? $self->unique('uid') : $1;
1274 $recref->{gid} =~ /^(\d*)$/ or return "Illegal gid";
1275 $recref->{gid} = $1 eq '' ? $recref->{uid} : $1;
1276 #not all systems use gid=uid
1277 #you can set a fixed gid in part_svc
1279 return "Only root can have uid 0"
1280 if $recref->{uid} == 0
1281 && $recref->{username} !~ /^(root|toor|smtp)$/;
1283 unless ( $recref->{username} eq 'sync' ) {
1284 if ( grep $_ eq $recref->{shell}, @shells ) {
1285 $recref->{shell} = (grep $_ eq $recref->{shell}, @shells)[0];
1287 return "Illegal shell \`". $self->shell. "\'; ".
1288 "shells configuration value contains: @shells";
1291 $recref->{shell} = '/bin/sync';
1295 $recref->{gid} ne '' ?
1296 return "Can't have gid without uid" : ( $recref->{gid}='' );
1297 #$recref->{dir} ne '' ?
1298 # return "Can't have directory without uid" : ( $recref->{dir}='' );
1299 $recref->{shell} ne '' ?
1300 return "Can't have shell without uid" : ( $recref->{shell}='' );
1303 unless ( $part_svc->part_svc_column('dir')->columnflag eq 'F' ) {
1305 $recref->{dir} =~ /^([\/\w\-\.\&\:\#]*)$/
1306 or return "Illegal directory: ". $recref->{dir};
1307 $recref->{dir} = $1;
1308 return "Illegal directory"
1309 if $recref->{dir} =~ /(^|\/)\.+(\/|$)/; #no .. component
1310 return "Illegal directory"
1311 if $recref->{dir} =~ /\&/ && ! $username_ampersand;
1312 unless ( $recref->{dir} ) {
1313 $recref->{dir} = $dir_prefix . '/';
1314 if ( $dirhash > 0 ) {
1315 for my $h ( 1 .. $dirhash ) {
1316 $recref->{dir} .= substr($recref->{username}, $h-1, 1). '/';
1318 } elsif ( $dirhash < 0 ) {
1319 for my $h ( reverse $dirhash .. -1 ) {
1320 $recref->{dir} .= substr($recref->{username}, $h, 1). '/';
1323 $recref->{dir} .= $recref->{username};
1329 if ( $self->getfield('finger') eq '' ) {
1330 my $cust_pkg = $self->svcnum
1331 ? $self->cust_svc->cust_pkg
1332 : qsearchs('cust_pkg', { 'pkgnum' => $self->getfield('pkgnum') } );
1334 my $cust_main = $cust_pkg->cust_main;
1335 $self->setfield('finger', $cust_main->first.' '.$cust_main->get('last') );
1338 # $error = $self->ut_textn('finger');
1339 # return $error if $error;
1340 $self->getfield('finger') =~ /^([\w \,\.\-\'\&\t\!\@\#\$\%\(\)\+\;\"\?\/\*\<\>]*)$/
1341 or return "Illegal finger: ". $self->getfield('finger');
1342 $self->setfield('finger', $1);
1344 for (qw( quota file_quota file_maxsize )) {
1345 $recref->{$_} =~ /^(\w*)$/ or return "Illegal $_";
1348 $recref->{file_maxnum} =~ /^\s*(\d*)\s*$/ or return "Illegal file_maxnum";
1349 $recref->{file_maxnum} = $1;
1351 unless ( $part_svc->part_svc_column('slipip')->columnflag eq 'F' ) {
1352 if ( $recref->{slipip} eq '' ) {
1353 $recref->{slipip} = ''; # eh?
1354 } elsif ( $recref->{slipip} eq '0e0' ) {
1355 $recref->{slipip} = '0e0';
1357 $recref->{slipip} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/
1358 or return "Illegal slipip: ". $self->slipip;
1359 $recref->{slipip} = $1;
1363 #arbitrary RADIUS stuff; allow ut_textn for now
1364 foreach ( grep /^radius_/, fields('svc_acct') ) {
1365 $self->ut_textn($_);
1368 # First, if _password is blank, generate one and set default encoding.
1369 if ( ! $recref->{_password} ) {
1370 $error = $self->set_password('');
1372 # But if there's a _password but no encoding, assume it's plaintext and
1373 # set it to default encoding.
1374 elsif ( ! $recref->{_password_encoding} ) {
1375 $error = $self->set_password($recref->{_password});
1377 return $error if $error;
1379 # Next, check _password to ensure compliance with the encoding.
1380 if ( $recref->{_password_encoding} eq 'ldap' ) {
1382 if ( $recref->{_password} =~ /^(\{[\w\-]+\})(!?.{0,64})$/ ) {
1383 $recref->{_password} = uc($1).$2;
1385 return 'Illegal (ldap-encoded) password: '. $recref->{_password};
1388 } elsif ( $recref->{_password_encoding} eq 'crypt' ) {
1390 if ( $recref->{_password} =~
1391 #/^(\$\w+\$.*|[\w\+\/]{13}|_[\w\+\/]{19}|\*)$/
1392 /^(!!?)?(\$\w+\$.*|[\w\+\/\.]{13}|_[\w\+\/\.]{19}|\*)$/
1395 $recref->{_password} = ( defined($1) ? $1 : '' ). $2;
1398 return 'Illegal (crypt-encoded) password: '. $recref->{_password};
1401 } elsif ( $recref->{_password_encoding} eq 'plain' ) {
1402 # Password randomization is now in set_password.
1403 # Strip whitespace characters, check length requirements, etc.
1404 if ( $recref->{_password} =~ /^([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1405 $recref->{_password} = $1;
1407 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1408 FS::Msgcat::_gettext('illegal_password_characters').
1409 ": ". $recref->{_password};
1412 if ( $password_noampersand ) {
1413 $recref->{_password} =~ /\&/ and return gettext('illegal_password');
1415 if ( $password_noexclamation ) {
1416 $recref->{_password} =~ /\!/ and return gettext('illegal_password');
1420 return "invalid password encoding ('".$recref->{_password_encoding}."'";
1423 $self->SUPER::check;
1428 sub _password_encryption {
1430 my $encoding = lc($self->_password_encoding);
1431 return if !$encoding;
1432 return 'plain' if $encoding eq 'plain';
1433 if($encoding eq 'crypt') {
1434 my $pass = $self->_password;
1435 $pass =~ s/^\*SUSPENDED\* //;
1437 return 'md5' if $pass =~ /^\$1\$/;
1438 #return 'blowfish' if $self->_password =~ /^\$2\$/;
1439 return 'des' if length($pass) == 13;
1442 if($encoding eq 'ldap') {
1443 uc($self->_password) =~ /^\{([\w-]+)\}/;
1444 return 'crypt' if $1 eq 'CRYPT' or $1 eq 'DES';
1445 return 'plain' if $1 eq 'PLAIN' or $1 eq 'CLEARTEXT';
1446 return 'md5' if $1 eq 'MD5';
1447 return 'sha1' if $1 eq 'SHA' or $1 eq 'SHA-1';
1454 sub get_cleartext_password {
1456 if($self->_password_encryption eq 'plain') {
1457 if($self->_password_encoding eq 'ldap') {
1458 $self->_password =~ /\{\w+\}(.*)$/;
1462 return $self->_password;
1471 Set the cleartext password for the account. If _password_encoding is set, the
1472 new password will be encoded according to the existing method (including
1473 encryption mode, if it can be determined). Otherwise,
1474 config('default-password-encoding') is used.
1476 If no password is supplied (or a zero-length password when minimum password length
1477 is >0), one will be generated randomly.
1482 my( $self, $pass ) = ( shift, shift );
1484 warn "[$me] set_password (to $pass) called on $self: ". Dumper($self)
1487 my $failure = gettext('illegal_password'). " $passwordmin-$passwordmax ".
1488 FS::Msgcat::_gettext('illegal_password_characters').
1491 my( $encoding, $encryption ) = ('', '');
1493 if ( $self->_password_encoding ) {
1494 $encoding = $self->_password_encoding;
1495 # identify existing encryption method, try to use it.
1496 $encryption = $self->_password_encryption;
1498 # use the system default
1504 # set encoding to system default
1505 ($encoding, $encryption) =
1506 split(/-/, lc($conf->config('default-password-encoding') || ''));
1507 $encoding ||= 'legacy';
1508 $self->_password_encoding($encoding);
1511 if ( $encoding eq 'legacy' ) {
1513 # The legacy behavior from check():
1514 # If the password is blank, randomize it and set encoding to 'plain'.
1515 if(!defined($pass) or (length($pass) == 0 and $passwordmin)) {
1516 $pass = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1517 $self->_password_encoding('plain');
1519 # Prefix + valid-length password
1520 if ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1522 $self->_password_encoding('plain');
1523 # Prefix + crypt string
1524 } elsif ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([\w\.\/\$\;\+]{13,64})$/ ) {
1526 $self->_password_encoding('crypt');
1527 # Various disabled crypt passwords
1528 } elsif ( $pass eq '*' || $pass eq '!' || $pass eq '!!' ) {
1529 $self->_password_encoding('crypt');
1535 $self->_password($pass);
1541 if $passwordmin && length($pass) < $passwordmin
1542 or $passwordmax && length($pass) > $passwordmax;
1544 if ( $encoding eq 'crypt' ) {
1545 if ($encryption eq 'md5') {
1546 $pass = unix_md5_crypt($pass);
1547 } elsif ($encryption eq 'des') {
1548 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1551 } elsif ( $encoding eq 'ldap' ) {
1552 if ($encryption eq 'md5') {
1553 $pass = md5_base64($pass);
1554 } elsif ($encryption eq 'sha1') {
1555 $pass = sha1_base64($pass);
1556 } elsif ($encryption eq 'crypt') {
1557 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1559 # else $encryption eq 'plain', do nothing
1560 $pass .= '=' x (4 - length($pass) % 4) #properly padded base64
1561 if $encryption eq 'md5' || $encryption eq 'sha1';
1562 $pass = '{'.uc($encryption).'}'.$pass;
1564 # else encoding eq 'plain'
1566 $self->_password($pass);
1572 Internal function to check the username against the list of system usernames
1573 from the I<system_usernames> configuration value. Returns true if the username
1574 is listed on the system username list.
1580 scalar( grep { $self->username eq $_ || $self->email eq $_ }
1581 $conf->config('system_usernames')
1585 =item _check_duplicate
1587 Internal method to check for duplicates usernames, username@domain pairs and
1590 If the I<global_unique-username> configuration value is set to B<username> or
1591 B<username@domain>, enforces global username or username@domain uniqueness.
1593 In all cases, check for duplicate uids and usernames or username@domain pairs
1594 per export and with identical I<svcpart> values.
1598 sub _check_duplicate {
1601 my $global_unique = $conf->config('global_unique-username') || 'none';
1602 return '' if $global_unique eq 'disabled';
1606 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
1607 unless ( $part_svc ) {
1608 return 'unknown svcpart '. $self->svcpart;
1611 my @dup_user = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1612 qsearch( 'svc_acct', { 'username' => $self->username } );
1613 return gettext('username_in_use')
1614 if $global_unique eq 'username' && @dup_user;
1616 my @dup_userdomain = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1617 qsearch( 'svc_acct', { 'username' => $self->username,
1618 'domsvc' => $self->domsvc } );
1619 return gettext('username_in_use')
1620 if $global_unique eq 'username@domain' && @dup_userdomain;
1623 if ( $part_svc->part_svc_column('uid')->columnflag ne 'F'
1624 && $self->username !~ /^(toor|(hyla)?fax)$/ ) {
1625 @dup_uid = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1626 qsearch( 'svc_acct', { 'uid' => $self->uid } );
1631 if ( @dup_user || @dup_userdomain || @dup_uid ) {
1632 my $exports = FS::part_export::export_info('svc_acct');
1633 my %conflict_user_svcpart;
1634 my %conflict_userdomain_svcpart = ( $self->svcpart => 'SELF', );
1636 foreach my $part_export ( $part_svc->part_export ) {
1638 #this will catch to the same exact export
1639 my @svcparts = map { $_->svcpart } $part_export->export_svc;
1641 #this will catch to exports w/same exporthost+type ???
1642 #my @other_part_export = qsearch('part_export', {
1643 # 'machine' => $part_export->machine,
1644 # 'exporttype' => $part_export->exporttype,
1646 #foreach my $other_part_export ( @other_part_export ) {
1647 # push @svcparts, map { $_->svcpart }
1648 # qsearch('export_svc', { 'exportnum' => $part_export->exportnum });
1651 #my $nodomain = $exports->{$part_export->exporttype}{'nodomain'};
1652 #silly kludge to avoid uninitialized value errors
1653 my $nodomain = exists( $exports->{$part_export->exporttype}{'nodomain'} )
1654 ? $exports->{$part_export->exporttype}{'nodomain'}
1656 if ( $nodomain =~ /^Y/i ) {
1657 $conflict_user_svcpart{$_} = $part_export->exportnum
1660 $conflict_userdomain_svcpart{$_} = $part_export->exportnum
1665 foreach my $dup_user ( @dup_user ) {
1666 my $dup_svcpart = $dup_user->cust_svc->svcpart;
1667 if ( exists($conflict_user_svcpart{$dup_svcpart}) ) {
1668 return "duplicate username ". $self->username.
1669 ": conflicts with svcnum ". $dup_user->svcnum.
1670 " via exportnum ". $conflict_user_svcpart{$dup_svcpart};
1674 foreach my $dup_userdomain ( @dup_userdomain ) {
1675 my $dup_svcpart = $dup_userdomain->cust_svc->svcpart;
1676 if ( exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1677 return "duplicate username\@domain ". $self->email.
1678 ": conflicts with svcnum ". $dup_userdomain->svcnum.
1679 " via exportnum ". $conflict_userdomain_svcpart{$dup_svcpart};
1683 foreach my $dup_uid ( @dup_uid ) {
1684 my $dup_svcpart = $dup_uid->cust_svc->svcpart;
1685 if ( exists($conflict_user_svcpart{$dup_svcpart})
1686 || exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1687 return "duplicate uid ". $self->uid.
1688 ": conflicts with svcnum ". $dup_uid->svcnum.
1690 ( $conflict_user_svcpart{$dup_svcpart}
1691 || $conflict_userdomain_svcpart{$dup_svcpart} );
1703 Depriciated, use radius_reply instead.
1708 carp "FS::svc_acct::radius depriciated, use radius_reply";
1709 $_[0]->radius_reply;
1714 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1715 reply attributes of this record.
1717 Note that this is now the preferred method for reading RADIUS attributes -
1718 accessing the columns directly is discouraged, as the column names are
1719 expected to change in the future.
1726 return %{ $self->{'radius_reply'} }
1727 if exists $self->{'radius_reply'};
1732 my($column, $attrib) = ($1, $2);
1733 #$attrib =~ s/_/\-/g;
1734 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1735 } grep { /^radius_/ && $self->getfield($_) } fields( $self->table );
1737 if ( $self->slipip && $self->slipip ne '0e0' ) {
1738 $reply{$radius_ip} = $self->slipip;
1741 if ( $self->seconds !~ /^$/ ) {
1742 $reply{'Session-Timeout'} = $self->seconds;
1745 if ( $conf->exists('radius-chillispot-max') ) {
1746 #http://dev.coova.org/svn/coova-chilli/doc/dictionary.chillispot
1748 #hmm. just because sqlradius.pm says so?
1755 foreach my $what (qw( input output total )) {
1756 my $is = $whatis{$what}.'bytes';
1757 if ( $self->$is() =~ /\d/ ) {
1758 my $big = new Math::BigInt $self->$is();
1759 $big = new Math::BigInt '0' if $big->is_neg();
1760 my $att = "Chillispot-Max-\u$what";
1761 $reply{"$att-Octets"} = $big->copy->band(0xffffffff)->bstr;
1762 $reply{"$att-Gigawords"} = $big->copy->brsft(32)->bstr;
1773 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1774 check attributes of this record.
1776 Note that this is now the preferred method for reading RADIUS attributes -
1777 accessing the columns directly is discouraged, as the column names are
1778 expected to change in the future.
1785 return %{ $self->{'radius_check'} }
1786 if exists $self->{'radius_check'};
1791 my($column, $attrib) = ($1, $2);
1792 #$attrib =~ s/_/\-/g;
1793 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1794 } grep { /^rc_/ && $self->getfield($_) } fields( $self->table );
1797 my($pw_attrib, $password) = $self->radius_password;
1798 $check{$pw_attrib} = $password;
1800 my $cust_svc = $self->cust_svc;
1802 my $cust_pkg = $cust_svc->cust_pkg;
1803 if ( $cust_pkg && $cust_pkg->part_pkg->is_prepaid && $cust_pkg->bill ) {
1804 $check{'Expiration'} = time2str('%B %e %Y %T', $cust_pkg->bill ); #http://lists.cistron.nl/pipermail/freeradius-users/2005-January/040184.html
1807 warn "WARNING: no cust_svc record for svc_acct.svcnum ". $self->svcnum.
1808 "; can't set Expiration\n"
1816 =item radius_password
1818 Returns a key/value pair containing the RADIUS attribute name and value
1823 sub radius_password {
1827 if ( $self->_password_encoding eq 'ldap' ) {
1828 $pw_attrib = 'Password-With-Header';
1829 } elsif ( $self->_password_encoding eq 'crypt' ) {
1830 $pw_attrib = 'Crypt-Password';
1831 } elsif ( $self->_password_encoding eq 'plain' ) {
1832 $pw_attrib = $radius_password;
1834 $pw_attrib = length($self->_password) <= 12
1839 ($pw_attrib, $self->_password);
1845 This method instructs the object to "snapshot" or freeze RADIUS check and
1846 reply attributes to the current values.
1850 #bah, my english is too broken this morning
1851 #Of note is the "Expiration" attribute, which, for accounts in prepaid packages, is typically defined on-the-fly as the associated packages cust_pkg.bill. (This is used by
1852 #the FS::cust_pkg's replace method to trigger the correct export updates when
1853 #package dates change)
1858 $self->{$_} = { $self->$_() }
1859 foreach qw( radius_reply radius_check );
1863 =item forget_snapshot
1865 This methos instructs the object to forget any previously snapshotted
1866 RADIUS check and reply attributes.
1870 sub forget_snapshot {
1874 foreach qw( radius_reply radius_check );
1878 =item domain [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1880 Returns the domain associated with this account.
1882 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1889 die "svc_acct.domsvc is null for svcnum ". $self->svcnum unless $self->domsvc;
1890 my $svc_domain = $self->svc_domain(@_)
1891 or die "no svc_domain.svcnum for svc_acct.domsvc ". $self->domsvc;
1892 $svc_domain->domain;
1897 Returns the FS::cust_svc record for this account (see L<FS::cust_svc>).
1901 #inherited from svc_Common
1903 =item email [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1905 Returns an email address associated with the account.
1907 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1914 $self->username. '@'. $self->domain(@_);
1920 Returns an array of FS::acct_snarf records associated with the account.
1924 # unused as originally intended, but now by Communigate Pro "RPOP"
1928 'table' => 'acct_snarf',
1929 'hashref' => { 'svcnum' => $self->svcnum },
1930 #'order_by' => 'ORDER BY priority ASC',
1934 =item cgp_rpop_hashref
1936 Returns an arrayref of RPOP data suitable for Communigate Pro API commands.
1940 sub cgp_rpop_hashref {
1942 { map { $_->snarfname => $_->cgp_hashref } $self->acct_snarf };
1945 =item decrement_upbytes OCTETS
1947 Decrements the I<upbytes> field of this record by the given amount. If there
1948 is an error, returns the error, otherwise returns false.
1952 sub decrement_upbytes {
1953 shift->_op_usage('-', 'upbytes', @_);
1956 =item increment_upbytes OCTETS
1958 Increments the I<upbytes> field of this record by the given amount. If there
1959 is an error, returns the error, otherwise returns false.
1963 sub increment_upbytes {
1964 shift->_op_usage('+', 'upbytes', @_);
1967 =item decrement_downbytes OCTETS
1969 Decrements the I<downbytes> field of this record by the given amount. If there
1970 is an error, returns the error, otherwise returns false.
1974 sub decrement_downbytes {
1975 shift->_op_usage('-', 'downbytes', @_);
1978 =item increment_downbytes OCTETS
1980 Increments the I<downbytes> field of this record by the given amount. If there
1981 is an error, returns the error, otherwise returns false.
1985 sub increment_downbytes {
1986 shift->_op_usage('+', 'downbytes', @_);
1989 =item decrement_totalbytes OCTETS
1991 Decrements the I<totalbytes> field of this record by the given amount. If there
1992 is an error, returns the error, otherwise returns false.
1996 sub decrement_totalbytes {
1997 shift->_op_usage('-', 'totalbytes', @_);
2000 =item increment_totalbytes OCTETS
2002 Increments the I<totalbytes> field of this record by the given amount. If there
2003 is an error, returns the error, otherwise returns false.
2007 sub increment_totalbytes {
2008 shift->_op_usage('+', 'totalbytes', @_);
2011 =item decrement_seconds SECONDS
2013 Decrements the I<seconds> field of this record by the given amount. If there
2014 is an error, returns the error, otherwise returns false.
2018 sub decrement_seconds {
2019 shift->_op_usage('-', 'seconds', @_);
2022 =item increment_seconds SECONDS
2024 Increments the I<seconds> field of this record by the given amount. If there
2025 is an error, returns the error, otherwise returns false.
2029 sub increment_seconds {
2030 shift->_op_usage('+', 'seconds', @_);
2038 my %op2condition = (
2039 '-' => sub { my($self, $column, $amount) = @_;
2040 $self->$column - $amount <= 0;
2042 '+' => sub { my($self, $column, $amount) = @_;
2043 ($self->$column || 0) + $amount > 0;
2046 my %op2warncondition = (
2047 '-' => sub { my($self, $column, $amount) = @_;
2048 my $threshold = $column . '_threshold';
2049 $self->$column - $amount <= $self->$threshold + 0;
2051 '+' => sub { my($self, $column, $amount) = @_;
2052 ($self->$column || 0) + $amount > 0;
2057 my( $self, $op, $column, $amount ) = @_;
2059 warn "$me _op_usage called for $column on svcnum ". $self->svcnum.
2060 ' ('. $self->email. "): $op $amount\n"
2063 return '' unless $amount;
2065 local $SIG{HUP} = 'IGNORE';
2066 local $SIG{INT} = 'IGNORE';
2067 local $SIG{QUIT} = 'IGNORE';
2068 local $SIG{TERM} = 'IGNORE';
2069 local $SIG{TSTP} = 'IGNORE';
2070 local $SIG{PIPE} = 'IGNORE';
2072 my $oldAutoCommit = $FS::UID::AutoCommit;
2073 local $FS::UID::AutoCommit = 0;
2076 my $sql = "UPDATE svc_acct SET $column = ".
2077 " CASE WHEN $column IS NULL THEN 0 ELSE $column END ". #$column||0
2078 " $op ? WHERE svcnum = ?";
2082 my $sth = $dbh->prepare( $sql )
2083 or die "Error preparing $sql: ". $dbh->errstr;
2084 my $rv = $sth->execute($amount, $self->svcnum);
2085 die "Error executing $sql: ". $sth->errstr
2086 unless defined($rv);
2087 die "Can't update $column for svcnum". $self->svcnum
2090 #$self->snapshot; #not necessary, we retain the old values
2091 #create an object with the updated usage values
2092 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2094 my $error = $new->replace($self);
2096 $dbh->rollback if $oldAutoCommit;
2097 return "Error replacing: $error";
2100 #overlimit_action eq 'cancel' handling
2101 my $cust_pkg = $self->cust_svc->cust_pkg;
2103 && $cust_pkg->part_pkg->option('overlimit_action', 1) eq 'cancel'
2104 && $op eq '-' && &{$op2condition{$op}}($self, $column, $amount)
2108 my $error = $cust_pkg->cancel; #XXX should have a reason
2110 $dbh->rollback if $oldAutoCommit;
2111 return "Error cancelling: $error";
2114 #nothing else is relevant if we're cancelling, so commit & return success
2115 warn "$me update successful; committing\n"
2117 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2122 my $action = $op2action{$op};
2124 if ( &{$op2condition{$op}}($self, $column, $amount) &&
2125 ( $action eq 'suspend' && !$self->overlimit
2126 || $action eq 'unsuspend' && $self->overlimit )
2129 my $error = $self->_op_overlimit($action);
2131 $dbh->rollback if $oldAutoCommit;
2137 if ( $conf->exists("svc_acct-usage_$action")
2138 && &{$op2condition{$op}}($self, $column, $amount) ) {
2139 #my $error = $self->$action();
2140 my $error = $self->cust_svc->cust_pkg->$action();
2141 # $error ||= $self->overlimit($action);
2143 $dbh->rollback if $oldAutoCommit;
2144 return "Error ${action}ing: $error";
2148 if ($warning_template && &{$op2warncondition{$op}}($self, $column, $amount)) {
2149 my $wqueue = new FS::queue {
2150 'svcnum' => $self->svcnum,
2151 'job' => 'FS::svc_acct::reached_threshold',
2156 $to = $warning_cc if &{$op2condition{$op}}($self, $column, $amount);
2160 my $error = $wqueue->insert(
2161 'svcnum' => $self->svcnum,
2163 'column' => $column,
2167 $dbh->rollback if $oldAutoCommit;
2168 return "Error queuing threshold activity: $error";
2172 warn "$me update successful; committing\n"
2174 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2180 my( $self, $action ) = @_;
2182 local $SIG{HUP} = 'IGNORE';
2183 local $SIG{INT} = 'IGNORE';
2184 local $SIG{QUIT} = 'IGNORE';
2185 local $SIG{TERM} = 'IGNORE';
2186 local $SIG{TSTP} = 'IGNORE';
2187 local $SIG{PIPE} = 'IGNORE';
2189 my $oldAutoCommit = $FS::UID::AutoCommit;
2190 local $FS::UID::AutoCommit = 0;
2193 my $cust_pkg = $self->cust_svc->cust_pkg;
2195 my @conf_overlimit =
2197 ? $conf->config('overlimit_groups', $cust_pkg->cust_main->agentnum )
2198 : $conf->config('overlimit_groups');
2200 foreach my $part_export ( $self->cust_svc->part_svc->part_export ) {
2202 my @groups = scalar(@conf_overlimit) ? @conf_overlimit
2203 : split(' ',$part_export->option('overlimit_groups'));
2204 next unless scalar(@groups);
2206 my $other = new FS::svc_acct $self->hashref;
2207 $other->usergroup(\@groups);
2210 if ($action eq 'suspend') {
2213 } else { # $action eq 'unsuspend'
2218 my $error = $part_export->export_replace($new, $old)
2219 || $self->overlimit($action);
2222 $dbh->rollback if $oldAutoCommit;
2223 return "Error replacing radius groups: $error";
2228 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2234 my( $self, $valueref, %options ) = @_;
2236 warn "$me set_usage called for svcnum ". $self->svcnum.
2237 ' ('. $self->email. "): ".
2238 join(', ', map { "$_ => " . $valueref->{$_}} keys %$valueref) . "\n"
2241 local $SIG{HUP} = 'IGNORE';
2242 local $SIG{INT} = 'IGNORE';
2243 local $SIG{QUIT} = 'IGNORE';
2244 local $SIG{TERM} = 'IGNORE';
2245 local $SIG{TSTP} = 'IGNORE';
2246 local $SIG{PIPE} = 'IGNORE';
2248 local $FS::svc_Common::noexport_hack = 1;
2249 my $oldAutoCommit = $FS::UID::AutoCommit;
2250 local $FS::UID::AutoCommit = 0;
2255 if ( $options{null} ) {
2256 %handyhash = ( map { ( $_ => undef, $_."_threshold" => undef ) }
2257 qw( seconds upbytes downbytes totalbytes )
2260 foreach my $field (keys %$valueref){
2261 $reset = 1 if $valueref->{$field};
2262 $self->setfield($field, $valueref->{$field});
2263 $self->setfield( $field.'_threshold',
2264 int($self->getfield($field)
2265 * ( $conf->exists('svc_acct-usage_threshold')
2266 ? 1 - $conf->config('svc_acct-usage_threshold')/100
2271 $handyhash{$field} = $self->getfield($field);
2272 $handyhash{$field.'_threshold'} = $self->getfield($field.'_threshold');
2274 #my $error = $self->replace; #NO! we avoid the call to ->check for
2275 #die $error if $error; #services not explicity changed via the UI
2277 my $sql = "UPDATE svc_acct SET " .
2278 join (',', map { "$_ = ?" } (keys %handyhash) ).
2279 " WHERE svcnum = ". $self->svcnum;
2284 if (scalar(keys %handyhash)) {
2285 my $sth = $dbh->prepare( $sql )
2286 or die "Error preparing $sql: ". $dbh->errstr;
2287 my $rv = $sth->execute(values %handyhash);
2288 die "Error executing $sql: ". $sth->errstr
2289 unless defined($rv);
2290 die "Can't update usage for svcnum ". $self->svcnum
2294 #$self->snapshot; #not necessary, we retain the old values
2295 #create an object with the updated usage values
2296 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2297 local($FS::Record::nowarn_identical) = 1;
2298 my $error = $new->replace($self); #call exports
2300 $dbh->rollback if $oldAutoCommit;
2301 return "Error replacing: $error";
2308 $error = $self->_op_overlimit('unsuspend')
2309 if $self->overlimit;;
2311 $error ||= $self->cust_svc->cust_pkg->unsuspend
2312 if $conf->exists("svc_acct-usage_unsuspend");
2315 $dbh->rollback if $oldAutoCommit;
2316 return "Error unsuspending: $error";
2321 warn "$me update successful; committing\n"
2323 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2329 =item recharge HASHREF
2331 Increments usage columns by the amount specified in HASHREF as
2332 column=>amount pairs.
2337 my ($self, $vhash) = @_;
2340 warn "[$me] recharge called on $self: ". Dumper($self).
2341 "\nwith vhash: ". Dumper($vhash);
2344 my $oldAutoCommit = $FS::UID::AutoCommit;
2345 local $FS::UID::AutoCommit = 0;
2349 foreach my $column (keys %$vhash){
2350 $error ||= $self->_op_usage('+', $column, $vhash->{$column});
2354 $dbh->rollback if $oldAutoCommit;
2356 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2361 =item is_rechargeable
2363 Returns true if this svc_account can be "recharged" and false otherwise.
2367 sub is_rechargable {
2369 $self->seconds ne ''
2370 || $self->upbytes ne ''
2371 || $self->downbytes ne ''
2372 || $self->totalbytes ne '';
2375 =item seconds_since TIMESTAMP
2377 Returns the number of seconds this account has been online since TIMESTAMP,
2378 according to the session monitor (see L<FS::Session>).
2380 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2381 L<Time::Local> and L<Date::Parse> for conversion functions.
2385 #note: POD here, implementation in FS::cust_svc
2388 $self->cust_svc->seconds_since(@_);
2391 =item last_login_text
2393 Returns text describing the time of last login.
2397 sub last_login_text {
2399 $self->last_login ? ctime($self->last_login) : 'unknown';
2402 =item psearch_cdrs OPTIONS
2404 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records
2405 associated with this service. For svc_acct, "associated with" means that
2406 either the "src" or the "charged_party" field of the CDR matches the
2407 "username" field of the service.
2412 my($self, %options) = @_;
2417 my $did = dbh->quote($self->username);
2419 my $prefix = $options{'default_prefix'} || ''; #convergent.au '+61'
2420 my $prefixdid = dbh->quote($prefix . $self->username);
2422 my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
2424 if ( $options{inbound} ) {
2425 # these will be selected under their DIDs
2426 push @where, "FALSE";
2430 if (!$options{'disable_charged_party'}) {
2432 "charged_party = $did",
2433 "charged_party = $prefixdid";
2435 if (!$options{'disable_src'}) {
2437 "src = $did AND charged_party IS NULL",
2438 "src = $prefixdid AND charged_party IS NULL";
2440 push @where, '(' . join(' OR ', @orwhere) . ')';
2442 # $options{'status'} = '' is meaningful; for the rest of them it's not
2443 if ( exists $options{'status'} ) {
2444 $hash{'freesidestatus'} = $options{'status'};
2446 if ( $options{'cdrtypenum'} ) {
2447 $hash{'cdrtypenum'} = $options{'cdrtypenum'};
2449 if ( $options{'calltypenum'} ) {
2450 $hash{'calltypenum'} = $options{'calltypenum'};
2452 if ( $options{'begin'} ) {
2453 push @where, 'startdate >= '. $options{'begin'};
2455 if ( $options{'end'} ) {
2456 push @where, 'startdate < '. $options{'end'};
2458 if ( $options{'nonzero'} ) {
2459 push @where, 'duration > 0';
2462 my $extra_sql = join(' AND ', @where);
2465 $extra_sql = " AND ".$extra_sql;
2467 $extra_sql = " WHERE ".$extra_sql;
2473 'hashref' => \%hash,
2474 'extra_sql' => $extra_sql,
2475 'order_by' => "ORDER BY startdate $for_update",
2479 =item get_cdrs (DEPRECATED)
2481 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a
2482 single list. Arguments are the same as for psearch_cdrs.
2488 my $psearch = $self->psearch_cdrs(@_);
2489 qsearch ( $psearch->{query} )
2492 # sub radius_groups has moved to svc_Radius_Mixin
2494 =item clone_suspended
2496 Constructor used by FS::part_export::_export_suspend fallback. Document
2501 sub clone_suspended {
2503 my %hash = $self->hash;
2504 $hash{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
2505 new FS::svc_acct \%hash;
2508 =item clone_kludge_unsuspend
2510 Constructor used by FS::part_export::_export_unsuspend fallback. Document
2515 sub clone_kludge_unsuspend {
2517 my %hash = $self->hash;
2518 $hash{_password} = '';
2519 new FS::svc_acct \%hash;
2522 =item check_password
2524 Checks the supplied password against the (possibly encrypted) password in the
2525 database. Returns true for a successful authentication, false for no match.
2527 Currently supported encryptions are: classic DES crypt() and MD5
2531 sub check_password {
2532 my($self, $check_password) = @_;
2534 #remove old-style SUSPENDED kludge, they should be allowed to login to
2535 #self-service and pay up
2536 ( my $password = $self->_password ) =~ s/^\*SUSPENDED\* //;
2538 if ( $self->_password_encoding eq 'ldap' ) {
2540 $password =~ s/^{PLAIN}/{CLEARTEXT}/;
2541 my $auth = from_rfc2307 Authen::Passphrase $password;
2542 return $auth->match($check_password);
2544 } elsif ( $self->_password_encoding eq 'crypt' ) {
2546 my $auth = from_crypt Authen::Passphrase $self->_password;
2547 return $auth->match($check_password);
2549 } elsif ( $self->_password_encoding eq 'plain' ) {
2551 return $check_password eq $password;
2555 #XXX this could be replaced with Authen::Passphrase stuff
2557 if ( $password =~ /^(\*|!!?)$/ ) { #no self-service login
2559 } elsif ( length($password) < 13 ) { #plaintext
2560 $check_password eq $password;
2561 } elsif ( length($password) == 13 ) { #traditional DES crypt
2562 crypt($check_password, $password) eq $password;
2563 } elsif ( $password =~ /^\$1\$/ ) { #MD5 crypt
2564 unix_md5_crypt($check_password, $password) eq $password;
2565 } elsif ( $password =~ /^\$2a?\$/ ) { #Blowfish
2566 warn "Can't check password: Blowfish encryption not yet supported, ".
2567 "svcnum ". $self->svcnum. "\n";
2570 warn "Can't check password: Unrecognized encryption for svcnum ".
2571 $self->svcnum. "\n";
2579 =item crypt_password [ DEFAULT_ENCRYPTION_TYPE ]
2581 Returns an encrypted password, either by passing through an encrypted password
2582 in the database or by encrypting a plaintext password from the database.
2584 The optional DEFAULT_ENCRYPTION_TYPE parameter can be set to I<crypt> (classic
2585 UNIX DES crypt), I<md5> (md5 crypt supported by most modern Linux and BSD
2586 distrubtions), or (eventually) I<blowfish> (blowfish hashing supported by
2587 OpenBSD, SuSE, other Linux distibutions with pam_unix2, etc.). The default
2588 encryption type is only used if the password is not already encrypted in the
2593 sub crypt_password {
2596 if ( $self->_password_encoding eq 'ldap' ) {
2598 if ( $self->_password =~ /^\{(PLAIN|CLEARTEXT)\}(.+)$/ ) {
2601 #XXX this could be replaced with Authen::Passphrase stuff
2603 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2604 if ( $encryption eq 'crypt' ) {
2607 $saltset[int(rand(64))].$saltset[int(rand(64))]
2609 } elsif ( $encryption eq 'md5' ) {
2610 return unix_md5_crypt( $self->_password );
2611 } elsif ( $encryption eq 'blowfish' ) {
2612 croak "unknown encryption method $encryption";
2614 croak "unknown encryption method $encryption";
2617 } elsif ( $self->_password =~ /^\{CRYPT\}(.+)$/ ) {
2621 } elsif ( $self->_password_encoding eq 'crypt' ) {
2623 return $self->_password;
2625 } elsif ( $self->_password_encoding eq 'plain' ) {
2627 #XXX this could be replaced with Authen::Passphrase stuff
2629 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2630 if ( $encryption eq 'crypt' ) {
2633 $saltset[int(rand(64))].$saltset[int(rand(64))]
2635 } elsif ( $encryption eq 'md5' ) {
2636 return unix_md5_crypt( $self->_password );
2637 } elsif ( $encryption eq 'sha1_base64' ) { #for acct_sql
2638 my $pass = sha1_base64( $self->_password );
2639 $pass .= '=' x (4 - length($pass) % 4); #properly padded base64
2641 } elsif ( $encryption eq 'blowfish' ) {
2642 croak "unknown encryption method $encryption";
2644 croak "unknown encryption method $encryption";
2649 if ( length($self->_password) == 13
2650 || $self->_password =~ /^\$(1|2a?)\$/
2651 || $self->_password =~ /^(\*|NP|\*LK\*|!!?)$/
2657 #XXX this could be replaced with Authen::Passphrase stuff
2659 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2660 if ( $encryption eq 'crypt' ) {
2663 $saltset[int(rand(64))].$saltset[int(rand(64))]
2665 } elsif ( $encryption eq 'md5' ) {
2666 return unix_md5_crypt( $self->_password );
2667 } elsif ( $encryption eq 'blowfish' ) {
2668 croak "unknown encryption method $encryption";
2670 croak "unknown encryption method $encryption";
2679 =item ldap_password [ DEFAULT_ENCRYPTION_TYPE ]
2681 Returns an encrypted password in "LDAP" format, with a curly-bracked prefix
2682 describing the format, for example, "{PLAIN}himom", "{CRYPT}94pAVyK/4oIBk" or
2683 "{MD5}5426824942db4253f87a1009fd5d2d4".
2685 The optional DEFAULT_ENCRYPTION_TYPE is not yet used, but the idea is for it
2686 to work the same as the B</crypt_password> method.
2692 #eventually should check a "password-encoding" field
2694 if ( $self->_password_encoding eq 'ldap' ) {
2696 return $self->_password;
2698 } elsif ( $self->_password_encoding eq 'crypt' ) {
2700 if ( length($self->_password) == 13 ) { #crypt
2701 return '{CRYPT}'. $self->_password;
2702 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2704 #} elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2705 # die "Blowfish encryption not supported in this context, svcnum ".
2706 # $self->svcnum. "\n";
2708 warn "encryption method not (yet?) supported in LDAP context";
2709 return '{CRYPT}*'; #unsupported, should not auth
2712 } elsif ( $self->_password_encoding eq 'plain' ) {
2714 return '{PLAIN}'. $self->_password;
2716 #return '{CLEARTEXT}'. $self->_password; #?
2720 if ( length($self->_password) == 13 ) { #crypt
2721 return '{CRYPT}'. $self->_password;
2722 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2724 } elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2725 warn "Blowfish encryption not supported in this context, svcnum ".
2726 $self->svcnum. "\n";
2729 #are these two necessary anymore?
2730 } elsif ( $self->_password =~ /^(\w{48})$/ ) { #LDAP SSHA
2731 return '{SSHA}'. $1;
2732 } elsif ( $self->_password =~ /^(\w{64})$/ ) { #LDAP NS-MTA-MD5
2733 return '{NS-MTA-MD5}'. $1;
2736 return '{PLAIN}'. $self->_password;
2738 #return '{CLEARTEXT}'. $self->_password; #?
2740 #XXX this could be replaced with Authen::Passphrase stuff if it gets used
2741 #my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2742 #if ( $encryption eq 'crypt' ) {
2743 # return '{CRYPT}'. crypt(
2745 # $saltset[int(rand(64))].$saltset[int(rand(64))]
2747 #} elsif ( $encryption eq 'md5' ) {
2748 # unix_md5_crypt( $self->_password );
2749 #} elsif ( $encryption eq 'blowfish' ) {
2750 # croak "unknown encryption method $encryption";
2752 # croak "unknown encryption method $encryption";
2760 =item domain_slash_username
2762 Returns $domain/$username/
2766 sub domain_slash_username {
2768 $self->domain. '/'. $self->username. '/';
2771 =item virtual_maildir
2773 Returns $domain/maildirs/$username/
2777 sub virtual_maildir {
2779 $self->domain. '/maildirs/'. $self->username. '/';
2784 =head1 CLASS METHODS
2788 =item search HASHREF
2790 Class method which returns a qsearch hash expression to search for parameters
2791 specified in HASHREF. Valid parameters are
2805 Arrayref of pkgparts
2811 Arrayref of additional WHERE clauses, will be ANDed together.
2822 my( $class, $params, $from, $where ) = @_;
2824 #these two should probably move to svc_Domain_Mixin ?
2827 if ( $params->{'domain'} ) {
2828 my $svc_domain = qsearchs('svc_domain', { 'domain'=>$params->{'domain'} } );
2829 #preserve previous behavior & bubble up an error if $svc_domain not found?
2830 push @$where, 'domsvc = '. $svc_domain->svcnum if $svc_domain;
2834 if ( $params->{'domsvc'} =~ /^(\d+)$/ ) {
2835 push @$where, "domsvc = $1";
2840 if ( $params->{'popnum'} =~ /^(\d+)$/ ) {
2841 push @$where, "popnum = $1";
2845 #and these in svc_Tower_Mixin, or maybe we never should have done svc_acct
2846 # towers (or, as mark thought, never should have done svc_broadband)
2849 my @where_sector = $class->tower_sector_sql($params);
2850 if ( @where_sector ) {
2851 push @$where, @where_sector;
2852 push @$from, ' LEFT JOIN tower_sector USING ( sectornum )';
2865 This is the FS::svc_acct job-queue-able version. It still uses
2866 FS::Misc::send_email under-the-hood.
2873 eval "use FS::Misc qw(send_email)";
2876 $opt{mimetype} ||= 'text/plain';
2877 $opt{mimetype} .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2879 my $error = send_email(
2880 'from' => $opt{from},
2882 'subject' => $opt{subject},
2883 'content-type' => $opt{mimetype},
2884 'body' => [ map "$_\n", split("\n", $opt{body}) ],
2886 die $error if $error;
2889 =item check_and_rebuild_fuzzyfiles
2893 sub check_and_rebuild_fuzzyfiles {
2894 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2895 -e "$dir/svc_acct.username"
2896 or &rebuild_fuzzyfiles;
2899 =item rebuild_fuzzyfiles
2903 sub rebuild_fuzzyfiles {
2905 use Fcntl qw(:flock);
2907 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2911 open(USERNAMELOCK,">>$dir/svc_acct.username")
2912 or die "can't open $dir/svc_acct.username: $!";
2913 flock(USERNAMELOCK,LOCK_EX)
2914 or die "can't lock $dir/svc_acct.username: $!";
2916 my @all_username = map $_->getfield('username'), qsearch('svc_acct', {});
2918 open (USERNAMECACHE,">$dir/svc_acct.username.tmp")
2919 or die "can't open $dir/svc_acct.username.tmp: $!";
2920 print USERNAMECACHE join("\n", @all_username), "\n";
2921 close USERNAMECACHE or die "can't close $dir/svc_acct.username.tmp: $!";
2923 rename "$dir/svc_acct.username.tmp", "$dir/svc_acct.username";
2933 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2934 open(USERNAMECACHE,"<$dir/svc_acct.username")
2935 or die "can't open $dir/svc_acct.username: $!";
2936 my @array = map { chomp; $_; } <USERNAMECACHE>;
2937 close USERNAMECACHE;
2941 =item append_fuzzyfiles USERNAME
2945 sub append_fuzzyfiles {
2946 my $username = shift;
2948 &check_and_rebuild_fuzzyfiles;
2950 use Fcntl qw(:flock);
2952 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2954 open(USERNAME,">>$dir/svc_acct.username")
2955 or die "can't open $dir/svc_acct.username: $!";
2956 flock(USERNAME,LOCK_EX)
2957 or die "can't lock $dir/svc_acct.username: $!";
2959 print USERNAME "$username\n";
2961 flock(USERNAME,LOCK_UN)
2962 or die "can't unlock $dir/svc_acct.username: $!";
2969 =item reached_threshold
2971 Performs some activities when svc_acct thresholds (such as number of seconds
2972 remaining) are reached.
2976 sub reached_threshold {
2979 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } );
2980 die "Cannot find svc_acct with svcnum " . $opt{'svcnum'} unless $svc_acct;
2982 if ( $opt{'op'} eq '+' ){
2983 $svc_acct->setfield( $opt{'column'}.'_threshold',
2984 int($svc_acct->getfield($opt{'column'})
2985 * ( $conf->exists('svc_acct-usage_threshold')
2986 ? $conf->config('svc_acct-usage_threshold')/100
2991 my $error = $svc_acct->replace;
2992 die $error if $error;
2993 }elsif ( $opt{'op'} eq '-' ){
2995 my $threshold = $svc_acct->getfield( $opt{'column'}.'_threshold' );
2996 return '' if ($threshold eq '' );
2998 $svc_acct->setfield( $opt{'column'}.'_threshold', 0 );
2999 my $error = $svc_acct->replace;
3000 die $error if $error; # email next time, i guess
3002 if ( $warning_template ) {
3003 eval "use FS::Misc qw(send_email)";
3006 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3007 my $cust_main = $cust_pkg->cust_main;
3009 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ }
3010 $cust_main->invoicing_list,
3011 ($opt{'to'} ? $opt{'to'} : ())
3014 my $mimetype = $warning_mimetype;
3015 $mimetype .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
3017 my $body = $warning_template->fill_in( HASH => {
3018 'custnum' => $cust_main->custnum,
3019 'username' => $svc_acct->username,
3020 'password' => $svc_acct->_password,
3021 'first' => $cust_main->first,
3022 'last' => $cust_main->getfield('last'),
3023 'pkg' => $cust_pkg->part_pkg->pkg,
3024 'column' => $opt{'column'},
3025 'amount' => $opt{'column'} =~/bytes/
3026 ? FS::UI::bytecount::display_bytecount($svc_acct->getfield($opt{'column'}))
3027 : $svc_acct->getfield($opt{'column'}),
3028 'threshold' => $opt{'column'} =~/bytes/
3029 ? FS::UI::bytecount::display_bytecount($threshold)
3034 my $error = send_email(
3035 'from' => $warning_from,
3037 'subject' => $warning_subject,
3038 'content-type' => $mimetype,
3039 'body' => [ map "$_\n", split("\n", $body) ],
3041 die $error if $error;
3044 die "unknown op: " . $opt{'op'};
3048 sub process_print_welcome_letter {
3051 my $self = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } )
3052 or die "invalid svc_acct: " . $opt{'svcnum'};
3053 my $cust_main = $self->cust_svc->cust_pkg->cust_main;
3055 my $ps = $cust_main->print_ps('svc_acct_welcome_letter',
3057 map { $_ => $self->$_ } $self->fields, # or maybe just username & password?
3060 my $error = FS::Misc::do_print(
3062 'agentnum' => $cust_main->agentnum,
3064 die $error if $error;
3072 The $recref stuff in sub check should be cleaned up.
3074 The suspend, unsuspend and cancel methods update the database, but not the
3075 current object. This is probably a bug as it's unexpected and
3078 insertion of RADIUS group stuff in insert could be done with child_objects now
3079 (would probably clean up export of them too)
3081 _op_usage and set_usage bypass the history... maybe they shouldn't
3085 L<FS::svc_Common>, edit/part_svc.cgi from an installed web interface,
3086 export.html from the base documentation, L<FS::Record>, L<FS::Conf>,
3087 L<FS::cust_svc>, L<FS::part_svc>, L<FS::cust_pkg>, L<FS::queue>,
3088 L<freeside-queued>), L<FS::svc_acct_pop>,
3089 schema.html from the base documentation.