4 use vars qw( @ISA $DEBUG $me $conf $skip_fuzzyfiles
5 $dir_prefix @shells $usernamemin
6 $usernamemax $passwordmin $passwordmax
7 $username_ampersand $username_letter $username_letterfirst
8 $username_noperiod $username_nounderscore $username_nodash
9 $username_uppercase $username_percent
10 $password_noampersand $password_noexclamation
11 $warning_template $warning_from $warning_subject $warning_mimetype
14 $radius_password $radius_ip
20 use Crypt::PasswdMD5 1.2;
22 use Authen::Passphrase;
23 use FS::UID qw( datasrc );
25 use FS::Record qw( qsearch qsearchs fields dbh dbdef );
26 use FS::Msgcat qw(gettext);
31 use FS::cust_main_invoice;
35 use FS::radius_usergroup;
42 @ISA = qw( FS::svc_Common );
45 $me = '[FS::svc_acct]';
47 #ask FS::UID to run this stuff for us later
48 $FS::UID::callback{'FS::svc_acct'} = sub {
50 $dir_prefix = $conf->config('home');
51 @shells = $conf->config('shells');
52 $usernamemin = $conf->config('usernamemin') || 2;
53 $usernamemax = $conf->config('usernamemax');
54 $passwordmin = $conf->config('passwordmin') || 6;
55 $passwordmax = $conf->config('passwordmax') || 8;
56 $username_letter = $conf->exists('username-letter');
57 $username_letterfirst = $conf->exists('username-letterfirst');
58 $username_noperiod = $conf->exists('username-noperiod');
59 $username_nounderscore = $conf->exists('username-nounderscore');
60 $username_nodash = $conf->exists('username-nodash');
61 $username_uppercase = $conf->exists('username-uppercase');
62 $username_ampersand = $conf->exists('username-ampersand');
63 $username_percent = $conf->exists('username-percent');
64 $password_noampersand = $conf->exists('password-noexclamation');
65 $password_noexclamation = $conf->exists('password-noexclamation');
66 $dirhash = $conf->config('dirhash') || 0;
67 if ( $conf->exists('warning_email') ) {
68 $warning_template = new Text::Template (
70 SOURCE => [ map "$_\n", $conf->config('warning_email') ]
71 ) or warn "can't create warning email template: $Text::Template::ERROR";
72 $warning_from = $conf->config('warning_email-from'); # || 'your-isp-is-dum'
73 $warning_subject = $conf->config('warning_email-subject') || 'Warning';
74 $warning_mimetype = $conf->config('warning_email-mimetype') || 'text/plain';
75 $warning_cc = $conf->config('warning_email-cc');
77 $warning_template = '';
79 $warning_subject = '';
80 $warning_mimetype = '';
83 $smtpmachine = $conf->config('smtpmachine');
84 $radius_password = $conf->config('radius-password') || 'Password';
85 $radius_ip = $conf->config('radius-ip') || 'Framed-IP-Address';
86 @pw_set = ( 'A'..'Z' ) if $conf->exists('password-generated-allcaps');
89 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '.' , '/' );
90 @pw_set = ( 'a'..'z', 'A'..'Z', '0'..'9', '(', ')', '#', '!', '.', ',' );
94 my ( $hashref, $cache ) = @_;
95 if ( $hashref->{'svc_acct_svcnum'} ) {
96 $self->{'_domsvc'} = FS::svc_domain->new( {
97 'svcnum' => $hashref->{'domsvc'},
98 'domain' => $hashref->{'svc_acct_domain'},
99 'catchall' => $hashref->{'svc_acct_catchall'},
106 FS::svc_acct - Object methods for svc_acct records
112 $record = new FS::svc_acct \%hash;
113 $record = new FS::svc_acct { 'column' => 'value' };
115 $error = $record->insert;
117 $error = $new_record->replace($old_record);
119 $error = $record->delete;
121 $error = $record->check;
123 $error = $record->suspend;
125 $error = $record->unsuspend;
127 $error = $record->cancel;
129 %hash = $record->radius;
131 %hash = $record->radius_reply;
133 %hash = $record->radius_check;
135 $domain = $record->domain;
137 $svc_domain = $record->svc_domain;
139 $email = $record->email;
141 $seconds_since = $record->seconds_since($timestamp);
145 An FS::svc_acct object represents an account. FS::svc_acct inherits from
146 FS::svc_Common. The following fields are currently supported:
150 =item svcnum - primary key (assigned automatcially for new accounts)
154 =item _password - generated if blank
156 =item _password_encoding - plain, crypt, ldap (or empty for autodetection)
158 =item sec_phrase - security phrase
160 =item popnum - Point of presence (see L<FS::svc_acct_pop>)
168 =item dir - set automatically if blank (and uid is not)
172 =item quota - (unimplementd)
174 =item slipip - IP address
184 =item domsvc - svcnum from svc_domain
186 =item radius_I<Radius_Attribute> - I<Radius-Attribute> (reply)
188 =item rc_I<Radius_Attribute> - I<Radius-Attribute> (check)
198 Creates a new account. To add the account to the database, see L<"insert">.
205 'longname_plural' => 'Access accounts and mailboxes',
206 'sorts' => [ 'username', 'uid', ],
207 'display_weight' => 10,
208 'cancel_weight' => 50,
210 'dir' => 'Home directory',
213 def_label => 'UID (set to fixed and blank for no UIDs)',
216 'slipip' => 'IP address',
217 # 'popnum' => qq!<A HREF="$p/browse/svc_acct_pop.cgi/">POP number</A>!,
219 label => 'Access number',
221 select_table => 'svc_acct_pop',
222 select_key => 'popnum',
223 select_label => 'city',
229 disable_default => 1,
236 disable_inventory => 1,
239 '_password' => 'Password',
242 def_label => 'GID (when blank, defaults to UID)',
246 #desc =>'Shell (all service definitions should have a default or fixed shell that is present in the <b>shells</b> configuration file, set to blank for no shell tracking)',
248 def_label=> 'Shell (set to blank for no shell tracking)',
250 select_list => [ $conf->config('shells') ],
251 disable_inventory => 1,
254 'finger' => 'Real name (GECOS)',
257 #def_label => 'svcnum from svc_domain',
259 select_table => 'svc_domain',
260 select_key => 'svcnum',
261 select_label => 'domain',
262 disable_inventory => 1,
266 label => 'RADIUS groups',
267 type => 'radius_usergroup_selector',
268 disable_inventory => 1,
271 'seconds' => { label => 'Seconds',
273 disable_inventory => 1,
280 sub table { 'svc_acct'; }
284 #false laziness with edit/svc_acct.cgi
286 my( $self, $groups ) = @_;
287 if ( ref($groups) eq 'ARRAY' ) {
289 } elsif ( length($groups) ) {
290 [ split(/\s*,\s*/, $groups) ];
298 =item search_sql STRING
300 Class method which returns an SQL fragment to search for the given string.
305 my( $class, $string ) = @_;
306 if ( $string =~ /^([^@]+)@([^@]+)$/ ) {
307 my( $username, $domain ) = ( $1, $2 );
308 my $q_username = dbh->quote($username);
309 my @svc_domain = qsearch('svc_domain', { 'domain' => $domain } );
311 "svc_acct.username = $q_username AND ( ".
312 join( ' OR ', map { "svc_acct.domsvc = ". $_->svcnum; } @svc_domain ).
317 } elsif ( $string =~ /^(\d{1,3}\.){3}\d{1,3}$/ ) {
319 $class->search_sql_field('slipip', $string ).
321 $class->search_sql_field('username', $string ).
324 $class->search_sql_field('username', $string);
328 =item label [ END_TIMESTAMP [ START_TIMESTAMP ] ]
330 Returns the "username@domain" string for this account.
332 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
344 =item insert [ , OPTION => VALUE ... ]
346 Adds this account to the database. If there is an error, returns the error,
347 otherwise returns false.
349 The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be
350 defined. An FS::cust_svc record will be created and inserted.
352 The additional field I<usergroup> can optionally be defined; if so it should
353 contain an arrayref of group names. See L<FS::radius_usergroup>.
355 The additional field I<child_objects> can optionally be defined; if so it
356 should contain an arrayref of FS::tablename objects. They will have their
357 svcnum fields set and will be inserted after this record, but before any
358 exports are run. Each element of the array can also optionally be a
359 two-element array reference containing the child object and the name of an
360 alternate field to be filled in with the newly-inserted svcnum, for example
361 C<[ $svc_forward, 'srcsvc' ]>
363 Currently available options are: I<depend_jobnum>
365 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
366 jobnums), all provisioning jobs will have a dependancy on the supplied
367 jobnum(s) (they will not run until the specific job(s) complete(s)).
369 (TODOC: L<FS::queue> and L<freeside-queued>)
371 (TODOC: new exports!)
380 warn "[$me] insert called on $self: ". Dumper($self).
381 "\nwith options: ". Dumper(%options);
384 local $SIG{HUP} = 'IGNORE';
385 local $SIG{INT} = 'IGNORE';
386 local $SIG{QUIT} = 'IGNORE';
387 local $SIG{TERM} = 'IGNORE';
388 local $SIG{TSTP} = 'IGNORE';
389 local $SIG{PIPE} = 'IGNORE';
391 my $oldAutoCommit = $FS::UID::AutoCommit;
392 local $FS::UID::AutoCommit = 0;
395 my $error = $self->check;
396 return $error if $error;
398 if ( $self->svcnum && qsearchs('cust_svc',{'svcnum'=>$self->svcnum}) ) {
399 my $cust_svc = qsearchs('cust_svc',{'svcnum'=>$self->svcnum});
400 unless ( $cust_svc ) {
401 $dbh->rollback if $oldAutoCommit;
402 return "no cust_svc record found for svcnum ". $self->svcnum;
404 $self->pkgnum($cust_svc->pkgnum);
405 $self->svcpart($cust_svc->svcpart);
408 $error = $self->_check_duplicate;
410 $dbh->rollback if $oldAutoCommit;
415 $error = $self->SUPER::insert(
416 'jobnums' => \@jobnums,
417 'child_objects' => $self->child_objects,
421 $dbh->rollback if $oldAutoCommit;
425 if ( $self->usergroup ) {
426 foreach my $groupname ( @{$self->usergroup} ) {
427 my $radius_usergroup = new FS::radius_usergroup ( {
428 svcnum => $self->svcnum,
429 groupname => $groupname,
431 my $error = $radius_usergroup->insert;
433 $dbh->rollback if $oldAutoCommit;
439 unless ( $skip_fuzzyfiles ) {
440 $error = $self->queue_fuzzyfiles_update;
442 $dbh->rollback if $oldAutoCommit;
443 return "updating fuzzy search cache: $error";
447 my $cust_pkg = $self->cust_svc->cust_pkg;
450 my $cust_main = $cust_pkg->cust_main;
451 my $agentnum = $cust_main->agentnum;
453 if ( $conf->exists('emailinvoiceautoalways')
454 || $conf->exists('emailinvoiceauto')
455 && ! $cust_main->invoicing_list_emailonly
457 my @invoicing_list = $cust_main->invoicing_list;
458 push @invoicing_list, $self->email;
459 $cust_main->invoicing_list(\@invoicing_list);
463 my ($to,$welcome_template,$welcome_from,$welcome_subject,$welcome_subject_template,$welcome_mimetype)
464 = ('','','','','','');
466 if ( $conf->exists('welcome_email', $agentnum) ) {
467 $welcome_template = new Text::Template (
469 SOURCE => [ map "$_\n", $conf->config('welcome_email', $agentnum) ]
470 ) or warn "can't create welcome email template: $Text::Template::ERROR";
471 $welcome_from = $conf->config('welcome_email-from', $agentnum);
472 # || 'your-isp-is-dum'
473 $welcome_subject = $conf->config('welcome_email-subject', $agentnum)
475 $welcome_subject_template = new Text::Template (
477 SOURCE => $welcome_subject,
478 ) or warn "can't create welcome email subject template: $Text::Template::ERROR";
479 $welcome_mimetype = $conf->config('welcome_email-mimetype', $agentnum)
482 if ( $welcome_template && $cust_pkg ) {
483 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
487 'custnum' => $self->custnum,
488 'username' => $self->username,
489 'password' => $self->_password,
490 'first' => $cust_main->first,
491 'last' => $cust_main->getfield('last'),
492 'pkg' => $cust_pkg->part_pkg->pkg,
494 my $wqueue = new FS::queue {
495 'svcnum' => $self->svcnum,
496 'job' => 'FS::svc_acct::send_email'
498 my $error = $wqueue->insert(
500 'from' => $welcome_from,
501 'subject' => $welcome_subject_template->fill_in( HASH => \%hash, ),
502 'mimetype' => $welcome_mimetype,
503 'body' => $welcome_template->fill_in( HASH => \%hash, ),
506 $dbh->rollback if $oldAutoCommit;
507 return "error queuing welcome email: $error";
510 if ( $options{'depend_jobnum'} ) {
511 warn "$me depend_jobnum found; adding to welcome email dependancies"
513 if ( ref($options{'depend_jobnum'}) ) {
514 warn "$me adding jobs ". join(', ', @{$options{'depend_jobnum'}} ).
515 "to welcome email dependancies"
517 push @jobnums, @{ $options{'depend_jobnum'} };
519 warn "$me adding job $options{'depend_jobnum'} ".
520 "to welcome email dependancies"
522 push @jobnums, $options{'depend_jobnum'};
526 foreach my $jobnum ( @jobnums ) {
527 my $error = $wqueue->depend_insert($jobnum);
529 $dbh->rollback if $oldAutoCommit;
530 return "error queuing welcome email job dependancy: $error";
540 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
546 Deletes this account from the database. If there is an error, returns the
547 error, otherwise returns false.
549 The corresponding FS::cust_svc record will be deleted as well.
551 (TODOC: new exports!)
558 return "can't delete system account" if $self->_check_system;
560 return "Can't delete an account which is a (svc_forward) source!"
561 if qsearch( 'svc_forward', { 'srcsvc' => $self->svcnum } );
563 return "Can't delete an account which is a (svc_forward) destination!"
564 if qsearch( 'svc_forward', { 'dstsvc' => $self->svcnum } );
566 return "Can't delete an account with (svc_www) web service!"
567 if qsearch( 'svc_www', { 'usersvc' => $self->svcnum } );
569 # what about records in session ? (they should refer to history table)
571 local $SIG{HUP} = 'IGNORE';
572 local $SIG{INT} = 'IGNORE';
573 local $SIG{QUIT} = 'IGNORE';
574 local $SIG{TERM} = 'IGNORE';
575 local $SIG{TSTP} = 'IGNORE';
576 local $SIG{PIPE} = 'IGNORE';
578 my $oldAutoCommit = $FS::UID::AutoCommit;
579 local $FS::UID::AutoCommit = 0;
582 foreach my $cust_main_invoice (
583 qsearch( 'cust_main_invoice', { 'dest' => $self->svcnum } )
585 unless ( defined($cust_main_invoice) ) {
586 warn "WARNING: something's wrong with qsearch";
589 my %hash = $cust_main_invoice->hash;
590 $hash{'dest'} = $self->email;
591 my $new = new FS::cust_main_invoice \%hash;
592 my $error = $new->replace($cust_main_invoice);
594 $dbh->rollback if $oldAutoCommit;
599 foreach my $svc_domain (
600 qsearch( 'svc_domain', { 'catchall' => $self->svcnum } )
602 my %hash = new FS::svc_domain->hash;
603 $hash{'catchall'} = '';
604 my $new = new FS::svc_domain \%hash;
605 my $error = $new->replace($svc_domain);
607 $dbh->rollback if $oldAutoCommit;
612 my $error = $self->SUPER::delete;
614 $dbh->rollback if $oldAutoCommit;
618 foreach my $radius_usergroup (
619 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } )
621 my $error = $radius_usergroup->delete;
623 $dbh->rollback if $oldAutoCommit;
628 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
632 =item replace OLD_RECORD
634 Replaces OLD_RECORD with this one in the database. If there is an error,
635 returns the error, otherwise returns false.
637 The additional field I<usergroup> can optionally be defined; if so it should
638 contain an arrayref of group names. See L<FS::radius_usergroup>.
644 my ( $new, $old ) = ( shift, shift );
646 warn "$me replacing $old with $new\n" if $DEBUG;
648 # We absolutely have to have an old vs. new record to make this work.
649 if (!defined($old)) {
650 $old = qsearchs( 'svc_acct', { 'svcnum' => $new->svcnum } );
653 return "can't modify system account" if $old->_check_system;
656 #no warnings 'numeric'; #alas, a 5.006-ism
659 foreach my $xid (qw( uid gid )) {
661 return "Can't change $xid!"
662 if ! $conf->exists("svc_acct-edit_$xid")
663 && $old->$xid() != $new->$xid()
664 && $new->cust_svc->part_svc->part_svc_column($xid)->columnflag ne 'F'
669 #change homdir when we change username
670 $new->setfield('dir', '') if $old->username ne $new->username;
672 local $SIG{HUP} = 'IGNORE';
673 local $SIG{INT} = 'IGNORE';
674 local $SIG{QUIT} = 'IGNORE';
675 local $SIG{TERM} = 'IGNORE';
676 local $SIG{TSTP} = 'IGNORE';
677 local $SIG{PIPE} = 'IGNORE';
679 my $oldAutoCommit = $FS::UID::AutoCommit;
680 local $FS::UID::AutoCommit = 0;
683 # redundant, but so $new->usergroup gets set
684 $error = $new->check;
685 return $error if $error;
687 $old->usergroup( [ $old->radius_groups ] );
689 warn $old->email. " old groups: ". join(' ',@{$old->usergroup}). "\n";
690 warn $new->email. "new groups: ". join(' ',@{$new->usergroup}). "\n";
692 if ( $new->usergroup ) {
693 #(sorta) false laziness with FS::part_export::sqlradius::_export_replace
694 my @newgroups = @{$new->usergroup};
695 foreach my $oldgroup ( @{$old->usergroup} ) {
696 if ( grep { $oldgroup eq $_ } @newgroups ) {
697 @newgroups = grep { $oldgroup ne $_ } @newgroups;
700 my $radius_usergroup = qsearchs('radius_usergroup', {
701 svcnum => $old->svcnum,
702 groupname => $oldgroup,
704 my $error = $radius_usergroup->delete;
706 $dbh->rollback if $oldAutoCommit;
707 return "error deleting radius_usergroup $oldgroup: $error";
711 foreach my $newgroup ( @newgroups ) {
712 my $radius_usergroup = new FS::radius_usergroup ( {
713 svcnum => $new->svcnum,
714 groupname => $newgroup,
716 my $error = $radius_usergroup->insert;
718 $dbh->rollback if $oldAutoCommit;
719 return "error adding radius_usergroup $newgroup: $error";
725 if ( $old->username ne $new->username || $old->domsvc != $new->domsvc ) {
726 $new->svcpart( $new->cust_svc->svcpart ) unless $new->svcpart;
727 $error = $new->_check_duplicate;
729 $dbh->rollback if $oldAutoCommit;
734 $error = $new->SUPER::replace($old);
736 $dbh->rollback if $oldAutoCommit;
737 return $error if $error;
740 if ( $new->username ne $old->username && ! $skip_fuzzyfiles ) {
741 $error = $new->queue_fuzzyfiles_update;
743 $dbh->rollback if $oldAutoCommit;
744 return "updating fuzzy search cache: $error";
748 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
752 =item queue_fuzzyfiles_update
754 Used by insert & replace to update the fuzzy search cache
758 sub queue_fuzzyfiles_update {
761 local $SIG{HUP} = 'IGNORE';
762 local $SIG{INT} = 'IGNORE';
763 local $SIG{QUIT} = 'IGNORE';
764 local $SIG{TERM} = 'IGNORE';
765 local $SIG{TSTP} = 'IGNORE';
766 local $SIG{PIPE} = 'IGNORE';
768 my $oldAutoCommit = $FS::UID::AutoCommit;
769 local $FS::UID::AutoCommit = 0;
772 my $queue = new FS::queue {
773 'svcnum' => $self->svcnum,
774 'job' => 'FS::svc_acct::append_fuzzyfiles'
776 my $error = $queue->insert($self->username);
778 $dbh->rollback if $oldAutoCommit;
779 return "queueing job (transaction rolled back): $error";
782 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
790 Suspends this account by calling export-specific suspend hooks. If there is
791 an error, returns the error, otherwise returns false.
793 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
799 return "can't suspend system account" if $self->_check_system;
800 $self->SUPER::suspend;
805 Unsuspends this account by by calling export-specific suspend hooks. If there
806 is an error, returns the error, otherwise returns false.
808 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
814 my %hash = $self->hash;
815 if ( $hash{_password} =~ /^\*SUSPENDED\* (.*)$/ ) {
816 $hash{_password} = $1;
817 my $new = new FS::svc_acct ( \%hash );
818 my $error = $new->replace($self);
819 return $error if $error;
822 $self->SUPER::unsuspend;
827 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
829 If the B<auto_unset_catchall> configuration option is set, this method will
830 automatically remove any references to the canceled service in the catchall
831 field of svc_domain. This allows packages that contain both a svc_domain and
832 its catchall svc_acct to be canceled in one step.
837 # Only one thing to do at this level
839 foreach my $svc_domain (
840 qsearch( 'svc_domain', { catchall => $self->svcnum } ) ) {
841 if($conf->exists('auto_unset_catchall')) {
842 my %hash = $svc_domain->hash;
843 $hash{catchall} = '';
844 my $new = new FS::svc_domain ( \%hash );
845 my $error = $new->replace($svc_domain);
846 return $error if $error;
848 return "cannot unprovision svc_acct #".$self->svcnum.
849 " while assigned as catchall for svc_domain #".$svc_domain->svcnum;
853 $self->SUPER::cancel;
859 Checks all fields to make sure this is a valid service. If there is an error,
860 returns the error, otherwise returns false. Called by the insert and replace
863 Sets any fixed values; see L<FS::part_svc>.
870 my($recref) = $self->hashref;
872 my $x = $self->setfixed( $self->_fieldhandlers );
873 return $x unless ref($x);
876 if ( $part_svc->part_svc_column('usergroup')->columnflag eq "F" ) {
878 [ split(',', $part_svc->part_svc_column('usergroup')->columnvalue) ] );
881 my $error = $self->ut_numbern('svcnum')
882 #|| $self->ut_number('domsvc')
883 || $self->ut_foreign_key('domsvc', 'svc_domain', 'svcnum' )
884 || $self->ut_textn('sec_phrase')
885 || $self->ut_snumbern('seconds')
886 || $self->ut_snumbern('upbytes')
887 || $self->ut_snumbern('downbytes')
888 || $self->ut_snumbern('totalbytes')
889 || $self->ut_enum( '_password_encoding',
890 [ '', qw( plain crypt ldap ) ]
893 return $error if $error;
895 my $ulen = $usernamemax || $self->dbdef_table->column('username')->length;
896 if ( $username_uppercase ) {
897 $recref->{username} =~ /^([a-z0-9_\-\.\&\%]{$usernamemin,$ulen})$/i
898 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
899 $recref->{username} = $1;
901 $recref->{username} =~ /^([a-z0-9_\-\.\&\%]{$usernamemin,$ulen})$/
902 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
903 $recref->{username} = $1;
906 if ( $username_letterfirst ) {
907 $recref->{username} =~ /^[a-z]/ or return gettext('illegal_username');
908 } elsif ( $username_letter ) {
909 $recref->{username} =~ /[a-z]/ or return gettext('illegal_username');
911 if ( $username_noperiod ) {
912 $recref->{username} =~ /\./ and return gettext('illegal_username');
914 if ( $username_nounderscore ) {
915 $recref->{username} =~ /_/ and return gettext('illegal_username');
917 if ( $username_nodash ) {
918 $recref->{username} =~ /\-/ and return gettext('illegal_username');
920 unless ( $username_ampersand ) {
921 $recref->{username} =~ /\&/ and return gettext('illegal_username');
923 unless ( $username_percent ) {
924 $recref->{username} =~ /\%/ and return gettext('illegal_username');
927 $recref->{popnum} =~ /^(\d*)$/ or return "Illegal popnum: ".$recref->{popnum};
928 $recref->{popnum} = $1;
929 return "Unknown popnum" unless
930 ! $recref->{popnum} ||
931 qsearchs('svc_acct_pop',{'popnum'=> $recref->{popnum} } );
933 unless ( $part_svc->part_svc_column('uid')->columnflag eq 'F' ) {
935 $recref->{uid} =~ /^(\d*)$/ or return "Illegal uid";
936 $recref->{uid} = $1 eq '' ? $self->unique('uid') : $1;
938 $recref->{gid} =~ /^(\d*)$/ or return "Illegal gid";
939 $recref->{gid} = $1 eq '' ? $recref->{uid} : $1;
940 #not all systems use gid=uid
941 #you can set a fixed gid in part_svc
943 return "Only root can have uid 0"
944 if $recref->{uid} == 0
945 && $recref->{username} !~ /^(root|toor|smtp)$/;
947 unless ( $recref->{username} eq 'sync' ) {
948 if ( grep $_ eq $recref->{shell}, @shells ) {
949 $recref->{shell} = (grep $_ eq $recref->{shell}, @shells)[0];
951 return "Illegal shell \`". $self->shell. "\'; ".
952 "shells configuration value contains: @shells";
955 $recref->{shell} = '/bin/sync';
959 $recref->{gid} ne '' ?
960 return "Can't have gid without uid" : ( $recref->{gid}='' );
961 #$recref->{dir} ne '' ?
962 # return "Can't have directory without uid" : ( $recref->{dir}='' );
963 $recref->{shell} ne '' ?
964 return "Can't have shell without uid" : ( $recref->{shell}='' );
967 unless ( $part_svc->part_svc_column('dir')->columnflag eq 'F' ) {
969 $recref->{dir} =~ /^([\/\w\-\.\&]*)$/
970 or return "Illegal directory: ". $recref->{dir};
972 return "Illegal directory"
973 if $recref->{dir} =~ /(^|\/)\.+(\/|$)/; #no .. component
974 return "Illegal directory"
975 if $recref->{dir} =~ /\&/ && ! $username_ampersand;
976 unless ( $recref->{dir} ) {
977 $recref->{dir} = $dir_prefix . '/';
978 if ( $dirhash > 0 ) {
979 for my $h ( 1 .. $dirhash ) {
980 $recref->{dir} .= substr($recref->{username}, $h-1, 1). '/';
982 } elsif ( $dirhash < 0 ) {
983 for my $h ( reverse $dirhash .. -1 ) {
984 $recref->{dir} .= substr($recref->{username}, $h, 1). '/';
987 $recref->{dir} .= $recref->{username};
993 # $error = $self->ut_textn('finger');
994 # return $error if $error;
995 if ( $self->getfield('finger') eq '' ) {
996 my $cust_pkg = $self->svcnum
997 ? $self->cust_svc->cust_pkg
998 : qsearchs('cust_pkg', { 'pkgnum' => $self->getfield('pkgnum') } );
1000 my $cust_main = $cust_pkg->cust_main;
1001 $self->setfield('finger', $cust_main->first.' '.$cust_main->get('last') );
1004 $self->getfield('finger') =~
1005 /^([\w \t\!\@\#\$\%\&\(\)\-\+\;\'\"\,\.\?\/\*\<\>]*)$/
1006 or return "Illegal finger: ". $self->getfield('finger');
1007 $self->setfield('finger', $1);
1009 $recref->{quota} =~ /^(\w*)$/ or return "Illegal quota";
1010 $recref->{quota} = $1;
1012 unless ( $part_svc->part_svc_column('slipip')->columnflag eq 'F' ) {
1013 if ( $recref->{slipip} eq '' ) {
1014 $recref->{slipip} = '';
1015 } elsif ( $recref->{slipip} eq '0e0' ) {
1016 $recref->{slipip} = '0e0';
1018 $recref->{slipip} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/
1019 or return "Illegal slipip: ". $self->slipip;
1020 $recref->{slipip} = $1;
1025 #arbitrary RADIUS stuff; allow ut_textn for now
1026 foreach ( grep /^radius_/, fields('svc_acct') ) {
1027 $self->ut_textn($_);
1030 if ( $recref->{_password_encoding} eq 'ldap' ) {
1032 if ( $recref->{_password} =~ /^(\{[\w\-]+\})(!?.{0,64})$/ ) {
1033 $recref->{_password} = uc($1).$2;
1035 return 'Illegal (ldap-encoded) password: '. $recref->{_password};
1038 } elsif ( $recref->{_password_encoding} eq 'crypt' ) {
1040 if ( $recref->{_password} =~
1041 #/^(\$\w+\$.*|[\w\+\/]{13}|_[\w\+\/]{19}|\*)$/
1042 /^(!!?)?(\$\w+\$.*|[\w\+\/]{13}|_[\w\+\/]{19}|\*)$/
1045 $recref->{_password} = $1.$2;
1048 return 'Illegal (crypt-encoded) password';
1051 } elsif ( $recref->{_password_encoding} eq 'plain' ) {
1053 #generate a password if it is blank
1054 $recref->{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) )
1055 unless length( $recref->{_password} );
1057 if ( $recref->{_password} =~ /^([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1058 $recref->{_password} = $1;
1060 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1061 FS::Msgcat::_gettext('illegal_password_characters').
1062 ": ". $recref->{_password};
1065 if ( $password_noampersand ) {
1066 $recref->{_password} =~ /\&/ and return gettext('illegal_password');
1068 if ( $password_noexclamation ) {
1069 $recref->{_password} =~ /\!/ and return gettext('illegal_password');
1074 #carp "warning: _password_encoding unspecified\n";
1076 #generate a password if it is blank
1077 unless ( length( $recref->{_password} ) ) {
1079 $recref->{_password} =
1080 join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1081 $recref->{_password_encoding} = 'plain';
1085 #if ( $recref->{_password} =~ /^((\*SUSPENDED\* )?)([^\t\n]{4,16})$/ ) {
1086 if ( $recref->{_password} =~ /^((\*SUSPENDED\* |!!?)?)([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1087 $recref->{_password} = $1.$3;
1088 $recref->{_password_encoding} = 'plain';
1089 } elsif ( $recref->{_password} =~
1090 /^((\*SUSPENDED\* |!!?)?)([\w\.\/\$\;\+]{13,64})$/
1092 $recref->{_password} = $1.$3;
1093 $recref->{_password_encoding} = 'crypt';
1094 } elsif ( $recref->{_password} eq '*' ) {
1095 $recref->{_password} = '*';
1096 $recref->{_password_encoding} = 'crypt';
1097 } elsif ( $recref->{_password} eq '!' ) {
1098 $recref->{_password_encoding} = 'crypt';
1099 $recref->{_password} = '!';
1100 } elsif ( $recref->{_password} eq '!!' ) {
1101 $recref->{_password} = '!!';
1102 $recref->{_password_encoding} = 'crypt';
1104 #return "Illegal password";
1105 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1106 FS::Msgcat::_gettext('illegal_password_characters').
1107 ": ". $recref->{_password};
1114 $self->SUPER::check;
1120 Internal function to check the username against the list of system usernames
1121 from the I<system_usernames> configuration value. Returns true if the username
1122 is listed on the system username list.
1128 scalar( grep { $self->username eq $_ || $self->email eq $_ }
1129 $conf->config('system_usernames')
1133 =item _check_duplicate
1135 Internal function to check for duplicates usernames, username@domain pairs and
1138 If the I<global_unique-username> configuration value is set to B<username> or
1139 B<username@domain>, enforces global username or username@domain uniqueness.
1141 In all cases, check for duplicate uids and usernames or username@domain pairs
1142 per export and with identical I<svcpart> values.
1146 sub _check_duplicate {
1149 my $global_unique = $conf->config('global_unique-username') || 'none';
1150 return '' if $global_unique eq 'disabled';
1152 #this is Pg-specific. what to do for mysql etc?
1153 # ( mysql LOCK TABLES certainly isn't equivalent or useful here :/ )
1154 warn "$me locking svc_acct table for duplicate search" if $DEBUG;
1155 dbh->do("LOCK TABLE svc_acct IN SHARE ROW EXCLUSIVE MODE")
1157 warn "$me acquired svc_acct table lock for duplicate search" if $DEBUG;
1159 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
1160 unless ( $part_svc ) {
1161 return 'unknown svcpart '. $self->svcpart;
1164 my @dup_user = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1165 qsearch( 'svc_acct', { 'username' => $self->username } );
1166 return gettext('username_in_use')
1167 if $global_unique eq 'username' && @dup_user;
1169 my @dup_userdomain = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1170 qsearch( 'svc_acct', { 'username' => $self->username,
1171 'domsvc' => $self->domsvc } );
1172 return gettext('username_in_use')
1173 if $global_unique eq 'username@domain' && @dup_userdomain;
1176 if ( $part_svc->part_svc_column('uid')->columnflag ne 'F'
1177 && $self->username !~ /^(toor|(hyla)?fax)$/ ) {
1178 @dup_uid = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1179 qsearch( 'svc_acct', { 'uid' => $self->uid } );
1184 if ( @dup_user || @dup_userdomain || @dup_uid ) {
1185 my $exports = FS::part_export::export_info('svc_acct');
1186 my %conflict_user_svcpart;
1187 my %conflict_userdomain_svcpart = ( $self->svcpart => 'SELF', );
1189 foreach my $part_export ( $part_svc->part_export ) {
1191 #this will catch to the same exact export
1192 my @svcparts = map { $_->svcpart } $part_export->export_svc;
1194 #this will catch to exports w/same exporthost+type ???
1195 #my @other_part_export = qsearch('part_export', {
1196 # 'machine' => $part_export->machine,
1197 # 'exporttype' => $part_export->exporttype,
1199 #foreach my $other_part_export ( @other_part_export ) {
1200 # push @svcparts, map { $_->svcpart }
1201 # qsearch('export_svc', { 'exportnum' => $part_export->exportnum });
1204 #my $nodomain = $exports->{$part_export->exporttype}{'nodomain'};
1205 #silly kludge to avoid uninitialized value errors
1206 my $nodomain = exists( $exports->{$part_export->exporttype}{'nodomain'} )
1207 ? $exports->{$part_export->exporttype}{'nodomain'}
1209 if ( $nodomain =~ /^Y/i ) {
1210 $conflict_user_svcpart{$_} = $part_export->exportnum
1213 $conflict_userdomain_svcpart{$_} = $part_export->exportnum
1218 foreach my $dup_user ( @dup_user ) {
1219 my $dup_svcpart = $dup_user->cust_svc->svcpart;
1220 if ( exists($conflict_user_svcpart{$dup_svcpart}) ) {
1221 return "duplicate username: conflicts with svcnum ". $dup_user->svcnum.
1222 " via exportnum ". $conflict_user_svcpart{$dup_svcpart};
1226 foreach my $dup_userdomain ( @dup_userdomain ) {
1227 my $dup_svcpart = $dup_userdomain->cust_svc->svcpart;
1228 if ( exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1229 return "duplicate username\@domain: conflicts with svcnum ".
1230 $dup_userdomain->svcnum. " via exportnum ".
1231 $conflict_userdomain_svcpart{$dup_svcpart};
1235 foreach my $dup_uid ( @dup_uid ) {
1236 my $dup_svcpart = $dup_uid->cust_svc->svcpart;
1237 if ( exists($conflict_user_svcpart{$dup_svcpart})
1238 || exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1239 return "duplicate uid: conflicts with svcnum ". $dup_uid->svcnum.
1240 " via exportnum ". $conflict_user_svcpart{$dup_svcpart}
1241 || $conflict_userdomain_svcpart{$dup_svcpart};
1253 Depriciated, use radius_reply instead.
1258 carp "FS::svc_acct::radius depriciated, use radius_reply";
1259 $_[0]->radius_reply;
1264 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1265 reply attributes of this record.
1267 Note that this is now the preferred method for reading RADIUS attributes -
1268 accessing the columns directly is discouraged, as the column names are
1269 expected to change in the future.
1276 return %{ $self->{'radius_reply'} }
1277 if exists $self->{'radius_reply'};
1282 my($column, $attrib) = ($1, $2);
1283 #$attrib =~ s/_/\-/g;
1284 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1285 } grep { /^radius_/ && $self->getfield($_) } fields( $self->table );
1287 if ( $self->slipip && $self->slipip ne '0e0' ) {
1288 $reply{$radius_ip} = $self->slipip;
1291 if ( $self->seconds !~ /^$/ ) {
1292 $reply{'Session-Timeout'} = $self->seconds;
1300 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1301 check attributes of this record.
1303 Note that this is now the preferred method for reading RADIUS attributes -
1304 accessing the columns directly is discouraged, as the column names are
1305 expected to change in the future.
1312 return %{ $self->{'radius_check'} }
1313 if exists $self->{'radius_check'};
1318 my($column, $attrib) = ($1, $2);
1319 #$attrib =~ s/_/\-/g;
1320 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1321 } grep { /^rc_/ && $self->getfield($_) } fields( $self->table );
1323 my $password = $self->_password;
1324 my $pw_attrib = length($password) <= 12 ? $radius_password : 'Crypt-Password'; $check{$pw_attrib} = $password;
1326 my $cust_svc = $self->cust_svc;
1327 die "FATAL: no cust_svc record for svc_acct.svcnum ". $self->svcnum. "\n"
1329 my $cust_pkg = $cust_svc->cust_pkg;
1330 if ( $cust_pkg && $cust_pkg->part_pkg->is_prepaid && $cust_pkg->bill ) {
1331 $check{'Expiration'} = time2str('%B %e %Y %T', $cust_pkg->bill ); #http://lists.cistron.nl/pipermail/freeradius-users/2005-January/040184.html
1340 This method instructs the object to "snapshot" or freeze RADIUS check and
1341 reply attributes to the current values.
1345 #bah, my english is too broken this morning
1346 #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
1347 #the FS::cust_pkg's replace method to trigger the correct export updates when
1348 #package dates change)
1353 $self->{$_} = { $self->$_() }
1354 foreach qw( radius_reply radius_check );
1358 =item forget_snapshot
1360 This methos instructs the object to forget any previously snapshotted
1361 RADIUS check and reply attributes.
1365 sub forget_snapshot {
1369 foreach qw( radius_reply radius_check );
1373 =item domain [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1375 Returns the domain associated with this account.
1377 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1384 die "svc_acct.domsvc is null for svcnum ". $self->svcnum unless $self->domsvc;
1385 my $svc_domain = $self->svc_domain(@_)
1386 or die "no svc_domain.svcnum for svc_acct.domsvc ". $self->domsvc;
1387 $svc_domain->domain;
1392 Returns the FS::svc_domain record for this account's domain (see
1397 # FS::h_svc_acct has a history-aware svc_domain override
1402 ? $self->{'_domsvc'}
1403 : qsearchs( 'svc_domain', { 'svcnum' => $self->domsvc } );
1408 Returns the FS::cust_svc record for this account (see L<FS::cust_svc>).
1412 #inherited from svc_Common
1414 =item email [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1416 Returns an email address associated with the account.
1418 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1425 $self->username. '@'. $self->domain(@_);
1430 Returns an array of FS::acct_snarf records associated with the account.
1431 If the acct_snarf table does not exist or there are no associated records,
1432 an empty list is returned
1438 return () unless dbdef->table('acct_snarf');
1439 eval "use FS::acct_snarf;";
1441 qsearch('acct_snarf', { 'svcnum' => $self->svcnum } );
1444 =item decrement_upbytes OCTETS
1446 Decrements the I<upbytes> field of this record by the given amount. If there
1447 is an error, returns the error, otherwise returns false.
1451 sub decrement_upbytes {
1452 shift->_op_usage('-', 'upbytes', @_);
1455 =item increment_upbytes OCTETS
1457 Increments the I<upbytes> field of this record by the given amount. If there
1458 is an error, returns the error, otherwise returns false.
1462 sub increment_upbytes {
1463 shift->_op_usage('+', 'upbytes', @_);
1466 =item decrement_downbytes OCTETS
1468 Decrements the I<downbytes> field of this record by the given amount. If there
1469 is an error, returns the error, otherwise returns false.
1473 sub decrement_downbytes {
1474 shift->_op_usage('-', 'downbytes', @_);
1477 =item increment_downbytes OCTETS
1479 Increments the I<downbytes> field of this record by the given amount. If there
1480 is an error, returns the error, otherwise returns false.
1484 sub increment_downbytes {
1485 shift->_op_usage('+', 'downbytes', @_);
1488 =item decrement_totalbytes OCTETS
1490 Decrements the I<totalbytes> field of this record by the given amount. If there
1491 is an error, returns the error, otherwise returns false.
1495 sub decrement_totalbytes {
1496 shift->_op_usage('-', 'totalbytes', @_);
1499 =item increment_totalbytes OCTETS
1501 Increments the I<totalbytes> field of this record by the given amount. If there
1502 is an error, returns the error, otherwise returns false.
1506 sub increment_totalbytes {
1507 shift->_op_usage('+', 'totalbytes', @_);
1510 =item decrement_seconds SECONDS
1512 Decrements the I<seconds> field of this record by the given amount. If there
1513 is an error, returns the error, otherwise returns false.
1517 sub decrement_seconds {
1518 shift->_op_usage('-', 'seconds', @_);
1521 =item increment_seconds SECONDS
1523 Increments the I<seconds> field of this record by the given amount. If there
1524 is an error, returns the error, otherwise returns false.
1528 sub increment_seconds {
1529 shift->_op_usage('+', 'seconds', @_);
1537 my %op2condition = (
1538 '-' => sub { my($self, $column, $amount) = @_;
1539 $self->$column - $amount <= 0;
1541 '+' => sub { my($self, $column, $amount) = @_;
1542 $self->$column + $amount > 0;
1545 my %op2warncondition = (
1546 '-' => sub { my($self, $column, $amount) = @_;
1547 my $threshold = $column . '_threshold';
1548 $self->$column - $amount <= $self->$threshold + 0;
1550 '+' => sub { my($self, $column, $amount) = @_;
1551 $self->$column + $amount > 0;
1556 my( $self, $op, $column, $amount ) = @_;
1558 warn "$me _op_usage called for $column on svcnum ". $self->svcnum.
1559 ' ('. $self->email. "): $op $amount\n"
1562 return '' unless $amount;
1564 local $SIG{HUP} = 'IGNORE';
1565 local $SIG{INT} = 'IGNORE';
1566 local $SIG{QUIT} = 'IGNORE';
1567 local $SIG{TERM} = 'IGNORE';
1568 local $SIG{TSTP} = 'IGNORE';
1569 local $SIG{PIPE} = 'IGNORE';
1571 my $oldAutoCommit = $FS::UID::AutoCommit;
1572 local $FS::UID::AutoCommit = 0;
1575 my $sql = "UPDATE svc_acct SET $column = ".
1576 " CASE WHEN $column IS NULL THEN 0 ELSE $column END ". #$column||0
1577 " $op ? WHERE svcnum = ?";
1581 my $sth = $dbh->prepare( $sql )
1582 or die "Error preparing $sql: ". $dbh->errstr;
1583 my $rv = $sth->execute($amount, $self->svcnum);
1584 die "Error executing $sql: ". $sth->errstr
1585 unless defined($rv);
1586 die "Can't update $column for svcnum". $self->svcnum
1589 my $action = $op2action{$op};
1591 if ( &{$op2condition{$op}}($self, $column, $amount) ) {
1592 foreach my $part_export ( $self->cust_svc->part_svc->part_export ) {
1593 if ($part_export->option('overlimit_groups'), 1) {
1595 my $other = new FS::svc_acct $self->hashref;
1596 my $groups = &{ $self->_fieldhandlers->{'usergroup'} }
1597 ($self, $part_export->option('overlimit_groups'));
1598 $other->usergroup( $groups );
1599 if ($action eq 'suspend'){
1600 $new = $other; $old = $self;
1602 $new = $self; $old = $other;
1604 my $error = $part_export->export_replace($new, $old);
1605 $error ||= $self->overlimit($action);
1607 $dbh->rollback if $oldAutoCommit;
1608 return "Error replacing radius groups in export, ${op}: $error";
1614 if ( $conf->exists("svc_acct-usage_$action")
1615 && &{$op2condition{$op}}($self, $column, $amount) ) {
1616 #my $error = $self->$action();
1617 my $error = $self->cust_svc->cust_pkg->$action();
1618 $error ||= $self->overlimit($action);
1620 $dbh->rollback if $oldAutoCommit;
1621 return "Error ${action}ing: $error";
1625 if ($warning_template && &{$op2warncondition{$op}}($self, $column, $amount)) {
1626 my $wqueue = new FS::queue {
1627 'svcnum' => $self->svcnum,
1628 'job' => 'FS::svc_acct::reached_threshold',
1633 $to = $warning_cc if &{$op2condition{$op}}($self, $column, $amount);
1637 my $error = $wqueue->insert(
1638 'svcnum' => $self->svcnum,
1640 'column' => $column,
1644 $dbh->rollback if $oldAutoCommit;
1645 return "Error queuing threshold activity: $error";
1649 warn "$me update successful; committing\n"
1651 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1657 my( $self, $valueref ) = @_;
1659 warn "$me set_usage called for svcnum ". $self->svcnum.
1660 ' ('. $self->email. "): ".
1661 join(', ', map { "$_ => " . $valueref->{$_}} keys %$valueref) . "\n"
1664 local $SIG{HUP} = 'IGNORE';
1665 local $SIG{INT} = 'IGNORE';
1666 local $SIG{QUIT} = 'IGNORE';
1667 local $SIG{TERM} = 'IGNORE';
1668 local $SIG{TSTP} = 'IGNORE';
1669 local $SIG{PIPE} = 'IGNORE';
1671 local $FS::svc_Common::noexport_hack = 1;
1672 my $oldAutoCommit = $FS::UID::AutoCommit;
1673 local $FS::UID::AutoCommit = 0;
1678 foreach my $field (keys %$valueref){
1679 $reset = 1 if $valueref->{$field};
1680 $self->setfield($field, $valueref->{$field});
1681 $self->setfield( $field.'_threshold',
1682 int($self->getfield($field)
1683 * ( $conf->exists('svc_acct-usage_threshold')
1684 ? 1 - $conf->config('svc_acct-usage_threshold')/100
1689 $handyhash{$field} = $self->getfield($field);
1690 $handyhash{$field.'_threshold'} = $self->getfield($field.'_threshold');
1692 #my $error = $self->replace; #NO! we avoid the call to ->check for
1693 #die $error if $error; #services not explicity changed via the UI
1695 my $sql = "UPDATE svc_acct SET " .
1696 join (',', map { "$_ = ?" } (keys %handyhash) ).
1697 " WHERE svcnum = ?";
1702 if (scalar(keys %handyhash)) {
1703 my $sth = $dbh->prepare( $sql )
1704 or die "Error preparing $sql: ". $dbh->errstr;
1705 my $rv = $sth->execute((grep{$_} values %handyhash), $self->svcnum);
1706 die "Error executing $sql: ". $sth->errstr
1707 unless defined($rv);
1708 die "Can't update usage for svcnum ". $self->svcnum
1713 my $error = $self->overlimit('unsuspend');
1715 foreach my $part_export ( $self->cust_svc->part_svc->part_export ) {
1716 if ($part_export->option('overlimit_groups'), 1) {
1717 my $old = new FS::svc_acct $self->hashref;
1718 my $groups = &{ $self->_fieldhandlers->{'usergroup'} }
1719 ($self, $part_export->option('overlimit_groups'));
1720 $old->usergroup( $groups );
1721 $error ||= $part_export->export_replace($self, $old);
1725 if ( $conf->exists("svc_acct-usage_unsuspend")) {
1726 $error ||= $self->cust_svc->cust_pkg->unsuspend;
1729 $dbh->rollback if $oldAutoCommit;
1730 return "Error unsuspending: $error";
1734 warn "$me update successful; committing\n"
1736 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1742 =item recharge HASHREF
1744 Increments usage columns by the amount specified in HASHREF as
1745 column=>amount pairs.
1750 my ($self, $vhash) = @_;
1753 warn "[$me] recharge called on $self: ". Dumper($self).
1754 "\nwith vhash: ". Dumper($vhash);
1757 my $oldAutoCommit = $FS::UID::AutoCommit;
1758 local $FS::UID::AutoCommit = 0;
1762 foreach my $column (keys %$vhash){
1763 $error ||= $self->_op_usage('+', $column, $vhash->{$column});
1767 $dbh->rollback if $oldAutoCommit;
1769 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1774 =item is_rechargeable
1776 Returns true if this svc_account can be "recharged" and false otherwise.
1780 sub is_rechargable {
1782 $self->seconds ne ''
1783 || $self->upbytes ne ''
1784 || $self->downbytes ne ''
1785 || $self->totalbytes ne '';
1788 =item seconds_since TIMESTAMP
1790 Returns the number of seconds this account has been online since TIMESTAMP,
1791 according to the session monitor (see L<FS::Session>).
1793 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1794 L<Time::Local> and L<Date::Parse> for conversion functions.
1798 #note: POD here, implementation in FS::cust_svc
1801 $self->cust_svc->seconds_since(@_);
1804 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1806 Returns the numbers of seconds this account has been online between
1807 TIMESTAMP_START (inclusive) and TIMESTAMP_END (exclusive), according to an
1808 external SQL radacct table, specified via sqlradius export. Sessions which
1809 started in the specified range but are still open are counted from session
1810 start to the end of the range (unless they are over 1 day old, in which case
1811 they are presumed missing their stop record and not counted). Also, sessions
1812 which end in the range but started earlier are counted from the start of the
1813 range to session end. Finally, sessions which start before the range but end
1814 after are counted for the entire range.
1816 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1817 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1822 #note: POD here, implementation in FS::cust_svc
1823 sub seconds_since_sqlradacct {
1825 $self->cust_svc->seconds_since_sqlradacct(@_);
1828 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
1830 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
1831 in this package for sessions ending between TIMESTAMP_START (inclusive) and
1832 TIMESTAMP_END (exclusive).
1834 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1835 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1840 #note: POD here, implementation in FS::cust_svc
1841 sub attribute_since_sqlradacct {
1843 $self->cust_svc->attribute_since_sqlradacct(@_);
1846 =item get_session_history TIMESTAMP_START TIMESTAMP_END
1848 Returns an array of hash references of this customers login history for the
1849 given time range. (document this better)
1853 sub get_session_history {
1855 $self->cust_svc->get_session_history(@_);
1858 =item get_cdrs TIMESTAMP_START TIMESTAMP_END [ 'OPTION' => 'VALUE ... ]
1863 my($self, $start, $end, %opt ) = @_;
1865 my $did = $self->username; #yup
1867 my $prefix = $opt{'default_prefix'}; #convergent.au '+61'
1869 my $for_update = $opt{'for_update'} ? 'FOR UPDATE' : '';
1871 #SELECT $for_update * FROM cdr
1872 # WHERE calldate >= $start #need a conversion
1873 # AND calldate < $end #ditto
1874 # AND ( charged_party = "$did"
1875 # OR charged_party = "$prefix$did" #if length($prefix);
1876 # OR ( ( charged_party IS NULL OR charged_party = '' )
1878 # ( src = "$did" OR src = "$prefix$did" ) # if length($prefix)
1881 # AND ( freesidestatus IS NULL OR freesidestatus = '' )
1884 if ( length($prefix) ) {
1886 " AND ( charged_party = '$did'
1887 OR charged_party = '$prefix$did'
1888 OR ( ( charged_party IS NULL OR charged_party = '' )
1890 ( src = '$did' OR src = '$prefix$did' )
1896 " AND ( charged_party = '$did'
1897 OR ( ( charged_party IS NULL OR charged_party = '' )
1907 'select' => "$for_update *",
1910 #( freesidestatus IS NULL OR freesidestatus = '' )
1911 'freesidestatus' => '',
1913 'extra_sql' => $charged_or_src,
1921 Returns all RADIUS groups for this account (see L<FS::radius_usergroup>).
1927 if ( $self->usergroup ) {
1928 confess "explicitly specified usergroup not an arrayref: ". $self->usergroup
1929 unless ref($self->usergroup) eq 'ARRAY';
1930 #when provisioning records, export callback runs in svc_Common.pm before
1931 #radius_usergroup records can be inserted...
1932 @{$self->usergroup};
1934 map { $_->groupname }
1935 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } );
1939 =item clone_suspended
1941 Constructor used by FS::part_export::_export_suspend fallback. Document
1946 sub clone_suspended {
1948 my %hash = $self->hash;
1949 $hash{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1950 new FS::svc_acct \%hash;
1953 =item clone_kludge_unsuspend
1955 Constructor used by FS::part_export::_export_unsuspend fallback. Document
1960 sub clone_kludge_unsuspend {
1962 my %hash = $self->hash;
1963 $hash{_password} = '';
1964 new FS::svc_acct \%hash;
1967 =item check_password
1969 Checks the supplied password against the (possibly encrypted) password in the
1970 database. Returns true for a successful authentication, false for no match.
1972 Currently supported encryptions are: classic DES crypt() and MD5
1976 sub check_password {
1977 my($self, $check_password) = @_;
1979 #remove old-style SUSPENDED kludge, they should be allowed to login to
1980 #self-service and pay up
1981 ( my $password = $self->_password ) =~ s/^\*SUSPENDED\* //;
1983 if ( $self->_password_encoding eq 'ldap' ) {
1985 my $auth = from_rfc2307 Authen::Passphrase $self->_password;
1986 return $auth->match($check_password);
1988 } elsif ( $self->_password_encoding eq 'crypt' ) {
1990 my $auth = from_crypt Authen::Passphrase $self->_password;
1991 return $auth->match($check_password);
1993 } elsif ( $self->_password_encoding eq 'plain' ) {
1995 return $check_password eq $password;
1999 #XXX this could be replaced with Authen::Passphrase stuff
2001 if ( $password =~ /^(\*|!!?)$/ ) { #no self-service login
2003 } elsif ( length($password) < 13 ) { #plaintext
2004 $check_password eq $password;
2005 } elsif ( length($password) == 13 ) { #traditional DES crypt
2006 crypt($check_password, $password) eq $password;
2007 } elsif ( $password =~ /^\$1\$/ ) { #MD5 crypt
2008 unix_md5_crypt($check_password, $password) eq $password;
2009 } elsif ( $password =~ /^\$2a?\$/ ) { #Blowfish
2010 warn "Can't check password: Blowfish encryption not yet supported, ".
2011 "svcnum ". $self->svcnum. "\n";
2014 warn "Can't check password: Unrecognized encryption for svcnum ".
2015 $self->svcnum. "\n";
2023 =item crypt_password [ DEFAULT_ENCRYPTION_TYPE ]
2025 Returns an encrypted password, either by passing through an encrypted password
2026 in the database or by encrypting a plaintext password from the database.
2028 The optional DEFAULT_ENCRYPTION_TYPE parameter can be set to I<crypt> (classic
2029 UNIX DES crypt), I<md5> (md5 crypt supported by most modern Linux and BSD
2030 distrubtions), or (eventually) I<blowfish> (blowfish hashing supported by
2031 OpenBSD, SuSE, other Linux distibutions with pam_unix2, etc.). The default
2032 encryption type is only used if the password is not already encrypted in the
2037 sub crypt_password {
2040 if ( $self->_password_encoding eq 'ldap' ) {
2042 if ( $self->_password =~ /^\{(PLAIN|CLEARTEXT)\}(.+)$/ ) {
2045 #XXX this could be replaced with Authen::Passphrase stuff
2047 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2048 if ( $encryption eq 'crypt' ) {
2051 $saltset[int(rand(64))].$saltset[int(rand(64))]
2053 } elsif ( $encryption eq 'md5' ) {
2054 unix_md5_crypt( $self->_password );
2055 } elsif ( $encryption eq 'blowfish' ) {
2056 croak "unknown encryption method $encryption";
2058 croak "unknown encryption method $encryption";
2061 } elsif ( $self->_password =~ /^\{CRYPT\}(.+)$/ ) {
2065 } elsif ( $self->_password_encoding eq 'crypt' ) {
2067 return $self->_password;
2069 } elsif ( $self->_password_encoding eq 'plain' ) {
2071 #XXX this could be replaced with Authen::Passphrase stuff
2073 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2074 if ( $encryption eq 'crypt' ) {
2077 $saltset[int(rand(64))].$saltset[int(rand(64))]
2079 } elsif ( $encryption eq 'md5' ) {
2080 unix_md5_crypt( $self->_password );
2081 } elsif ( $encryption eq 'blowfish' ) {
2082 croak "unknown encryption method $encryption";
2084 croak "unknown encryption method $encryption";
2089 if ( length($self->_password) == 13
2090 || $self->_password =~ /^\$(1|2a?)\$/
2091 || $self->_password =~ /^(\*|NP|\*LK\*|!!?)$/
2097 #XXX this could be replaced with Authen::Passphrase stuff
2099 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2100 if ( $encryption eq 'crypt' ) {
2103 $saltset[int(rand(64))].$saltset[int(rand(64))]
2105 } elsif ( $encryption eq 'md5' ) {
2106 unix_md5_crypt( $self->_password );
2107 } elsif ( $encryption eq 'blowfish' ) {
2108 croak "unknown encryption method $encryption";
2110 croak "unknown encryption method $encryption";
2119 =item ldap_password [ DEFAULT_ENCRYPTION_TYPE ]
2121 Returns an encrypted password in "LDAP" format, with a curly-bracked prefix
2122 describing the format, for example, "{PLAIN}himom", "{CRYPT}94pAVyK/4oIBk" or
2123 "{MD5}5426824942db4253f87a1009fd5d2d4".
2125 The optional DEFAULT_ENCRYPTION_TYPE is not yet used, but the idea is for it
2126 to work the same as the B</crypt_password> method.
2132 #eventually should check a "password-encoding" field
2134 if ( $self->_password_encoding eq 'ldap' ) {
2136 return $self->_password;
2138 } elsif ( $self->_password_encoding eq 'crypt' ) {
2140 if ( length($self->_password) == 13 ) { #crypt
2141 return '{CRYPT}'. $self->_password;
2142 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2144 #} elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2145 # die "Blowfish encryption not supported in this context, svcnum ".
2146 # $self->svcnum. "\n";
2148 warn "encryption method not (yet?) supported in LDAP context";
2149 return '{CRYPT}*'; #unsupported, should not auth
2152 } elsif ( $self->_password_encoding eq 'plain' ) {
2154 return '{PLAIN}'. $self->_password;
2156 #return '{CLEARTEXT}'. $self->_password; #?
2160 if ( length($self->_password) == 13 ) { #crypt
2161 return '{CRYPT}'. $self->_password;
2162 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2164 } elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2165 warn "Blowfish encryption not supported in this context, svcnum ".
2166 $self->svcnum. "\n";
2169 #are these two necessary anymore?
2170 } elsif ( $self->_password =~ /^(\w{48})$/ ) { #LDAP SSHA
2171 return '{SSHA}'. $1;
2172 } elsif ( $self->_password =~ /^(\w{64})$/ ) { #LDAP NS-MTA-MD5
2173 return '{NS-MTA-MD5}'. $1;
2176 return '{PLAIN}'. $self->_password;
2178 #return '{CLEARTEXT}'. $self->_password; #?
2180 #XXX this could be replaced with Authen::Passphrase stuff if it gets used
2181 #my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2182 #if ( $encryption eq 'crypt' ) {
2183 # return '{CRYPT}'. crypt(
2185 # $saltset[int(rand(64))].$saltset[int(rand(64))]
2187 #} elsif ( $encryption eq 'md5' ) {
2188 # unix_md5_crypt( $self->_password );
2189 #} elsif ( $encryption eq 'blowfish' ) {
2190 # croak "unknown encryption method $encryption";
2192 # croak "unknown encryption method $encryption";
2200 =item domain_slash_username
2202 Returns $domain/$username/
2206 sub domain_slash_username {
2208 $self->domain. '/'. $self->username. '/';
2211 =item virtual_maildir
2213 Returns $domain/maildirs/$username/
2217 sub virtual_maildir {
2219 $self->domain. '/maildirs/'. $self->username. '/';
2230 This is the FS::svc_acct job-queue-able version. It still uses
2231 FS::Misc::send_email under-the-hood.
2238 eval "use FS::Misc qw(send_email)";
2241 $opt{mimetype} ||= 'text/plain';
2242 $opt{mimetype} .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2244 my $error = send_email(
2245 'from' => $opt{from},
2247 'subject' => $opt{subject},
2248 'content-type' => $opt{mimetype},
2249 'body' => [ map "$_\n", split("\n", $opt{body}) ],
2251 die $error if $error;
2254 =item check_and_rebuild_fuzzyfiles
2258 sub check_and_rebuild_fuzzyfiles {
2259 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2260 -e "$dir/svc_acct.username"
2261 or &rebuild_fuzzyfiles;
2264 =item rebuild_fuzzyfiles
2268 sub rebuild_fuzzyfiles {
2270 use Fcntl qw(:flock);
2272 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2276 open(USERNAMELOCK,">>$dir/svc_acct.username")
2277 or die "can't open $dir/svc_acct.username: $!";
2278 flock(USERNAMELOCK,LOCK_EX)
2279 or die "can't lock $dir/svc_acct.username: $!";
2281 my @all_username = map $_->getfield('username'), qsearch('svc_acct', {});
2283 open (USERNAMECACHE,">$dir/svc_acct.username.tmp")
2284 or die "can't open $dir/svc_acct.username.tmp: $!";
2285 print USERNAMECACHE join("\n", @all_username), "\n";
2286 close USERNAMECACHE or die "can't close $dir/svc_acct.username.tmp: $!";
2288 rename "$dir/svc_acct.username.tmp", "$dir/svc_acct.username";
2298 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2299 open(USERNAMECACHE,"<$dir/svc_acct.username")
2300 or die "can't open $dir/svc_acct.username: $!";
2301 my @array = map { chomp; $_; } <USERNAMECACHE>;
2302 close USERNAMECACHE;
2306 =item append_fuzzyfiles USERNAME
2310 sub append_fuzzyfiles {
2311 my $username = shift;
2313 &check_and_rebuild_fuzzyfiles;
2315 use Fcntl qw(:flock);
2317 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2319 open(USERNAME,">>$dir/svc_acct.username")
2320 or die "can't open $dir/svc_acct.username: $!";
2321 flock(USERNAME,LOCK_EX)
2322 or die "can't lock $dir/svc_acct.username: $!";
2324 print USERNAME "$username\n";
2326 flock(USERNAME,LOCK_UN)
2327 or die "can't unlock $dir/svc_acct.username: $!";
2335 =item radius_usergroup_selector GROUPS_ARRAYREF [ SELECTNAME ]
2339 sub radius_usergroup_selector {
2340 my $sel_groups = shift;
2341 my %sel_groups = map { $_=>1 } @$sel_groups;
2343 my $selectname = shift || 'radius_usergroup';
2346 my $sth = $dbh->prepare(
2347 'SELECT DISTINCT(groupname) FROM radius_usergroup ORDER BY groupname'
2348 ) or die $dbh->errstr;
2349 $sth->execute() or die $sth->errstr;
2350 my @all_groups = map { $_->[0] } @{$sth->fetchall_arrayref};
2354 function ${selectname}_doadd(object) {
2355 var myvalue = object.${selectname}_add.value;
2356 var optionName = new Option(myvalue,myvalue,false,true);
2357 var length = object.$selectname.length;
2358 object.$selectname.options[length] = optionName;
2359 object.${selectname}_add.value = "";
2362 <SELECT MULTIPLE NAME="$selectname">
2365 foreach my $group ( @all_groups ) {
2366 $html .= qq(<OPTION VALUE="$group");
2367 if ( $sel_groups{$group} ) {
2368 $html .= ' SELECTED';
2369 $sel_groups{$group} = 0;
2371 $html .= ">$group</OPTION>\n";
2373 foreach my $group ( grep { $sel_groups{$_} } keys %sel_groups ) {
2374 $html .= qq(<OPTION VALUE="$group" SELECTED>$group</OPTION>\n);
2376 $html .= '</SELECT>';
2378 $html .= qq!<BR><INPUT TYPE="text" NAME="${selectname}_add">!.
2379 qq!<INPUT TYPE="button" VALUE="Add new group" onClick="${selectname}_doadd(this.form)">!;
2384 =item reached_threshold
2386 Performs some activities when svc_acct thresholds (such as number of seconds
2387 remaining) are reached.
2391 sub reached_threshold {
2394 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } );
2395 die "Cannot find svc_acct with svcnum " . $opt{'svcnum'} unless $svc_acct;
2397 if ( $opt{'op'} eq '+' ){
2398 $svc_acct->setfield( $opt{'column'}.'_threshold',
2399 int($svc_acct->getfield($opt{'column'})
2400 * ( $conf->exists('svc_acct-usage_threshold')
2401 ? $conf->config('svc_acct-usage_threshold')/100
2406 my $error = $svc_acct->replace;
2407 die $error if $error;
2408 }elsif ( $opt{'op'} eq '-' ){
2410 my $threshold = $svc_acct->getfield( $opt{'column'}.'_threshold' );
2411 return '' if ($threshold eq '' );
2413 $svc_acct->setfield( $opt{'column'}.'_threshold', 0 );
2414 my $error = $svc_acct->replace;
2415 die $error if $error; # email next time, i guess
2417 if ( $warning_template ) {
2418 eval "use FS::Misc qw(send_email)";
2421 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2422 my $cust_main = $cust_pkg->cust_main;
2424 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ }
2425 $cust_main->invoicing_list,
2426 ($opt{'to'} ? $opt{'to'} : ())
2429 my $mimetype = $warning_mimetype;
2430 $mimetype .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2432 my $body = $warning_template->fill_in( HASH => {
2433 'custnum' => $cust_main->custnum,
2434 'username' => $svc_acct->username,
2435 'password' => $svc_acct->_password,
2436 'first' => $cust_main->first,
2437 'last' => $cust_main->getfield('last'),
2438 'pkg' => $cust_pkg->part_pkg->pkg,
2439 'column' => $opt{'column'},
2440 'amount' => $svc_acct->getfield($opt{'column'}),
2441 'threshold' => $threshold,
2445 my $error = send_email(
2446 'from' => $warning_from,
2448 'subject' => $warning_subject,
2449 'content-type' => $mimetype,
2450 'body' => [ map "$_\n", split("\n", $body) ],
2452 die $error if $error;
2455 die "unknown op: " . $opt{'op'};
2463 The $recref stuff in sub check should be cleaned up.
2465 The suspend, unsuspend and cancel methods update the database, but not the
2466 current object. This is probably a bug as it's unexpected and
2469 radius_usergroup_selector? putting web ui components in here? they should
2470 probably live somewhere else...
2472 insertion of RADIUS group stuff in insert could be done with child_objects now
2473 (would probably clean up export of them too)
2477 L<FS::svc_Common>, edit/part_svc.cgi from an installed web interface,
2478 export.html from the base documentation, L<FS::Record>, L<FS::Conf>,
2479 L<FS::cust_svc>, L<FS::part_svc>, L<FS::cust_pkg>, L<FS::queue>,
2480 L<freeside-queued>), L<FS::svc_acct_pop>,
2481 schema.html from the base documentation.