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 $welcome_template $welcome_from $welcome_subject $welcome_mimetype
12 $warning_template $warning_from $warning_subject $warning_mimetype
15 $radius_password $radius_ip
21 use Crypt::PasswdMD5 1.2;
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('welcome_email') ) {
68 $welcome_template = new Text::Template (
70 SOURCE => [ map "$_\n", $conf->config('welcome_email') ]
71 ) or warn "can't create welcome email template: $Text::Template::ERROR";
72 $welcome_from = $conf->config('welcome_email-from'); # || 'your-isp-is-dum'
73 $welcome_subject = $conf->config('welcome_email-subject') || 'Welcome';
74 $welcome_mimetype = $conf->config('welcome_email-mimetype') || 'text/plain';
76 $welcome_template = '';
78 $welcome_subject = '';
79 $welcome_mimetype = '';
81 if ( $conf->exists('warning_email') ) {
82 $warning_template = new Text::Template (
84 SOURCE => [ map "$_\n", $conf->config('warning_email') ]
85 ) or warn "can't create warning email template: $Text::Template::ERROR";
86 $warning_from = $conf->config('warning_email-from'); # || 'your-isp-is-dum'
87 $warning_subject = $conf->config('warning_email-subject') || 'Warning';
88 $warning_mimetype = $conf->config('warning_email-mimetype') || 'text/plain';
89 $warning_cc = $conf->config('warning_email-cc');
91 $warning_template = '';
93 $warning_subject = '';
94 $warning_mimetype = '';
97 $smtpmachine = $conf->config('smtpmachine');
98 $radius_password = $conf->config('radius-password') || 'Password';
99 $radius_ip = $conf->config('radius-ip') || 'Framed-IP-Address';
102 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '.' , '/' );
103 @pw_set = ( 'a'..'z', 'A'..'Z', '0'..'9', '(', ')', '#', '!', '.', ',' );
107 my ( $hashref, $cache ) = @_;
108 if ( $hashref->{'svc_acct_svcnum'} ) {
109 $self->{'_domsvc'} = FS::svc_domain->new( {
110 'svcnum' => $hashref->{'domsvc'},
111 'domain' => $hashref->{'svc_acct_domain'},
112 'catchall' => $hashref->{'svc_acct_catchall'},
119 FS::svc_acct - Object methods for svc_acct records
125 $record = new FS::svc_acct \%hash;
126 $record = new FS::svc_acct { 'column' => 'value' };
128 $error = $record->insert;
130 $error = $new_record->replace($old_record);
132 $error = $record->delete;
134 $error = $record->check;
136 $error = $record->suspend;
138 $error = $record->unsuspend;
140 $error = $record->cancel;
142 %hash = $record->radius;
144 %hash = $record->radius_reply;
146 %hash = $record->radius_check;
148 $domain = $record->domain;
150 $svc_domain = $record->svc_domain;
152 $email = $record->email;
154 $seconds_since = $record->seconds_since($timestamp);
158 An FS::svc_acct object represents an account. FS::svc_acct inherits from
159 FS::svc_Common. The following fields are currently supported:
163 =item svcnum - primary key (assigned automatcially for new accounts)
167 =item _password - generated if blank
169 =item sec_phrase - security phrase
171 =item popnum - Point of presence (see L<FS::svc_acct_pop>)
179 =item dir - set automatically if blank (and uid is not)
183 =item quota - (unimplementd)
185 =item slipip - IP address
195 =item domsvc - svcnum from svc_domain
197 =item radius_I<Radius_Attribute> - I<Radius-Attribute> (reply)
199 =item rc_I<Radius_Attribute> - I<Radius-Attribute> (check)
209 Creates a new account. To add the account to the database, see L<"insert">.
216 'longname_plural' => 'Access accounts and mailboxes',
217 'sorts' => [ 'username', 'uid', ],
218 'display_weight' => 10,
219 'cancel_weight' => 50,
221 'dir' => 'Home directory',
224 def_label => 'UID (set to fixed and blank for no UIDs)',
227 'slipip' => 'IP address',
228 # 'popnum' => qq!<A HREF="$p/browse/svc_acct_pop.cgi/">POP number</A>!,
230 label => 'Access number',
232 select_table => 'svc_acct_pop',
233 select_key => 'popnum',
234 select_label => 'city',
239 disable_default => 1,
245 disable_inventory => 1,
247 '_password' => 'Password',
250 def_label => 'GID (when blank, defaults to UID)',
254 #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)',
256 def_label=> 'Shell (set to blank for no shell tracking)',
258 select_list => [ $conf->config('shells') ],
259 disable_inventory => 1,
261 'finger' => 'Real name (GECOS)',
264 def_label => 'svcnum from svc_domain',
266 select_table => 'svc_domain',
267 select_key => 'svcnum',
268 select_label => 'domain',
269 disable_inventory => 1,
272 label => 'RADIUS groups',
273 type => 'radius_usergroup_selector',
274 disable_inventory => 1,
276 'seconds' => { label => 'Seconds',
278 disable_inventory => 1,
284 sub table { 'svc_acct'; }
288 #false laziness with edit/svc_acct.cgi
290 my( $self, $groups ) = @_;
291 if ( ref($groups) eq 'ARRAY' ) {
293 } elsif ( length($groups) ) {
294 [ split(/\s*,\s*/, $groups) ];
302 =item search_sql STRING
304 Class method which returns an SQL fragment to search for the given string.
309 my( $class, $string ) = @_;
310 if ( $string =~ /^([^@]+)@([^@]+)$/ ) {
311 my( $username, $domain ) = ( $1, $2 );
312 my $q_username = dbh->quote($username);
313 my @svc_domain = qsearch('svc_domain', { 'domain' => $domain } );
315 "svc_acct.username = $q_username AND ( ".
316 join( ' OR ', map { "svc_acct.domsvc = ". $_->svcnum; } @svc_domain ).
321 } elsif ( $string =~ /^(\d{1,3}\.){3}\d{1,3}$/ ) {
323 $class->search_sql_field('slipip', $string ).
325 $class->search_sql_field('username', $string ).
328 $class->search_sql_field('username', $string);
332 =item label [ END_TIMESTAMP [ START_TIMESTAMP ] ]
334 Returns the "username@domain" string for this account.
336 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
348 =item insert [ , OPTION => VALUE ... ]
350 Adds this account to the database. If there is an error, returns the error,
351 otherwise returns false.
353 The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be
354 defined. An FS::cust_svc record will be created and inserted.
356 The additional field I<usergroup> can optionally be defined; if so it should
357 contain an arrayref of group names. See L<FS::radius_usergroup>.
359 The additional field I<child_objects> can optionally be defined; if so it
360 should contain an arrayref of FS::tablename objects. They will have their
361 svcnum fields set and will be inserted after this record, but before any
362 exports are run. Each element of the array can also optionally be a
363 two-element array reference containing the child object and the name of an
364 alternate field to be filled in with the newly-inserted svcnum, for example
365 C<[ $svc_forward, 'srcsvc' ]>
367 Currently available options are: I<depend_jobnum>
369 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
370 jobnums), all provisioning jobs will have a dependancy on the supplied
371 jobnum(s) (they will not run until the specific job(s) complete(s)).
373 (TODOC: L<FS::queue> and L<freeside-queued>)
375 (TODOC: new exports!)
384 warn "[$me] insert called on $self: ". Dumper($self).
385 "\nwith options: ". Dumper(%options);
388 local $SIG{HUP} = 'IGNORE';
389 local $SIG{INT} = 'IGNORE';
390 local $SIG{QUIT} = 'IGNORE';
391 local $SIG{TERM} = 'IGNORE';
392 local $SIG{TSTP} = 'IGNORE';
393 local $SIG{PIPE} = 'IGNORE';
395 my $oldAutoCommit = $FS::UID::AutoCommit;
396 local $FS::UID::AutoCommit = 0;
399 my $error = $self->check;
400 return $error if $error;
402 if ( $self->svcnum && qsearchs('cust_svc',{'svcnum'=>$self->svcnum}) ) {
403 my $cust_svc = qsearchs('cust_svc',{'svcnum'=>$self->svcnum});
404 unless ( $cust_svc ) {
405 $dbh->rollback if $oldAutoCommit;
406 return "no cust_svc record found for svcnum ". $self->svcnum;
408 $self->pkgnum($cust_svc->pkgnum);
409 $self->svcpart($cust_svc->svcpart);
412 $error = $self->_check_duplicate;
414 $dbh->rollback if $oldAutoCommit;
419 $error = $self->SUPER::insert(
420 'jobnums' => \@jobnums,
421 'child_objects' => $self->child_objects,
425 $dbh->rollback if $oldAutoCommit;
429 if ( $self->usergroup ) {
430 foreach my $groupname ( @{$self->usergroup} ) {
431 my $radius_usergroup = new FS::radius_usergroup ( {
432 svcnum => $self->svcnum,
433 groupname => $groupname,
435 my $error = $radius_usergroup->insert;
437 $dbh->rollback if $oldAutoCommit;
443 unless ( $skip_fuzzyfiles ) {
444 $error = $self->queue_fuzzyfiles_update;
446 $dbh->rollback if $oldAutoCommit;
447 return "updating fuzzy search cache: $error";
451 my $cust_pkg = $self->cust_svc->cust_pkg;
454 my $cust_main = $cust_pkg->cust_main;
456 if ( $conf->exists('emailinvoiceautoalways')
457 || $conf->exists('emailinvoiceauto')
458 && ! $cust_main->invoicing_list_emailonly
460 my @invoicing_list = $cust_main->invoicing_list;
461 push @invoicing_list, $self->email;
462 $cust_main->invoicing_list(\@invoicing_list);
467 if ( $welcome_template && $cust_pkg ) {
468 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
470 my $wqueue = new FS::queue {
471 'svcnum' => $self->svcnum,
472 'job' => 'FS::svc_acct::send_email'
474 my $error = $wqueue->insert(
476 'from' => $welcome_from,
477 'subject' => $welcome_subject,
478 'mimetype' => $welcome_mimetype,
479 'body' => $welcome_template->fill_in( HASH => {
480 'custnum' => $self->custnum,
481 'username' => $self->username,
482 'password' => $self->_password,
483 'first' => $cust_main->first,
484 'last' => $cust_main->getfield('last'),
485 'pkg' => $cust_pkg->part_pkg->pkg,
489 $dbh->rollback if $oldAutoCommit;
490 return "error queuing welcome email: $error";
493 if ( $options{'depend_jobnum'} ) {
494 warn "$me depend_jobnum found; adding to welcome email dependancies"
496 if ( ref($options{'depend_jobnum'}) ) {
497 warn "$me adding jobs ". join(', ', @{$options{'depend_jobnum'}} ).
498 "to welcome email dependancies"
500 push @jobnums, @{ $options{'depend_jobnum'} };
502 warn "$me adding job $options{'depend_jobnum'} ".
503 "to welcome email dependancies"
505 push @jobnums, $options{'depend_jobnum'};
509 foreach my $jobnum ( @jobnums ) {
510 my $error = $wqueue->depend_insert($jobnum);
512 $dbh->rollback if $oldAutoCommit;
513 return "error queuing welcome email job dependancy: $error";
523 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
529 Deletes this account from the database. If there is an error, returns the
530 error, otherwise returns false.
532 The corresponding FS::cust_svc record will be deleted as well.
534 (TODOC: new exports!)
541 return "can't delete system account" if $self->_check_system;
543 return "Can't delete an account which is a (svc_forward) source!"
544 if qsearch( 'svc_forward', { 'srcsvc' => $self->svcnum } );
546 return "Can't delete an account which is a (svc_forward) destination!"
547 if qsearch( 'svc_forward', { 'dstsvc' => $self->svcnum } );
549 return "Can't delete an account with (svc_www) web service!"
550 if qsearch( 'svc_www', { 'usersvc' => $self->svcnum } );
552 # what about records in session ? (they should refer to history table)
554 local $SIG{HUP} = 'IGNORE';
555 local $SIG{INT} = 'IGNORE';
556 local $SIG{QUIT} = 'IGNORE';
557 local $SIG{TERM} = 'IGNORE';
558 local $SIG{TSTP} = 'IGNORE';
559 local $SIG{PIPE} = 'IGNORE';
561 my $oldAutoCommit = $FS::UID::AutoCommit;
562 local $FS::UID::AutoCommit = 0;
565 foreach my $cust_main_invoice (
566 qsearch( 'cust_main_invoice', { 'dest' => $self->svcnum } )
568 unless ( defined($cust_main_invoice) ) {
569 warn "WARNING: something's wrong with qsearch";
572 my %hash = $cust_main_invoice->hash;
573 $hash{'dest'} = $self->email;
574 my $new = new FS::cust_main_invoice \%hash;
575 my $error = $new->replace($cust_main_invoice);
577 $dbh->rollback if $oldAutoCommit;
582 foreach my $svc_domain (
583 qsearch( 'svc_domain', { 'catchall' => $self->svcnum } )
585 my %hash = new FS::svc_domain->hash;
586 $hash{'catchall'} = '';
587 my $new = new FS::svc_domain \%hash;
588 my $error = $new->replace($svc_domain);
590 $dbh->rollback if $oldAutoCommit;
595 foreach my $radius_usergroup (
596 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } )
598 my $error = $radius_usergroup->delete;
600 $dbh->rollback if $oldAutoCommit;
605 my $error = $self->SUPER::delete;
607 $dbh->rollback if $oldAutoCommit;
611 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
615 =item replace OLD_RECORD
617 Replaces OLD_RECORD with this one in the database. If there is an error,
618 returns the error, otherwise returns false.
620 The additional field I<usergroup> can optionally be defined; if so it should
621 contain an arrayref of group names. See L<FS::radius_usergroup>.
627 my ( $new, $old ) = ( shift, shift );
629 warn "$me replacing $old with $new\n" if $DEBUG;
631 # We absolutely have to have an old vs. new record to make this work.
632 if (!defined($old)) {
633 $old = qsearchs( 'svc_acct', { 'svcnum' => $new->svcnum } );
636 return "can't modify system account" if $old->_check_system;
639 #no warnings 'numeric'; #alas, a 5.006-ism
642 foreach my $xid (qw( uid gid )) {
644 return "Can't change $xid!"
645 if ! $conf->exists("svc_acct-edit_$xid")
646 && $old->$xid() != $new->$xid()
647 && $new->cust_svc->part_svc->part_svc_column($xid)->columnflag ne 'F'
652 #change homdir when we change username
653 $new->setfield('dir', '') if $old->username ne $new->username;
655 local $SIG{HUP} = 'IGNORE';
656 local $SIG{INT} = 'IGNORE';
657 local $SIG{QUIT} = 'IGNORE';
658 local $SIG{TERM} = 'IGNORE';
659 local $SIG{TSTP} = 'IGNORE';
660 local $SIG{PIPE} = 'IGNORE';
662 my $oldAutoCommit = $FS::UID::AutoCommit;
663 local $FS::UID::AutoCommit = 0;
666 # redundant, but so $new->usergroup gets set
667 $error = $new->check;
668 return $error if $error;
670 $old->usergroup( [ $old->radius_groups ] );
672 warn $old->email. " old groups: ". join(' ',@{$old->usergroup}). "\n";
673 warn $new->email. "new groups: ". join(' ',@{$new->usergroup}). "\n";
675 if ( $new->usergroup ) {
676 #(sorta) false laziness with FS::part_export::sqlradius::_export_replace
677 my @newgroups = @{$new->usergroup};
678 foreach my $oldgroup ( @{$old->usergroup} ) {
679 if ( grep { $oldgroup eq $_ } @newgroups ) {
680 @newgroups = grep { $oldgroup ne $_ } @newgroups;
683 my $radius_usergroup = qsearchs('radius_usergroup', {
684 svcnum => $old->svcnum,
685 groupname => $oldgroup,
687 my $error = $radius_usergroup->delete;
689 $dbh->rollback if $oldAutoCommit;
690 return "error deleting radius_usergroup $oldgroup: $error";
694 foreach my $newgroup ( @newgroups ) {
695 my $radius_usergroup = new FS::radius_usergroup ( {
696 svcnum => $new->svcnum,
697 groupname => $newgroup,
699 my $error = $radius_usergroup->insert;
701 $dbh->rollback if $oldAutoCommit;
702 return "error adding radius_usergroup $newgroup: $error";
708 if ( $old->username ne $new->username || $old->domsvc != $new->domsvc ) {
709 $new->svcpart( $new->cust_svc->svcpart ) unless $new->svcpart;
710 $error = $new->_check_duplicate;
712 $dbh->rollback if $oldAutoCommit;
717 $error = $new->SUPER::replace($old);
719 $dbh->rollback if $oldAutoCommit;
720 return $error if $error;
723 if ( $new->username ne $old->username && ! $skip_fuzzyfiles ) {
724 $error = $new->queue_fuzzyfiles_update;
726 $dbh->rollback if $oldAutoCommit;
727 return "updating fuzzy search cache: $error";
731 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
735 =item queue_fuzzyfiles_update
737 Used by insert & replace to update the fuzzy search cache
741 sub queue_fuzzyfiles_update {
744 local $SIG{HUP} = 'IGNORE';
745 local $SIG{INT} = 'IGNORE';
746 local $SIG{QUIT} = 'IGNORE';
747 local $SIG{TERM} = 'IGNORE';
748 local $SIG{TSTP} = 'IGNORE';
749 local $SIG{PIPE} = 'IGNORE';
751 my $oldAutoCommit = $FS::UID::AutoCommit;
752 local $FS::UID::AutoCommit = 0;
755 my $queue = new FS::queue {
756 'svcnum' => $self->svcnum,
757 'job' => 'FS::svc_acct::append_fuzzyfiles'
759 my $error = $queue->insert($self->username);
761 $dbh->rollback if $oldAutoCommit;
762 return "queueing job (transaction rolled back): $error";
765 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
773 Suspends this account by calling export-specific suspend hooks. If there is
774 an error, returns the error, otherwise returns false.
776 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
782 return "can't suspend system account" if $self->_check_system;
783 $self->SUPER::suspend;
788 Unsuspends this account by by calling export-specific suspend hooks. If there
789 is an error, returns the error, otherwise returns false.
791 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
797 my %hash = $self->hash;
798 if ( $hash{_password} =~ /^\*SUSPENDED\* (.*)$/ ) {
799 $hash{_password} = $1;
800 my $new = new FS::svc_acct ( \%hash );
801 my $error = $new->replace($self);
802 return $error if $error;
805 $self->SUPER::unsuspend;
810 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
812 If the B<auto_unset_catchall> configuration option is set, this method will
813 automatically remove any references to the canceled service in the catchall
814 field of svc_domain. This allows packages that contain both a svc_domain and
815 its catchall svc_acct to be canceled in one step.
820 # Only one thing to do at this level
822 foreach my $svc_domain (
823 qsearch( 'svc_domain', { catchall => $self->svcnum } ) ) {
824 if($conf->exists('auto_unset_catchall')) {
825 my %hash = $svc_domain->hash;
826 $hash{catchall} = '';
827 my $new = new FS::svc_domain ( \%hash );
828 my $error = $new->replace($svc_domain);
829 return $error if $error;
831 return "cannot unprovision svc_acct #".$self->svcnum.
832 " while assigned as catchall for svc_domain #".$svc_domain->svcnum;
836 $self->SUPER::cancel;
842 Checks all fields to make sure this is a valid service. If there is an error,
843 returns the error, otherwise returns false. Called by the insert and replace
846 Sets any fixed values; see L<FS::part_svc>.
853 my($recref) = $self->hashref;
855 my $x = $self->setfixed( $self->_fieldhandlers );
856 return $x unless ref($x);
859 if ( $part_svc->part_svc_column('usergroup')->columnflag eq "F" ) {
861 [ split(',', $part_svc->part_svc_column('usergroup')->columnvalue) ] );
864 my $error = $self->ut_numbern('svcnum')
865 #|| $self->ut_number('domsvc')
866 || $self->ut_foreign_key('domsvc', 'svc_domain', 'svcnum' )
867 || $self->ut_textn('sec_phrase')
868 || $self->ut_snumbern('seconds')
869 || $self->ut_snumbern('upbytes')
870 || $self->ut_snumbern('downbytes')
871 || $self->ut_snumbern('totalbytes')
873 return $error if $error;
875 my $ulen = $usernamemax || $self->dbdef_table->column('username')->length;
876 if ( $username_uppercase ) {
877 $recref->{username} =~ /^([a-z0-9_\-\.\&\%]{$usernamemin,$ulen})$/i
878 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
879 $recref->{username} = $1;
881 $recref->{username} =~ /^([a-z0-9_\-\.\&\%]{$usernamemin,$ulen})$/
882 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
883 $recref->{username} = $1;
886 if ( $username_letterfirst ) {
887 $recref->{username} =~ /^[a-z]/ or return gettext('illegal_username');
888 } elsif ( $username_letter ) {
889 $recref->{username} =~ /[a-z]/ or return gettext('illegal_username');
891 if ( $username_noperiod ) {
892 $recref->{username} =~ /\./ and return gettext('illegal_username');
894 if ( $username_nounderscore ) {
895 $recref->{username} =~ /_/ and return gettext('illegal_username');
897 if ( $username_nodash ) {
898 $recref->{username} =~ /\-/ and return gettext('illegal_username');
900 unless ( $username_ampersand ) {
901 $recref->{username} =~ /\&/ and return gettext('illegal_username');
903 if ( $password_noampersand ) {
904 $recref->{_password} =~ /\&/ and return gettext('illegal_password');
906 if ( $password_noexclamation ) {
907 $recref->{_password} =~ /\!/ and return gettext('illegal_password');
909 unless ( $username_percent ) {
910 $recref->{username} =~ /\%/ and return gettext('illegal_username');
913 $recref->{popnum} =~ /^(\d*)$/ or return "Illegal popnum: ".$recref->{popnum};
914 $recref->{popnum} = $1;
915 return "Unknown popnum" unless
916 ! $recref->{popnum} ||
917 qsearchs('svc_acct_pop',{'popnum'=> $recref->{popnum} } );
919 unless ( $part_svc->part_svc_column('uid')->columnflag eq 'F' ) {
921 $recref->{uid} =~ /^(\d*)$/ or return "Illegal uid";
922 $recref->{uid} = $1 eq '' ? $self->unique('uid') : $1;
924 $recref->{gid} =~ /^(\d*)$/ or return "Illegal gid";
925 $recref->{gid} = $1 eq '' ? $recref->{uid} : $1;
926 #not all systems use gid=uid
927 #you can set a fixed gid in part_svc
929 return "Only root can have uid 0"
930 if $recref->{uid} == 0
931 && $recref->{username} !~ /^(root|toor|smtp)$/;
933 unless ( $recref->{username} eq 'sync' ) {
934 if ( grep $_ eq $recref->{shell}, @shells ) {
935 $recref->{shell} = (grep $_ eq $recref->{shell}, @shells)[0];
937 return "Illegal shell \`". $self->shell. "\'; ".
938 $conf->dir. "/shells contains: @shells";
941 $recref->{shell} = '/bin/sync';
945 $recref->{gid} ne '' ?
946 return "Can't have gid without uid" : ( $recref->{gid}='' );
947 #$recref->{dir} ne '' ?
948 # return "Can't have directory without uid" : ( $recref->{dir}='' );
949 $recref->{shell} ne '' ?
950 return "Can't have shell without uid" : ( $recref->{shell}='' );
953 unless ( $part_svc->part_svc_column('dir')->columnflag eq 'F' ) {
955 $recref->{dir} =~ /^([\/\w\-\.\&]*)$/
956 or return "Illegal directory: ". $recref->{dir};
958 return "Illegal directory"
959 if $recref->{dir} =~ /(^|\/)\.+(\/|$)/; #no .. component
960 return "Illegal directory"
961 if $recref->{dir} =~ /\&/ && ! $username_ampersand;
962 unless ( $recref->{dir} ) {
963 $recref->{dir} = $dir_prefix . '/';
964 if ( $dirhash > 0 ) {
965 for my $h ( 1 .. $dirhash ) {
966 $recref->{dir} .= substr($recref->{username}, $h-1, 1). '/';
968 } elsif ( $dirhash < 0 ) {
969 for my $h ( reverse $dirhash .. -1 ) {
970 $recref->{dir} .= substr($recref->{username}, $h, 1). '/';
973 $recref->{dir} .= $recref->{username};
979 # $error = $self->ut_textn('finger');
980 # return $error if $error;
981 if ( $self->getfield('finger') eq '' ) {
982 my $cust_pkg = $self->svcnum
983 ? $self->cust_svc->cust_pkg
984 : qsearchs('cust_pkg', { 'pkgnum' => $self->getfield('pkgnum') } );
986 my $cust_main = $cust_pkg->cust_main;
987 $self->setfield('finger', $cust_main->first.' '.$cust_main->get('last') );
990 $self->getfield('finger') =~
991 /^([\w \t\!\@\#\$\%\&\(\)\-\+\;\'\"\,\.\?\/\*\<\>]*)$/
992 or return "Illegal finger: ". $self->getfield('finger');
993 $self->setfield('finger', $1);
995 $recref->{quota} =~ /^(\w*)$/ or return "Illegal quota";
996 $recref->{quota} = $1;
998 unless ( $part_svc->part_svc_column('slipip')->columnflag eq 'F' ) {
999 if ( $recref->{slipip} eq '' ) {
1000 $recref->{slipip} = '';
1001 } elsif ( $recref->{slipip} eq '0e0' ) {
1002 $recref->{slipip} = '0e0';
1004 $recref->{slipip} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/
1005 or return "Illegal slipip: ". $self->slipip;
1006 $recref->{slipip} = $1;
1011 #arbitrary RADIUS stuff; allow ut_textn for now
1012 foreach ( grep /^radius_/, fields('svc_acct') ) {
1013 $self->ut_textn($_);
1016 #generate a password if it is blank
1017 $recref->{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) )
1018 unless ( $recref->{_password} );
1020 #if ( $recref->{_password} =~ /^((\*SUSPENDED\* )?)([^\t\n]{4,16})$/ ) {
1021 if ( $recref->{_password} =~ /^((\*SUSPENDED\* |!!?)?)([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1022 $recref->{_password} = $1.$3;
1023 #uncomment this to encrypt password immediately upon entry, or run
1024 #bin/crypt_pw in cron to give new users a window during which their
1025 #password is available to techs, for faxing, etc. (also be aware of
1027 #$recref->{password} = $1.
1028 # crypt($3,$saltset[int(rand(64))].$saltset[int(rand(64))]
1030 } elsif ( $recref->{_password} =~ /^((\*SUSPENDED\* |!!?)?)([\w\.\/\$\;\+]{13,64})$/ ) {
1031 $recref->{_password} = $1.$3;
1032 } elsif ( $recref->{_password} eq '*' ) {
1033 $recref->{_password} = '*';
1034 } elsif ( $recref->{_password} eq '!' ) {
1035 $recref->{_password} = '!';
1036 } elsif ( $recref->{_password} eq '!!' ) {
1037 $recref->{_password} = '!!';
1039 #return "Illegal password";
1040 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1041 FS::Msgcat::_gettext('illegal_password_characters').
1042 ": ". $recref->{_password};
1045 $self->SUPER::check;
1050 Internal function to check the username against the list of system usernames
1051 from the I<system_usernames> configuration value. Returns true if the username
1052 is listed on the system username list.
1058 scalar( grep { $self->username eq $_ || $self->email eq $_ }
1059 $conf->config('system_usernames')
1063 =item _check_duplicate
1065 Internal function to check for duplicates usernames, username@domain pairs and
1068 If the I<global_unique-username> configuration value is set to B<username> or
1069 B<username@domain>, enforces global username or username@domain uniqueness.
1071 In all cases, check for duplicate uids and usernames or username@domain pairs
1072 per export and with identical I<svcpart> values.
1076 sub _check_duplicate {
1079 my $global_unique = $conf->config('global_unique-username') || 'none';
1080 return '' if $global_unique eq 'disabled';
1082 #this is Pg-specific. what to do for mysql etc?
1083 # ( mysql LOCK TABLES certainly isn't equivalent or useful here :/ )
1084 warn "$me locking svc_acct table for duplicate search" if $DEBUG;
1085 dbh->do("LOCK TABLE svc_acct IN SHARE ROW EXCLUSIVE MODE")
1087 warn "$me acquired svc_acct table lock for duplicate search" if $DEBUG;
1089 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
1090 unless ( $part_svc ) {
1091 return 'unknown svcpart '. $self->svcpart;
1094 my @dup_user = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1095 qsearch( 'svc_acct', { 'username' => $self->username } );
1096 return gettext('username_in_use')
1097 if $global_unique eq 'username' && @dup_user;
1099 my @dup_userdomain = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1100 qsearch( 'svc_acct', { 'username' => $self->username,
1101 'domsvc' => $self->domsvc } );
1102 return gettext('username_in_use')
1103 if $global_unique eq 'username@domain' && @dup_userdomain;
1106 if ( $part_svc->part_svc_column('uid')->columnflag ne 'F'
1107 && $self->username !~ /^(toor|(hyla)?fax)$/ ) {
1108 @dup_uid = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1109 qsearch( 'svc_acct', { 'uid' => $self->uid } );
1114 if ( @dup_user || @dup_userdomain || @dup_uid ) {
1115 my $exports = FS::part_export::export_info('svc_acct');
1116 my %conflict_user_svcpart;
1117 my %conflict_userdomain_svcpart = ( $self->svcpart => 'SELF', );
1119 foreach my $part_export ( $part_svc->part_export ) {
1121 #this will catch to the same exact export
1122 my @svcparts = map { $_->svcpart } $part_export->export_svc;
1124 #this will catch to exports w/same exporthost+type ???
1125 #my @other_part_export = qsearch('part_export', {
1126 # 'machine' => $part_export->machine,
1127 # 'exporttype' => $part_export->exporttype,
1129 #foreach my $other_part_export ( @other_part_export ) {
1130 # push @svcparts, map { $_->svcpart }
1131 # qsearch('export_svc', { 'exportnum' => $part_export->exportnum });
1134 #my $nodomain = $exports->{$part_export->exporttype}{'nodomain'};
1135 #silly kludge to avoid uninitialized value errors
1136 my $nodomain = exists( $exports->{$part_export->exporttype}{'nodomain'} )
1137 ? $exports->{$part_export->exporttype}{'nodomain'}
1139 if ( $nodomain =~ /^Y/i ) {
1140 $conflict_user_svcpart{$_} = $part_export->exportnum
1143 $conflict_userdomain_svcpart{$_} = $part_export->exportnum
1148 foreach my $dup_user ( @dup_user ) {
1149 my $dup_svcpart = $dup_user->cust_svc->svcpart;
1150 if ( exists($conflict_user_svcpart{$dup_svcpart}) ) {
1151 return "duplicate username: conflicts with svcnum ". $dup_user->svcnum.
1152 " via exportnum ". $conflict_user_svcpart{$dup_svcpart};
1156 foreach my $dup_userdomain ( @dup_userdomain ) {
1157 my $dup_svcpart = $dup_userdomain->cust_svc->svcpart;
1158 if ( exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1159 return "duplicate username\@domain: conflicts with svcnum ".
1160 $dup_userdomain->svcnum. " via exportnum ".
1161 $conflict_userdomain_svcpart{$dup_svcpart};
1165 foreach my $dup_uid ( @dup_uid ) {
1166 my $dup_svcpart = $dup_uid->cust_svc->svcpart;
1167 if ( exists($conflict_user_svcpart{$dup_svcpart})
1168 || exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1169 return "duplicate uid: conflicts with svcnum ". $dup_uid->svcnum.
1170 " via exportnum ". $conflict_user_svcpart{$dup_svcpart}
1171 || $conflict_userdomain_svcpart{$dup_svcpart};
1183 Depriciated, use radius_reply instead.
1188 carp "FS::svc_acct::radius depriciated, use radius_reply";
1189 $_[0]->radius_reply;
1194 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1195 reply attributes of this record.
1197 Note that this is now the preferred method for reading RADIUS attributes -
1198 accessing the columns directly is discouraged, as the column names are
1199 expected to change in the future.
1206 return %{ $self->{'radius_reply'} }
1207 if exists $self->{'radius_reply'};
1212 my($column, $attrib) = ($1, $2);
1213 #$attrib =~ s/_/\-/g;
1214 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1215 } grep { /^radius_/ && $self->getfield($_) } fields( $self->table );
1217 if ( $self->slipip && $self->slipip ne '0e0' ) {
1218 $reply{$radius_ip} = $self->slipip;
1221 if ( $self->seconds !~ /^$/ ) {
1222 $reply{'Session-Timeout'} = $self->seconds;
1230 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1231 check attributes of this record.
1233 Note that this is now the preferred method for reading RADIUS attributes -
1234 accessing the columns directly is discouraged, as the column names are
1235 expected to change in the future.
1242 return %{ $self->{'radius_check'} }
1243 if exists $self->{'radius_check'};
1248 my($column, $attrib) = ($1, $2);
1249 #$attrib =~ s/_/\-/g;
1250 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1251 } grep { /^rc_/ && $self->getfield($_) } fields( $self->table );
1253 my $password = $self->_password;
1254 my $pw_attrib = length($password) <= 12 ? $radius_password : 'Crypt-Password'; $check{$pw_attrib} = $password;
1256 my $cust_svc = $self->cust_svc;
1257 die "FATAL: no cust_svc record for svc_acct.svcnum ". $self->svcnum. "\n"
1259 my $cust_pkg = $cust_svc->cust_pkg;
1260 if ( $cust_pkg && $cust_pkg->part_pkg->is_prepaid && $cust_pkg->bill ) {
1261 $check{'Expiration'} = time2str('%B %e %Y %T', $cust_pkg->bill ); #http://lists.cistron.nl/pipermail/freeradius-users/2005-January/040184.html
1270 This method instructs the object to "snapshot" or freeze RADIUS check and
1271 reply attributes to the current values.
1275 #bah, my english is too broken this morning
1276 #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
1277 #the FS::cust_pkg's replace method to trigger the correct export updates when
1278 #package dates change)
1283 $self->{$_} = { $self->$_() }
1284 foreach qw( radius_reply radius_check );
1288 =item forget_snapshot
1290 This methos instructs the object to forget any previously snapshotted
1291 RADIUS check and reply attributes.
1295 sub forget_snapshot {
1299 foreach qw( radius_reply radius_check );
1303 =item domain [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1305 Returns the domain associated with this account.
1307 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1314 die "svc_acct.domsvc is null for svcnum ". $self->svcnum unless $self->domsvc;
1315 my $svc_domain = $self->svc_domain(@_)
1316 or die "no svc_domain.svcnum for svc_acct.domsvc ". $self->domsvc;
1317 $svc_domain->domain;
1322 Returns the FS::svc_domain record for this account's domain (see
1327 # FS::h_svc_acct has a history-aware svc_domain override
1332 ? $self->{'_domsvc'}
1333 : qsearchs( 'svc_domain', { 'svcnum' => $self->domsvc } );
1338 Returns the FS::cust_svc record for this account (see L<FS::cust_svc>).
1342 #inherited from svc_Common
1344 =item email [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1346 Returns an email address associated with the account.
1348 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1355 $self->username. '@'. $self->domain(@_);
1360 Returns an array of FS::acct_snarf records associated with the account.
1361 If the acct_snarf table does not exist or there are no associated records,
1362 an empty list is returned
1368 return () unless dbdef->table('acct_snarf');
1369 eval "use FS::acct_snarf;";
1371 qsearch('acct_snarf', { 'svcnum' => $self->svcnum } );
1374 =item decrement_upbytes OCTETS
1376 Decrements the I<upbytes> field of this record by the given amount. If there
1377 is an error, returns the error, otherwise returns false.
1381 sub decrement_upbytes {
1382 shift->_op_usage('-', 'upbytes', @_);
1385 =item increment_upbytes OCTETS
1387 Increments the I<upbytes> field of this record by the given amount. If there
1388 is an error, returns the error, otherwise returns false.
1392 sub increment_upbytes {
1393 shift->_op_usage('+', 'upbytes', @_);
1396 =item decrement_downbytes OCTETS
1398 Decrements the I<downbytes> field of this record by the given amount. If there
1399 is an error, returns the error, otherwise returns false.
1403 sub decrement_downbytes {
1404 shift->_op_usage('-', 'downbytes', @_);
1407 =item increment_downbytes OCTETS
1409 Increments the I<downbytes> field of this record by the given amount. If there
1410 is an error, returns the error, otherwise returns false.
1414 sub increment_downbytes {
1415 shift->_op_usage('+', 'downbytes', @_);
1418 =item decrement_totalbytes OCTETS
1420 Decrements the I<totalbytes> field of this record by the given amount. If there
1421 is an error, returns the error, otherwise returns false.
1425 sub decrement_totalbytes {
1426 shift->_op_usage('-', 'totalbytes', @_);
1429 =item increment_totalbytes OCTETS
1431 Increments the I<totalbytes> field of this record by the given amount. If there
1432 is an error, returns the error, otherwise returns false.
1436 sub increment_totalbytes {
1437 shift->_op_usage('+', 'totalbytes', @_);
1440 =item decrement_seconds SECONDS
1442 Decrements the I<seconds> field of this record by the given amount. If there
1443 is an error, returns the error, otherwise returns false.
1447 sub decrement_seconds {
1448 shift->_op_usage('-', 'seconds', @_);
1451 =item increment_seconds SECONDS
1453 Increments the I<seconds> field of this record by the given amount. If there
1454 is an error, returns the error, otherwise returns false.
1458 sub increment_seconds {
1459 shift->_op_usage('+', 'seconds', @_);
1467 my %op2condition = (
1468 '-' => sub { my($self, $column, $amount) = @_;
1469 $self->$column - $amount <= 0;
1471 '+' => sub { my($self, $column, $amount) = @_;
1472 $self->$column + $amount > 0;
1475 my %op2warncondition = (
1476 '-' => sub { my($self, $column, $amount) = @_;
1477 my $threshold = $column . '_threshold';
1478 $self->$column - $amount <= $self->$threshold + 0;
1480 '+' => sub { my($self, $column, $amount) = @_;
1481 $self->$column + $amount > 0;
1486 my( $self, $op, $column, $amount ) = @_;
1488 warn "$me _op_usage called for $column on svcnum ". $self->svcnum.
1489 ' ('. $self->email. "): $op $amount\n"
1492 return '' unless $amount;
1494 local $SIG{HUP} = 'IGNORE';
1495 local $SIG{INT} = 'IGNORE';
1496 local $SIG{QUIT} = 'IGNORE';
1497 local $SIG{TERM} = 'IGNORE';
1498 local $SIG{TSTP} = 'IGNORE';
1499 local $SIG{PIPE} = 'IGNORE';
1501 my $oldAutoCommit = $FS::UID::AutoCommit;
1502 local $FS::UID::AutoCommit = 0;
1505 my $sql = "UPDATE svc_acct SET $column = ".
1506 " CASE WHEN $column IS NULL THEN 0 ELSE $column END ". #$column||0
1507 " $op ? WHERE svcnum = ?";
1511 my $sth = $dbh->prepare( $sql )
1512 or die "Error preparing $sql: ". $dbh->errstr;
1513 my $rv = $sth->execute($amount, $self->svcnum);
1514 die "Error executing $sql: ". $sth->errstr
1515 unless defined($rv);
1516 die "Can't update $column for svcnum". $self->svcnum
1519 my $action = $op2action{$op};
1521 if ( $conf->exists("svc_acct-usage_$action")
1522 && &{$op2condition{$op}}($self, $column, $amount) ) {
1523 #my $error = $self->$action();
1524 my $error = $self->cust_svc->cust_pkg->$action();
1526 $dbh->rollback if $oldAutoCommit;
1527 return "Error ${action}ing: $error";
1531 if ($warning_template && &{$op2warncondition{$op}}($self, $column, $amount)) {
1532 my $wqueue = new FS::queue {
1533 'svcnum' => $self->svcnum,
1534 'job' => 'FS::svc_acct::reached_threshold',
1539 $to = $warning_cc if &{$op2condition{$op}}($self, $column, $amount);
1543 my $error = $wqueue->insert(
1544 'svcnum' => $self->svcnum,
1546 'column' => $column,
1550 $dbh->rollback if $oldAutoCommit;
1551 return "Error queuing threshold activity: $error";
1555 warn "$me update successful; committing\n"
1557 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1563 my( $self, $valueref ) = @_;
1565 warn "$me set_usage called for svcnum ". $self->svcnum.
1566 ' ('. $self->email. "): ".
1567 join(', ', map { "$_ => " . $valueref->{$_}} keys %$valueref) . "\n"
1570 local $SIG{HUP} = 'IGNORE';
1571 local $SIG{INT} = 'IGNORE';
1572 local $SIG{QUIT} = 'IGNORE';
1573 local $SIG{TERM} = 'IGNORE';
1574 local $SIG{TSTP} = 'IGNORE';
1575 local $SIG{PIPE} = 'IGNORE';
1577 local $FS::svc_Common::noexport_hack = 1;
1578 my $oldAutoCommit = $FS::UID::AutoCommit;
1579 local $FS::UID::AutoCommit = 0;
1583 foreach my $field (keys %$valueref){
1584 $reset = 1 if $valueref->{$field};
1585 $self->setfield($field, $valueref->{$field});
1586 $self->setfield( $field.'_threshold',
1587 int($self->getfield($field)
1588 * ( $conf->exists('svc_acct-usage_threshold')
1589 ? 1 - $conf->config('svc_acct-usage_threshold')/100
1595 my $error = $self->replace;
1596 die $error if $error;
1598 if ( $conf->exists("svc_acct-usage_unsuspend") && $reset ) {
1599 my $error = $self->cust_svc->cust_pkg->unsuspend;
1601 $dbh->rollback if $oldAutoCommit;
1602 return "Error unsuspending: $error";
1606 warn "$me update successful; committing\n"
1608 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1614 =item recharge HASHREF
1616 Increments usage columns by the amount specified in HASHREF as
1617 column=>amount pairs.
1622 my ($self, $vhash) = @_;
1625 warn "[$me] recharge called on $self: ". Dumper($self).
1626 "\nwith vhash: ". Dumper($vhash);
1629 my $oldAutoCommit = $FS::UID::AutoCommit;
1630 local $FS::UID::AutoCommit = 0;
1634 foreach my $column (keys %$vhash){
1635 $error ||= $self->_op_usage('+', $column, $vhash->{$column});
1639 $dbh->rollback if $oldAutoCommit;
1641 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1646 =item is_rechargeable
1648 Returns true if this svc_account can be "recharged" and false otherwise.
1652 sub is_rechargable {
1654 $self->seconds ne ''
1655 || $self->upbytes ne ''
1656 || $self->downbytes ne ''
1657 || $self->totalbytes ne '';
1660 =item seconds_since TIMESTAMP
1662 Returns the number of seconds this account has been online since TIMESTAMP,
1663 according to the session monitor (see L<FS::Session>).
1665 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
1666 L<Time::Local> and L<Date::Parse> for conversion functions.
1670 #note: POD here, implementation in FS::cust_svc
1673 $self->cust_svc->seconds_since(@_);
1676 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
1678 Returns the numbers of seconds this account has been online between
1679 TIMESTAMP_START (inclusive) and TIMESTAMP_END (exclusive), according to an
1680 external SQL radacct table, specified via sqlradius export. Sessions which
1681 started in the specified range but are still open are counted from session
1682 start to the end of the range (unless they are over 1 day old, in which case
1683 they are presumed missing their stop record and not counted). Also, sessions
1684 which end in the range but started earlier are counted from the start of the
1685 range to session end. Finally, sessions which start before the range but end
1686 after are counted for the entire range.
1688 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1689 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1694 #note: POD here, implementation in FS::cust_svc
1695 sub seconds_since_sqlradacct {
1697 $self->cust_svc->seconds_since_sqlradacct(@_);
1700 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
1702 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
1703 in this package for sessions ending between TIMESTAMP_START (inclusive) and
1704 TIMESTAMP_END (exclusive).
1706 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
1707 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
1712 #note: POD here, implementation in FS::cust_svc
1713 sub attribute_since_sqlradacct {
1715 $self->cust_svc->attribute_since_sqlradacct(@_);
1718 =item get_session_history TIMESTAMP_START TIMESTAMP_END
1720 Returns an array of hash references of this customers login history for the
1721 given time range. (document this better)
1725 sub get_session_history {
1727 $self->cust_svc->get_session_history(@_);
1730 =item get_cdrs TIMESTAMP_START TIMESTAMP_END [ 'OPTION' => 'VALUE ... ]
1735 my($self, $start, $end, %opt ) = @_;
1737 my $did = $self->username; #yup
1739 my $prefix = $opt{'default_prefix'}; #convergent.au '+61'
1741 my $for_update = $opt{'for_update'} ? 'FOR UPDATE' : '';
1743 #SELECT $for_update * FROM cdr
1744 # WHERE calldate >= $start #need a conversion
1745 # AND calldate < $end #ditto
1746 # AND ( charged_party = "$did"
1747 # OR charged_party = "$prefix$did" #if length($prefix);
1748 # OR ( ( charged_party IS NULL OR charged_party = '' )
1750 # ( src = "$did" OR src = "$prefix$did" ) # if length($prefix)
1753 # AND ( freesidestatus IS NULL OR freesidestatus = '' )
1756 if ( length($prefix) ) {
1758 " AND ( charged_party = '$did'
1759 OR charged_party = '$prefix$did'
1760 OR ( ( charged_party IS NULL OR charged_party = '' )
1762 ( src = '$did' OR src = '$prefix$did' )
1768 " AND ( charged_party = '$did'
1769 OR ( ( charged_party IS NULL OR charged_party = '' )
1779 'select' => "$for_update *",
1782 #( freesidestatus IS NULL OR freesidestatus = '' )
1783 'freesidestatus' => '',
1785 'extra_sql' => $charged_or_src,
1793 Returns all RADIUS groups for this account (see L<FS::radius_usergroup>).
1799 if ( $self->usergroup ) {
1800 confess "explicitly specified usergroup not an arrayref: ". $self->usergroup
1801 unless ref($self->usergroup) eq 'ARRAY';
1802 #when provisioning records, export callback runs in svc_Common.pm before
1803 #radius_usergroup records can be inserted...
1804 @{$self->usergroup};
1806 map { $_->groupname }
1807 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } );
1811 =item clone_suspended
1813 Constructor used by FS::part_export::_export_suspend fallback. Document
1818 sub clone_suspended {
1820 my %hash = $self->hash;
1821 $hash{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1822 new FS::svc_acct \%hash;
1825 =item clone_kludge_unsuspend
1827 Constructor used by FS::part_export::_export_unsuspend fallback. Document
1832 sub clone_kludge_unsuspend {
1834 my %hash = $self->hash;
1835 $hash{_password} = '';
1836 new FS::svc_acct \%hash;
1839 =item check_password
1841 Checks the supplied password against the (possibly encrypted) password in the
1842 database. Returns true for a successful authentication, false for no match.
1844 Currently supported encryptions are: classic DES crypt() and MD5
1848 sub check_password {
1849 my($self, $check_password) = @_;
1851 #remove old-style SUSPENDED kludge, they should be allowed to login to
1852 #self-service and pay up
1853 ( my $password = $self->_password ) =~ s/^\*SUSPENDED\* //;
1855 #eventually should check a "password-encoding" field
1856 if ( $password =~ /^(\*|!!?)$/ ) { #no self-service login
1858 } elsif ( length($password) < 13 ) { #plaintext
1859 $check_password eq $password;
1860 } elsif ( length($password) == 13 ) { #traditional DES crypt
1861 crypt($check_password, $password) eq $password;
1862 } elsif ( $password =~ /^\$1\$/ ) { #MD5 crypt
1863 unix_md5_crypt($check_password, $password) eq $password;
1864 } elsif ( $password =~ /^\$2a?\$/ ) { #Blowfish
1865 warn "Can't check password: Blowfish encryption not yet supported, svcnum".
1866 $self->svcnum. "\n";
1869 warn "Can't check password: Unrecognized encryption for svcnum ".
1870 $self->svcnum. "\n";
1876 =item crypt_password [ DEFAULT_ENCRYPTION_TYPE ]
1878 Returns an encrypted password, either by passing through an encrypted password
1879 in the database or by encrypting a plaintext password from the database.
1881 The optional DEFAULT_ENCRYPTION_TYPE parameter can be set to I<crypt> (classic
1882 UNIX DES crypt), I<md5> (md5 crypt supported by most modern Linux and BSD
1883 distrubtions), or (eventually) I<blowfish> (blowfish hashing supported by
1884 OpenBSD, SuSE, other Linux distibutions with pam_unix2, etc.). The default
1885 encryption type is only used if the password is not already encrypted in the
1890 sub crypt_password {
1892 #eventually should check a "password-encoding" field
1893 if ( length($self->_password) == 13
1894 || $self->_password =~ /^\$(1|2a?)\$/
1895 || $self->_password =~ /^(\*|NP|\*LK\*|!!?)$/
1900 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
1901 if ( $encryption eq 'crypt' ) {
1904 $saltset[int(rand(64))].$saltset[int(rand(64))]
1906 } elsif ( $encryption eq 'md5' ) {
1907 unix_md5_crypt( $self->_password );
1908 } elsif ( $encryption eq 'blowfish' ) {
1909 croak "unknown encryption method $encryption";
1911 croak "unknown encryption method $encryption";
1916 =item ldap_password [ DEFAULT_ENCRYPTION_TYPE ]
1918 Returns an encrypted password in "LDAP" format, with a curly-bracked prefix
1919 describing the format, for example, "{CRYPT}94pAVyK/4oIBk" or
1920 "{PLAIN-MD5}5426824942db4253f87a1009fd5d2d4f".
1922 The optional DEFAULT_ENCRYPTION_TYPE is not yet used, but the idea is for it
1923 to work the same as the B</crypt_password> method.
1929 #eventually should check a "password-encoding" field
1930 if ( length($self->_password) == 13 ) { #crypt
1931 return '{CRYPT}'. $self->_password;
1932 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
1934 } elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
1935 die "Blowfish encryption not supported in this context, svcnum ".
1936 $self->svcnum. "\n";
1937 } elsif ( $self->_password =~ /^(\w{48})$/ ) { #LDAP SSHA
1938 return '{SSHA}'. $1;
1939 } elsif ( $self->_password =~ /^(\w{64})$/ ) { #LDAP NS-MTA-MD5
1940 return '{NS-MTA-MD5}'. $1;
1942 return '{PLAIN}'. $self->_password;
1943 #my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
1944 #if ( $encryption eq 'crypt' ) {
1945 # return '{CRYPT}'. crypt(
1947 # $saltset[int(rand(64))].$saltset[int(rand(64))]
1949 #} elsif ( $encryption eq 'md5' ) {
1950 # unix_md5_crypt( $self->_password );
1951 #} elsif ( $encryption eq 'blowfish' ) {
1952 # croak "unknown encryption method $encryption";
1954 # croak "unknown encryption method $encryption";
1959 =item domain_slash_username
1961 Returns $domain/$username/
1965 sub domain_slash_username {
1967 $self->domain. '/'. $self->username. '/';
1970 =item virtual_maildir
1972 Returns $domain/maildirs/$username/
1976 sub virtual_maildir {
1978 $self->domain. '/maildirs/'. $self->username. '/';
1989 This is the FS::svc_acct job-queue-able version. It still uses
1990 FS::Misc::send_email under-the-hood.
1997 eval "use FS::Misc qw(send_email)";
2000 $opt{mimetype} ||= 'text/plain';
2001 $opt{mimetype} .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2003 my $error = send_email(
2004 'from' => $opt{from},
2006 'subject' => $opt{subject},
2007 'content-type' => $opt{mimetype},
2008 'body' => [ map "$_\n", split("\n", $opt{body}) ],
2010 die $error if $error;
2013 =item check_and_rebuild_fuzzyfiles
2017 sub check_and_rebuild_fuzzyfiles {
2018 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2019 -e "$dir/svc_acct.username"
2020 or &rebuild_fuzzyfiles;
2023 =item rebuild_fuzzyfiles
2027 sub rebuild_fuzzyfiles {
2029 use Fcntl qw(:flock);
2031 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2035 open(USERNAMELOCK,">>$dir/svc_acct.username")
2036 or die "can't open $dir/svc_acct.username: $!";
2037 flock(USERNAMELOCK,LOCK_EX)
2038 or die "can't lock $dir/svc_acct.username: $!";
2040 my @all_username = map $_->getfield('username'), qsearch('svc_acct', {});
2042 open (USERNAMECACHE,">$dir/svc_acct.username.tmp")
2043 or die "can't open $dir/svc_acct.username.tmp: $!";
2044 print USERNAMECACHE join("\n", @all_username), "\n";
2045 close USERNAMECACHE or die "can't close $dir/svc_acct.username.tmp: $!";
2047 rename "$dir/svc_acct.username.tmp", "$dir/svc_acct.username";
2057 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2058 open(USERNAMECACHE,"<$dir/svc_acct.username")
2059 or die "can't open $dir/svc_acct.username: $!";
2060 my @array = map { chomp; $_; } <USERNAMECACHE>;
2061 close USERNAMECACHE;
2065 =item append_fuzzyfiles USERNAME
2069 sub append_fuzzyfiles {
2070 my $username = shift;
2072 &check_and_rebuild_fuzzyfiles;
2074 use Fcntl qw(:flock);
2076 my $dir = $FS::UID::conf_dir. "cache.". $FS::UID::datasrc;
2078 open(USERNAME,">>$dir/svc_acct.username")
2079 or die "can't open $dir/svc_acct.username: $!";
2080 flock(USERNAME,LOCK_EX)
2081 or die "can't lock $dir/svc_acct.username: $!";
2083 print USERNAME "$username\n";
2085 flock(USERNAME,LOCK_UN)
2086 or die "can't unlock $dir/svc_acct.username: $!";
2094 =item radius_usergroup_selector GROUPS_ARRAYREF [ SELECTNAME ]
2098 sub radius_usergroup_selector {
2099 my $sel_groups = shift;
2100 my %sel_groups = map { $_=>1 } @$sel_groups;
2102 my $selectname = shift || 'radius_usergroup';
2105 my $sth = $dbh->prepare(
2106 'SELECT DISTINCT(groupname) FROM radius_usergroup ORDER BY groupname'
2107 ) or die $dbh->errstr;
2108 $sth->execute() or die $sth->errstr;
2109 my @all_groups = map { $_->[0] } @{$sth->fetchall_arrayref};
2113 function ${selectname}_doadd(object) {
2114 var myvalue = object.${selectname}_add.value;
2115 var optionName = new Option(myvalue,myvalue,false,true);
2116 var length = object.$selectname.length;
2117 object.$selectname.options[length] = optionName;
2118 object.${selectname}_add.value = "";
2121 <SELECT MULTIPLE NAME="$selectname">
2124 foreach my $group ( @all_groups ) {
2125 $html .= qq(<OPTION VALUE="$group");
2126 if ( $sel_groups{$group} ) {
2127 $html .= ' SELECTED';
2128 $sel_groups{$group} = 0;
2130 $html .= ">$group</OPTION>\n";
2132 foreach my $group ( grep { $sel_groups{$_} } keys %sel_groups ) {
2133 $html .= qq(<OPTION VALUE="$group" SELECTED>$group</OPTION>\n);
2135 $html .= '</SELECT>';
2137 $html .= qq!<BR><INPUT TYPE="text" NAME="${selectname}_add">!.
2138 qq!<INPUT TYPE="button" VALUE="Add new group" onClick="${selectname}_doadd(this.form)">!;
2143 =item reached_threshold
2145 Performs some activities when svc_acct thresholds (such as number of seconds
2146 remaining) are reached.
2150 sub reached_threshold {
2153 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } );
2154 die "Cannot find svc_acct with svcnum " . $opt{'svcnum'} unless $svc_acct;
2156 if ( $opt{'op'} eq '+' ){
2157 $svc_acct->setfield( $opt{'column'}.'_threshold',
2158 int($svc_acct->getfield($opt{'column'})
2159 * ( $conf->exists('svc_acct-usage_threshold')
2160 ? $conf->config('svc_acct-usage_threshold')/100
2165 my $error = $svc_acct->replace;
2166 die $error if $error;
2167 }elsif ( $opt{'op'} eq '-' ){
2169 my $threshold = $svc_acct->getfield( $opt{'column'}.'_threshold' );
2170 return '' if ($threshold eq '' );
2172 $svc_acct->setfield( $opt{'column'}.'_threshold', 0 );
2173 my $error = $svc_acct->replace;
2174 die $error if $error; # email next time, i guess
2176 if ( $warning_template ) {
2177 eval "use FS::Misc qw(send_email)";
2180 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2181 my $cust_main = $cust_pkg->cust_main;
2183 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ }
2184 $cust_main->invoicing_list,
2186 ($opt{'to'} ? $opt{'to'} : ())
2189 my $mimetype = $warning_mimetype;
2190 $mimetype .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2192 my $body = $warning_template->fill_in( HASH => {
2193 'custnum' => $cust_main->custnum,
2194 'username' => $svc_acct->username,
2195 'password' => $svc_acct->_password,
2196 'first' => $cust_main->first,
2197 'last' => $cust_main->getfield('last'),
2198 'pkg' => $cust_pkg->part_pkg->pkg,
2199 'column' => $opt{'column'},
2200 'amount' => $svc_acct->getfield($opt{'column'}),
2201 'threshold' => $threshold,
2205 my $error = send_email(
2206 'from' => $warning_from,
2208 'subject' => $warning_subject,
2209 'content-type' => $mimetype,
2210 'body' => [ map "$_\n", split("\n", $body) ],
2212 die $error if $error;
2215 die "unknown op: " . $opt{'op'};
2223 The $recref stuff in sub check should be cleaned up.
2225 The suspend, unsuspend and cancel methods update the database, but not the
2226 current object. This is probably a bug as it's unexpected and
2229 radius_usergroup_selector? putting web ui components in here? they should
2230 probably live somewhere else...
2232 insertion of RADIUS group stuff in insert could be done with child_objects now
2233 (would probably clean up export of them too)
2237 L<FS::svc_Common>, edit/part_svc.cgi from an installed web interface,
2238 export.html from the base documentation, L<FS::Record>, L<FS::Conf>,
2239 L<FS::cust_svc>, L<FS::part_svc>, L<FS::cust_pkg>, L<FS::queue>,
2240 L<freeside-queued>), L<FS::svc_acct_pop>,
2241 schema.html from the base documentation.