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 $username_colon
10 $password_noampersand $password_noexclamation
11 $warning_template $warning_from $warning_subject $warning_mimetype
14 $radius_password $radius_ip
17 use Scalar::Util qw( blessed );
22 use Crypt::PasswdMD5 1.2;
23 use Digest::SHA1 'sha1_base64';
24 use Digest::MD5 'md5_base64';
27 use Authen::Passphrase;
28 use FS::UID qw( datasrc driver_name );
30 use FS::Record qw( qsearch qsearchs fields dbh dbdef );
31 use FS::Msgcat qw(gettext);
32 use FS::UI::bytecount;
39 use FS::cust_main_invoice;
44 use FS::radius_usergroup;
51 @ISA = qw( FS::svc_Common );
54 $me = '[FS::svc_acct]';
56 #ask FS::UID to run this stuff for us later
57 FS::UID->install_callback( sub {
59 $dir_prefix = $conf->config('home');
60 @shells = $conf->config('shells');
61 $usernamemin = $conf->config('usernamemin') || 2;
62 $usernamemax = $conf->config('usernamemax');
63 $passwordmin = $conf->config('passwordmin'); # || 6;
65 $passwordmin = ( defined($passwordmin) && $passwordmin =~ /\d+/ )
68 $passwordmax = $conf->config('passwordmax') || 8;
69 $username_letter = $conf->exists('username-letter');
70 $username_letterfirst = $conf->exists('username-letterfirst');
71 $username_noperiod = $conf->exists('username-noperiod');
72 $username_nounderscore = $conf->exists('username-nounderscore');
73 $username_nodash = $conf->exists('username-nodash');
74 $username_uppercase = $conf->exists('username-uppercase');
75 $username_ampersand = $conf->exists('username-ampersand');
76 $username_percent = $conf->exists('username-percent');
77 $username_colon = $conf->exists('username-colon');
78 $password_noampersand = $conf->exists('password-noexclamation');
79 $password_noexclamation = $conf->exists('password-noexclamation');
80 $dirhash = $conf->config('dirhash') || 0;
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';
100 @pw_set = ( 'A'..'Z' ) if $conf->exists('password-generated-allcaps');
104 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '.' , '/' );
105 @pw_set = ( 'a'..'z', 'A'..'Z', '0'..'9', '(', ')', '#', '!', '.', ',' );
109 my ( $hashref, $cache ) = @_;
110 if ( $hashref->{'svc_acct_svcnum'} ) {
111 $self->{'_domsvc'} = FS::svc_domain->new( {
112 'svcnum' => $hashref->{'domsvc'},
113 'domain' => $hashref->{'svc_acct_domain'},
114 'catchall' => $hashref->{'svc_acct_catchall'},
121 FS::svc_acct - Object methods for svc_acct records
127 $record = new FS::svc_acct \%hash;
128 $record = new FS::svc_acct { 'column' => 'value' };
130 $error = $record->insert;
132 $error = $new_record->replace($old_record);
134 $error = $record->delete;
136 $error = $record->check;
138 $error = $record->suspend;
140 $error = $record->unsuspend;
142 $error = $record->cancel;
144 %hash = $record->radius;
146 %hash = $record->radius_reply;
148 %hash = $record->radius_check;
150 $domain = $record->domain;
152 $svc_domain = $record->svc_domain;
154 $email = $record->email;
156 $seconds_since = $record->seconds_since($timestamp);
160 An FS::svc_acct object represents an account. FS::svc_acct inherits from
161 FS::svc_Common. The following fields are currently supported:
167 Primary key (assigned automatcially for new accounts)
175 =item _password_encoding
177 plain, crypt, ldap (or empty for autodetection)
185 Point of presence (see L<FS::svc_acct_pop>)
197 set automatically if blank (and uid is not)
217 svcnum from svc_domain
221 Optional svcnum from svc_pbx
223 =item radius_I<Radius_Attribute>
225 I<Radius-Attribute> (reply)
227 =item rc_I<Radius_Attribute>
229 I<Radius-Attribute> (check)
239 Creates a new account. To add the account to the database, see L<"insert">.
246 'longname_plural' => 'Access accounts and mailboxes',
247 'sorts' => [ 'username', 'uid', 'seconds', 'last_login' ],
248 'display_weight' => 10,
249 'cancel_weight' => 50,
251 'dir' => 'Home directory',
254 def_info => 'set to fixed and blank for no UIDs',
257 'slipip' => 'IP address',
258 # 'popnum' => qq!<A HREF="$p/browse/svc_acct_pop.cgi/">POP number</A>!,
260 label => 'Access number',
262 select_table => 'svc_acct_pop',
263 select_key => 'popnum',
264 select_label => 'city',
270 disable_default => 1,
275 label => 'Communigate account type',
278 disable_inventory => 1,
281 'cgp_accessmodes' => {
282 label => 'Communigate enabled services',
283 type => 'communigate_pro-accessmodes',
284 disable_inventory => 1,
288 label => 'Quota', #Mail storage limit
290 disable_inventory => 1,
294 label => 'File storage limit',
296 disable_inventory => 1,
300 label => 'Number of files limit',
302 disable_inventory => 1,
306 label => 'File size limit',
308 disable_inventory => 1,
311 '_password' => 'Password',
314 def_info => 'when blank, defaults to UID',
319 def_info => 'set to blank for no shell tracking',
321 #select_list => [ $conf->config('shells') ],
322 select_list => [ $conf ? $conf->config('shells') : () ],
323 disable_inventory => 1,
326 'finger' => 'Real name', # (GECOS)',
330 select_table => 'svc_domain',
331 select_key => 'svcnum',
332 select_label => 'domain',
333 disable_inventory => 1,
339 select_table => 'svc_domain',
340 select_key => 'svcnum',
341 select_label => 'domain',
342 disable_inventory => 1,
345 'pbxsvc' => { label => 'PBX',
346 type => 'select-svc_pbx.html',
347 disable_inventory => 1,
348 disable_select => 1, #UI wonky, pry works otherwise
351 label => 'RADIUS groups',
352 type => 'radius_usergroup_selector',
353 disable_inventory => 1,
356 'seconds' => { label => 'Seconds',
357 label_sort => 'with Time Remaining',
359 disable_inventory => 1,
361 disable_part_svc_column => 1,
363 'upbytes' => { label => 'Upload',
365 disable_inventory => 1,
367 'format' => \&FS::UI::bytecount::display_bytecount,
368 'parse' => \&FS::UI::bytecount::parse_bytecount,
369 disable_part_svc_column => 1,
371 'downbytes' => { label => 'Download',
373 disable_inventory => 1,
375 'format' => \&FS::UI::bytecount::display_bytecount,
376 'parse' => \&FS::UI::bytecount::parse_bytecount,
377 disable_part_svc_column => 1,
379 'totalbytes'=> { label => 'Total up and download',
381 disable_inventory => 1,
383 'format' => \&FS::UI::bytecount::display_bytecount,
384 'parse' => \&FS::UI::bytecount::parse_bytecount,
385 disable_part_svc_column => 1,
387 'seconds_threshold' => { label => 'Seconds threshold',
389 disable_inventory => 1,
391 disable_part_svc_column => 1,
393 'upbytes_threshold' => { label => 'Upload threshold',
395 disable_inventory => 1,
397 'format' => \&FS::UI::bytecount::display_bytecount,
398 'parse' => \&FS::UI::bytecount::parse_bytecount,
399 disable_part_svc_column => 1,
401 'downbytes_threshold' => { label => 'Download threshold',
403 disable_inventory => 1,
405 'format' => \&FS::UI::bytecount::display_bytecount,
406 'parse' => \&FS::UI::bytecount::parse_bytecount,
407 disable_part_svc_column => 1,
409 'totalbytes_threshold'=> { label => 'Total up and download threshold',
411 disable_inventory => 1,
413 'format' => \&FS::UI::bytecount::display_bytecount,
414 'parse' => \&FS::UI::bytecount::parse_bytecount,
415 disable_part_svc_column => 1,
418 label => 'Last login',
422 label => 'Last logout',
429 sub table { 'svc_acct'; }
431 sub table_dupcheck_fields { ( 'username', 'domsvc' ); }
435 #false laziness with edit/svc_acct.cgi
437 my( $self, $groups ) = @_;
438 if ( ref($groups) eq 'ARRAY' ) {
440 } elsif ( length($groups) ) {
441 [ split(/\s*,\s*/, $groups) ];
450 shift->_lastlog('in', @_);
454 shift->_lastlog('out', @_);
458 my( $self, $op, $time ) = @_;
460 if ( defined($time) ) {
461 warn "$me last_log$op called on svcnum ". $self->svcnum.
462 ' ('. $self->email. "): $time\n"
467 my $sql = "UPDATE svc_acct SET last_log$op = ? WHERE svcnum = ?";
471 my $sth = $dbh->prepare( $sql )
472 or die "Error preparing $sql: ". $dbh->errstr;
473 my $rv = $sth->execute($time, $self->svcnum);
474 die "Error executing $sql: ". $sth->errstr
476 die "Can't update last_log$op for svcnum". $self->svcnum
479 $self->{'Hash'}->{"last_log$op"} = $time;
481 $self->getfield("last_log$op");
485 =item search_sql STRING
487 Class method which returns an SQL fragment to search for the given string.
492 my( $class, $string ) = @_;
493 if ( $string =~ /^([^@]+)@([^@]+)$/ ) {
494 my( $username, $domain ) = ( $1, $2 );
495 my $q_username = dbh->quote($username);
496 my @svc_domain = qsearch('svc_domain', { 'domain' => $domain } );
498 "svc_acct.username = $q_username AND ( ".
499 join( ' OR ', map { "svc_acct.domsvc = ". $_->svcnum; } @svc_domain ).
504 } elsif ( $string =~ /^(\d{1,3}\.){3}\d{1,3}$/ ) {
506 $class->search_sql_field('slipip', $string ).
508 $class->search_sql_field('username', $string ).
511 $class->search_sql_field('username', $string);
515 =item label [ END_TIMESTAMP [ START_TIMESTAMP ] ]
517 Returns the "username@domain" string for this account.
519 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
529 =item label_long [ END_TIMESTAMP [ START_TIMESTAMP ] ]
531 Returns a longer string label for this acccount ("Real Name <username@domain>"
532 if available, or "username@domain").
534 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
541 my $label = $self->label(@_);
542 my $finger = $self->finger;
543 return $label unless $finger =~ /\S/;
544 my $maxlen = 40 - length($label) - length($self->cust_svc->part_svc->svc);
545 $finger = substr($finger, 0, $maxlen-3).'...' if length($finger) > $maxlen;
549 =item insert [ , OPTION => VALUE ... ]
551 Adds this account to the database. If there is an error, returns the error,
552 otherwise returns false.
554 The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be
555 defined. An FS::cust_svc record will be created and inserted.
557 The additional field I<usergroup> can optionally be defined; if so it should
558 contain an arrayref of group names. See L<FS::radius_usergroup>.
560 The additional field I<child_objects> can optionally be defined; if so it
561 should contain an arrayref of FS::tablename objects. They will have their
562 svcnum fields set and will be inserted after this record, but before any
563 exports are run. Each element of the array can also optionally be a
564 two-element array reference containing the child object and the name of an
565 alternate field to be filled in with the newly-inserted svcnum, for example
566 C<[ $svc_forward, 'srcsvc' ]>
568 Currently available options are: I<depend_jobnum>
570 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
571 jobnums), all provisioning jobs will have a dependancy on the supplied
572 jobnum(s) (they will not run until the specific job(s) complete(s)).
574 (TODOC: L<FS::queue> and L<freeside-queued>)
576 (TODOC: new exports!)
585 warn "[$me] insert called on $self: ". Dumper($self).
586 "\nwith options: ". Dumper(%options);
589 local $SIG{HUP} = 'IGNORE';
590 local $SIG{INT} = 'IGNORE';
591 local $SIG{QUIT} = 'IGNORE';
592 local $SIG{TERM} = 'IGNORE';
593 local $SIG{TSTP} = 'IGNORE';
594 local $SIG{PIPE} = 'IGNORE';
596 my $oldAutoCommit = $FS::UID::AutoCommit;
597 local $FS::UID::AutoCommit = 0;
601 my $error = $self->SUPER::insert(
602 'jobnums' => \@jobnums,
603 'child_objects' => $self->child_objects,
607 $dbh->rollback if $oldAutoCommit;
611 if ( $self->usergroup ) {
612 foreach my $groupname ( @{$self->usergroup} ) {
613 my $radius_usergroup = new FS::radius_usergroup ( {
614 svcnum => $self->svcnum,
615 groupname => $groupname,
617 my $error = $radius_usergroup->insert;
619 $dbh->rollback if $oldAutoCommit;
625 unless ( $skip_fuzzyfiles ) {
626 $error = $self->queue_fuzzyfiles_update;
628 $dbh->rollback if $oldAutoCommit;
629 return "updating fuzzy search cache: $error";
633 my $cust_pkg = $self->cust_svc->cust_pkg;
636 my $cust_main = $cust_pkg->cust_main;
637 my $agentnum = $cust_main->agentnum;
639 if ( $conf->exists('emailinvoiceautoalways')
640 || $conf->exists('emailinvoiceauto')
641 && ! $cust_main->invoicing_list_emailonly
643 my @invoicing_list = $cust_main->invoicing_list;
644 push @invoicing_list, $self->email;
645 $cust_main->invoicing_list(\@invoicing_list);
649 my ($to,$welcome_template,$welcome_from,$welcome_subject,$welcome_subject_template,$welcome_mimetype)
650 = ('','','','','','');
652 if ( $conf->exists('welcome_email', $agentnum) ) {
653 $welcome_template = new Text::Template (
655 SOURCE => [ map "$_\n", $conf->config('welcome_email', $agentnum) ]
656 ) or warn "can't create welcome email template: $Text::Template::ERROR";
657 $welcome_from = $conf->config('welcome_email-from', $agentnum);
658 # || 'your-isp-is-dum'
659 $welcome_subject = $conf->config('welcome_email-subject', $agentnum)
661 $welcome_subject_template = new Text::Template (
663 SOURCE => $welcome_subject,
664 ) or warn "can't create welcome email subject template: $Text::Template::ERROR";
665 $welcome_mimetype = $conf->config('welcome_email-mimetype', $agentnum)
668 if ( $welcome_template && $cust_pkg ) {
669 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
673 'custnum' => $self->custnum,
674 'username' => $self->username,
675 'password' => $self->_password,
676 'first' => $cust_main->first,
677 'last' => $cust_main->getfield('last'),
678 'pkg' => $cust_pkg->part_pkg->pkg,
680 my $wqueue = new FS::queue {
681 'svcnum' => $self->svcnum,
682 'job' => 'FS::svc_acct::send_email'
684 my $error = $wqueue->insert(
686 'from' => $welcome_from,
687 'subject' => $welcome_subject_template->fill_in( HASH => \%hash, ),
688 'mimetype' => $welcome_mimetype,
689 'body' => $welcome_template->fill_in( HASH => \%hash, ),
692 $dbh->rollback if $oldAutoCommit;
693 return "error queuing welcome email: $error";
696 if ( $options{'depend_jobnum'} ) {
697 warn "$me depend_jobnum found; adding to welcome email dependancies"
699 if ( ref($options{'depend_jobnum'}) ) {
700 warn "$me adding jobs ". join(', ', @{$options{'depend_jobnum'}} ).
701 "to welcome email dependancies"
703 push @jobnums, @{ $options{'depend_jobnum'} };
705 warn "$me adding job $options{'depend_jobnum'} ".
706 "to welcome email dependancies"
708 push @jobnums, $options{'depend_jobnum'};
712 foreach my $jobnum ( @jobnums ) {
713 my $error = $wqueue->depend_insert($jobnum);
715 $dbh->rollback if $oldAutoCommit;
716 return "error queuing welcome email job dependancy: $error";
726 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
730 # set usage fields and thresholds if unset but set in a package def
731 # AND the package already has a last bill date (otherwise they get double added)
732 sub preinsert_hook_first {
735 return '' unless $self->pkgnum;
737 my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
738 return '' unless $cust_pkg && $cust_pkg->last_bill;
740 my $part_pkg = $cust_pkg->part_pkg;
741 return '' unless $part_pkg && $part_pkg->can('usage_valuehash');
743 my %values = $part_pkg->usage_valuehash;
744 my $multiplier = $conf->exists('svc_acct-usage_threshold')
745 ? 1 - $conf->config('svc_acct-usage_threshold')/100
746 : 0.20; #doesn't matter
748 foreach ( keys %values ) {
749 next if $self->getfield($_);
750 $self->setfield( $_, $values{$_} );
751 $self->setfield( $_. '_threshold', int( $values{$_} * $multiplier ) )
752 if $conf->exists('svc_acct-usage_threshold');
760 Deletes this account from the database. If there is an error, returns the
761 error, otherwise returns false.
763 The corresponding FS::cust_svc record will be deleted as well.
765 (TODOC: new exports!)
772 return "can't delete system account" if $self->_check_system;
774 return "Can't delete an account which is a (svc_forward) source!"
775 if qsearch( 'svc_forward', { 'srcsvc' => $self->svcnum } );
777 return "Can't delete an account which is a (svc_forward) destination!"
778 if qsearch( 'svc_forward', { 'dstsvc' => $self->svcnum } );
780 return "Can't delete an account with (svc_www) web service!"
781 if qsearch( 'svc_www', { 'usersvc' => $self->svcnum } );
783 # what about records in session ? (they should refer to history table)
785 local $SIG{HUP} = 'IGNORE';
786 local $SIG{INT} = 'IGNORE';
787 local $SIG{QUIT} = 'IGNORE';
788 local $SIG{TERM} = 'IGNORE';
789 local $SIG{TSTP} = 'IGNORE';
790 local $SIG{PIPE} = 'IGNORE';
792 my $oldAutoCommit = $FS::UID::AutoCommit;
793 local $FS::UID::AutoCommit = 0;
796 foreach my $cust_main_invoice (
797 qsearch( 'cust_main_invoice', { 'dest' => $self->svcnum } )
799 unless ( defined($cust_main_invoice) ) {
800 warn "WARNING: something's wrong with qsearch";
803 my %hash = $cust_main_invoice->hash;
804 $hash{'dest'} = $self->email;
805 my $new = new FS::cust_main_invoice \%hash;
806 my $error = $new->replace($cust_main_invoice);
808 $dbh->rollback if $oldAutoCommit;
813 foreach my $svc_domain (
814 qsearch( 'svc_domain', { 'catchall' => $self->svcnum } )
816 my %hash = new FS::svc_domain->hash;
817 $hash{'catchall'} = '';
818 my $new = new FS::svc_domain \%hash;
819 my $error = $new->replace($svc_domain);
821 $dbh->rollback if $oldAutoCommit;
826 my $error = $self->SUPER::delete;
828 $dbh->rollback if $oldAutoCommit;
832 foreach my $radius_usergroup (
833 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } )
835 my $error = $radius_usergroup->delete;
837 $dbh->rollback if $oldAutoCommit;
842 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
846 =item replace OLD_RECORD
848 Replaces OLD_RECORD with this one in the database. If there is an error,
849 returns the error, otherwise returns false.
851 The additional field I<usergroup> can optionally be defined; if so it should
852 contain an arrayref of group names. See L<FS::radius_usergroup>.
860 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
864 warn "$me replacing $old with $new\n" if $DEBUG;
868 return "can't modify system account" if $old->_check_system;
871 #no warnings 'numeric'; #alas, a 5.006-ism
874 foreach my $xid (qw( uid gid )) {
876 return "Can't change $xid!"
877 if ! $conf->exists("svc_acct-edit_$xid")
878 && $old->$xid() != $new->$xid()
879 && $new->cust_svc->part_svc->part_svc_column($xid)->columnflag ne 'F'
884 #change homdir when we change username
885 $new->setfield('dir', '') if $old->username ne $new->username;
887 local $SIG{HUP} = 'IGNORE';
888 local $SIG{INT} = 'IGNORE';
889 local $SIG{QUIT} = 'IGNORE';
890 local $SIG{TERM} = 'IGNORE';
891 local $SIG{TSTP} = 'IGNORE';
892 local $SIG{PIPE} = 'IGNORE';
894 my $oldAutoCommit = $FS::UID::AutoCommit;
895 local $FS::UID::AutoCommit = 0;
898 # redundant, but so $new->usergroup gets set
899 $error = $new->check;
900 return $error if $error;
902 $old->usergroup( [ $old->radius_groups ] );
904 warn $old->email. " old groups: ". join(' ',@{$old->usergroup}). "\n";
905 warn $new->email. "new groups: ". join(' ',@{$new->usergroup}). "\n";
907 if ( $new->usergroup ) {
908 #(sorta) false laziness with FS::part_export::sqlradius::_export_replace
909 my @newgroups = @{$new->usergroup};
910 foreach my $oldgroup ( @{$old->usergroup} ) {
911 if ( grep { $oldgroup eq $_ } @newgroups ) {
912 @newgroups = grep { $oldgroup ne $_ } @newgroups;
915 my $radius_usergroup = qsearchs('radius_usergroup', {
916 svcnum => $old->svcnum,
917 groupname => $oldgroup,
919 my $error = $radius_usergroup->delete;
921 $dbh->rollback if $oldAutoCommit;
922 return "error deleting radius_usergroup $oldgroup: $error";
926 foreach my $newgroup ( @newgroups ) {
927 my $radius_usergroup = new FS::radius_usergroup ( {
928 svcnum => $new->svcnum,
929 groupname => $newgroup,
931 my $error = $radius_usergroup->insert;
933 $dbh->rollback if $oldAutoCommit;
934 return "error adding radius_usergroup $newgroup: $error";
940 $error = $new->SUPER::replace($old, @_);
942 $dbh->rollback if $oldAutoCommit;
943 return $error if $error;
946 if ( $new->username ne $old->username && ! $skip_fuzzyfiles ) {
947 $error = $new->queue_fuzzyfiles_update;
949 $dbh->rollback if $oldAutoCommit;
950 return "updating fuzzy search cache: $error";
954 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
958 =item queue_fuzzyfiles_update
960 Used by insert & replace to update the fuzzy search cache
964 sub queue_fuzzyfiles_update {
967 local $SIG{HUP} = 'IGNORE';
968 local $SIG{INT} = 'IGNORE';
969 local $SIG{QUIT} = 'IGNORE';
970 local $SIG{TERM} = 'IGNORE';
971 local $SIG{TSTP} = 'IGNORE';
972 local $SIG{PIPE} = 'IGNORE';
974 my $oldAutoCommit = $FS::UID::AutoCommit;
975 local $FS::UID::AutoCommit = 0;
978 my $queue = new FS::queue {
979 'svcnum' => $self->svcnum,
980 'job' => 'FS::svc_acct::append_fuzzyfiles'
982 my $error = $queue->insert($self->username);
984 $dbh->rollback if $oldAutoCommit;
985 return "queueing job (transaction rolled back): $error";
988 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
996 Suspends this account by calling export-specific suspend hooks. If there is
997 an error, returns the error, otherwise returns false.
999 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1005 return "can't suspend system account" if $self->_check_system;
1006 $self->SUPER::suspend(@_);
1011 Unsuspends this account by by calling export-specific suspend hooks. If there
1012 is an error, returns the error, otherwise returns false.
1014 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1020 my %hash = $self->hash;
1021 if ( $hash{_password} =~ /^\*SUSPENDED\* (.*)$/ ) {
1022 $hash{_password} = $1;
1023 my $new = new FS::svc_acct ( \%hash );
1024 my $error = $new->replace($self);
1025 return $error if $error;
1028 $self->SUPER::unsuspend(@_);
1033 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
1035 If the B<auto_unset_catchall> configuration option is set, this method will
1036 automatically remove any references to the canceled service in the catchall
1037 field of svc_domain. This allows packages that contain both a svc_domain and
1038 its catchall svc_acct to be canceled in one step.
1043 # Only one thing to do at this level
1045 foreach my $svc_domain (
1046 qsearch( 'svc_domain', { catchall => $self->svcnum } ) ) {
1047 if($conf->exists('auto_unset_catchall')) {
1048 my %hash = $svc_domain->hash;
1049 $hash{catchall} = '';
1050 my $new = new FS::svc_domain ( \%hash );
1051 my $error = $new->replace($svc_domain);
1052 return $error if $error;
1054 return "cannot unprovision svc_acct #".$self->svcnum.
1055 " while assigned as catchall for svc_domain #".$svc_domain->svcnum;
1059 $self->SUPER::cancel(@_);
1065 Checks all fields to make sure this is a valid service. If there is an error,
1066 returns the error, otherwise returns false. Called by the insert and replace
1069 Sets any fixed values; see L<FS::part_svc>.
1076 my($recref) = $self->hashref;
1078 my $x = $self->setfixed( $self->_fieldhandlers );
1079 return $x unless ref($x);
1082 if ( $part_svc->part_svc_column('usergroup')->columnflag eq "F" ) {
1084 [ split(',', $part_svc->part_svc_column('usergroup')->columnvalue) ] );
1087 my $error = $self->ut_numbern('svcnum')
1088 #|| $self->ut_number('domsvc')
1089 || $self->ut_foreign_key( 'domsvc', 'svc_domain', 'svcnum' )
1090 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
1091 || $self->ut_textn('sec_phrase')
1092 || $self->ut_snumbern('seconds')
1093 || $self->ut_snumbern('upbytes')
1094 || $self->ut_snumbern('downbytes')
1095 || $self->ut_snumbern('totalbytes')
1096 || $self->ut_enum( '_password_encoding',
1097 [ '', qw( plain crypt ldap ) ]
1099 || $self->ut_enum( 'password_selfchange', [ '', 'Y' ] )
1100 || $self->ut_enum( 'password_recover', [ '', 'Y' ] )
1101 || $self->ut_textn( 'cgp_accessmodes' )
1102 || $self->ut_alphan( 'cgp_type' )
1103 || $self->ut_textn( 'cgp_aliases' ) #well
1105 return $error if $error;
1108 local $username_letter = $username_letter;
1109 if ($self->svcnum) {
1110 my $cust_svc = $self->cust_svc
1111 or return "no cust_svc record found for svcnum ". $self->svcnum;
1112 my $cust_pkg = $cust_svc->cust_pkg;
1114 if ($self->pkgnum) {
1115 $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $self->pkgnum } );#complain?
1119 $conf->exists('username-letter', $cust_pkg->cust_main->agentnum);
1122 my $ulen = $usernamemax || $self->dbdef_table->column('username')->length;
1123 if ( $username_uppercase ) {
1124 $recref->{username} =~ /^([a-z0-9_\-\.\&\%\:]{$usernamemin,$ulen})$/i
1125 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
1126 $recref->{username} = $1;
1128 $recref->{username} =~ /^([a-z0-9_\-\.\&\%\:]{$usernamemin,$ulen})$/
1129 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
1130 $recref->{username} = $1;
1133 if ( $username_letterfirst ) {
1134 $recref->{username} =~ /^[a-z]/ or return gettext('illegal_username');
1135 } elsif ( $username_letter ) {
1136 $recref->{username} =~ /[a-z]/ or return gettext('illegal_username');
1138 if ( $username_noperiod ) {
1139 $recref->{username} =~ /\./ and return gettext('illegal_username');
1141 if ( $username_nounderscore ) {
1142 $recref->{username} =~ /_/ and return gettext('illegal_username');
1144 if ( $username_nodash ) {
1145 $recref->{username} =~ /\-/ and return gettext('illegal_username');
1147 unless ( $username_ampersand ) {
1148 $recref->{username} =~ /\&/ and return gettext('illegal_username');
1150 unless ( $username_percent ) {
1151 $recref->{username} =~ /\%/ and return gettext('illegal_username');
1153 unless ( $username_colon ) {
1154 $recref->{username} =~ /\:/ and return gettext('illegal_username');
1157 $recref->{popnum} =~ /^(\d*)$/ or return "Illegal popnum: ".$recref->{popnum};
1158 $recref->{popnum} = $1;
1159 return "Unknown popnum" unless
1160 ! $recref->{popnum} ||
1161 qsearchs('svc_acct_pop',{'popnum'=> $recref->{popnum} } );
1163 unless ( $part_svc->part_svc_column('uid')->columnflag eq 'F' ) {
1165 $recref->{uid} =~ /^(\d*)$/ or return "Illegal uid";
1166 $recref->{uid} = $1 eq '' ? $self->unique('uid') : $1;
1168 $recref->{gid} =~ /^(\d*)$/ or return "Illegal gid";
1169 $recref->{gid} = $1 eq '' ? $recref->{uid} : $1;
1170 #not all systems use gid=uid
1171 #you can set a fixed gid in part_svc
1173 return "Only root can have uid 0"
1174 if $recref->{uid} == 0
1175 && $recref->{username} !~ /^(root|toor|smtp)$/;
1177 unless ( $recref->{username} eq 'sync' ) {
1178 if ( grep $_ eq $recref->{shell}, @shells ) {
1179 $recref->{shell} = (grep $_ eq $recref->{shell}, @shells)[0];
1181 return "Illegal shell \`". $self->shell. "\'; ".
1182 "shells configuration value contains: @shells";
1185 $recref->{shell} = '/bin/sync';
1189 $recref->{gid} ne '' ?
1190 return "Can't have gid without uid" : ( $recref->{gid}='' );
1191 #$recref->{dir} ne '' ?
1192 # return "Can't have directory without uid" : ( $recref->{dir}='' );
1193 $recref->{shell} ne '' ?
1194 return "Can't have shell without uid" : ( $recref->{shell}='' );
1197 unless ( $part_svc->part_svc_column('dir')->columnflag eq 'F' ) {
1199 $recref->{dir} =~ /^([\/\w\-\.\&]*)$/
1200 or return "Illegal directory: ". $recref->{dir};
1201 $recref->{dir} = $1;
1202 return "Illegal directory"
1203 if $recref->{dir} =~ /(^|\/)\.+(\/|$)/; #no .. component
1204 return "Illegal directory"
1205 if $recref->{dir} =~ /\&/ && ! $username_ampersand;
1206 unless ( $recref->{dir} ) {
1207 $recref->{dir} = $dir_prefix . '/';
1208 if ( $dirhash > 0 ) {
1209 for my $h ( 1 .. $dirhash ) {
1210 $recref->{dir} .= substr($recref->{username}, $h-1, 1). '/';
1212 } elsif ( $dirhash < 0 ) {
1213 for my $h ( reverse $dirhash .. -1 ) {
1214 $recref->{dir} .= substr($recref->{username}, $h, 1). '/';
1217 $recref->{dir} .= $recref->{username};
1223 # $error = $self->ut_textn('finger');
1224 # return $error if $error;
1225 if ( $self->getfield('finger') eq '' ) {
1226 my $cust_pkg = $self->svcnum
1227 ? $self->cust_svc->cust_pkg
1228 : qsearchs('cust_pkg', { 'pkgnum' => $self->getfield('pkgnum') } );
1230 my $cust_main = $cust_pkg->cust_main;
1231 $self->setfield('finger', $cust_main->first.' '.$cust_main->get('last') );
1234 $self->getfield('finger') =~
1235 /^([\w \t\!\@\#\$\%\&\(\)\-\+\;\'\"\,\.\?\/\*\<\>]*)$/
1236 or return "Illegal finger: ". $self->getfield('finger');
1237 $self->setfield('finger', $1);
1239 for (qw( quota file_quota file_maxsize )) {
1240 $recref->{$_} =~ /^(\w*)$/ or return "Illegal $_";
1243 $recref->{file_maxnum} =~ /^\s*(\d*)\s*$/ or return "Illegal file_maxnum";
1244 $recref->{file_maxnum} = $1;
1246 unless ( $part_svc->part_svc_column('slipip')->columnflag eq 'F' ) {
1247 if ( $recref->{slipip} eq '' ) {
1248 $recref->{slipip} = '';
1249 } elsif ( $recref->{slipip} eq '0e0' ) {
1250 $recref->{slipip} = '0e0';
1252 $recref->{slipip} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/
1253 or return "Illegal slipip: ". $self->slipip;
1254 $recref->{slipip} = $1;
1259 #arbitrary RADIUS stuff; allow ut_textn for now
1260 foreach ( grep /^radius_/, fields('svc_acct') ) {
1261 $self->ut_textn($_);
1264 # First, if _password is blank, generate one and set default encoding.
1265 if ( ! $recref->{_password} ) {
1266 $error = $self->set_password('');
1268 # But if there's a _password but no encoding, assume it's plaintext and
1269 # set it to default encoding.
1270 elsif ( ! $recref->{_password_encoding} ) {
1271 $error = $self->set_password($recref->{_password});
1273 return $error if $error;
1275 # Next, check _password to ensure compliance with the encoding.
1276 if ( $recref->{_password_encoding} eq 'ldap' ) {
1278 if ( $recref->{_password} =~ /^(\{[\w\-]+\})(!?.{0,64})$/ ) {
1279 $recref->{_password} = uc($1).$2;
1281 return 'Illegal (ldap-encoded) password: '. $recref->{_password};
1284 } elsif ( $recref->{_password_encoding} eq 'crypt' ) {
1286 if ( $recref->{_password} =~
1287 #/^(\$\w+\$.*|[\w\+\/]{13}|_[\w\+\/]{19}|\*)$/
1288 /^(!!?)?(\$\w+\$.*|[\w\+\/\.]{13}|_[\w\+\/\.]{19}|\*)$/
1291 $recref->{_password} = ( defined($1) ? $1 : '' ). $2;
1294 return 'Illegal (crypt-encoded) password: '. $recref->{_password};
1297 } elsif ( $recref->{_password_encoding} eq 'plain' ) {
1298 # Password randomization is now in set_password.
1299 # Strip whitespace characters, check length requirements, etc.
1300 if ( $recref->{_password} =~ /^([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1301 $recref->{_password} = $1;
1303 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1304 FS::Msgcat::_gettext('illegal_password_characters').
1305 ": ". $recref->{_password};
1308 if ( $password_noampersand ) {
1309 $recref->{_password} =~ /\&/ and return gettext('illegal_password');
1311 if ( $password_noexclamation ) {
1312 $recref->{_password} =~ /\!/ and return gettext('illegal_password');
1316 return "invalid password encoding ('".$recref->{_password_encoding}."'";
1318 $self->SUPER::check;
1323 sub _password_encryption {
1325 my $encoding = lc($self->_password_encoding);
1326 return if !$encoding;
1327 return 'plain' if $encoding eq 'plain';
1328 if($encoding eq 'crypt') {
1329 my $pass = $self->_password;
1330 $pass =~ s/^\*SUSPENDED\* //;
1332 return 'md5' if $pass =~ /^\$1\$/;
1333 #return 'blowfish' if $self->_password =~ /^\$2\$/;
1334 return 'des' if length($pass) == 13;
1337 if($encoding eq 'ldap') {
1338 uc($self->_password) =~ /^\{([\w-]+)\}/;
1339 return 'crypt' if $1 eq 'CRYPT' or $1 eq 'DES';
1340 return 'plain' if $1 eq 'PLAIN' or $1 eq 'CLEARTEXT';
1341 return 'md5' if $1 eq 'MD5';
1342 return 'sha1' if $1 eq 'SHA' or $1 eq 'SHA-1';
1349 sub get_cleartext_password {
1351 if($self->_password_encryption eq 'plain') {
1352 if($self->_password_encoding eq 'ldap') {
1353 $self->_password =~ /\{\w+\}(.*)$/;
1357 return $self->_password;
1366 Set the cleartext password for the account. If _password_encoding is set, the
1367 new password will be encoded according to the existing method (including
1368 encryption mode, if it can be determined). Otherwise,
1369 config('default-password-encoding') is used.
1371 If no password is supplied (or a zero-length password when minimum password length
1372 is >0), one will be generated randomly.
1377 my( $self, $pass ) = ( shift, shift );
1379 warn "[$me] set_password (to $pass) called on $self: ". Dumper($self)
1382 my $failure = gettext('illegal_password'). " $passwordmin-$passwordmax ".
1383 FS::Msgcat::_gettext('illegal_password_characters').
1386 my( $encoding, $encryption ) = ('', '');
1388 if ( $self->_password_encoding ) {
1389 $encoding = $self->_password_encoding;
1390 # identify existing encryption method, try to use it.
1391 $encryption = $self->_password_encryption;
1393 # use the system default
1399 # set encoding to system default
1400 ($encoding, $encryption) =
1401 split(/-/, lc($conf->config('default-password-encoding')));
1402 $encoding ||= 'legacy';
1403 $self->_password_encoding($encoding);
1406 if ( $encoding eq 'legacy' ) {
1408 # The legacy behavior from check():
1409 # If the password is blank, randomize it and set encoding to 'plain'.
1410 if(!defined($pass) or (length($pass) == 0 and $passwordmin)) {
1411 $pass = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1412 $self->_password_encoding('plain');
1414 # Prefix + valid-length password
1415 if ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1417 $self->_password_encoding('plain');
1418 # Prefix + crypt string
1419 } elsif ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([\w\.\/\$\;\+]{13,64})$/ ) {
1421 $self->_password_encoding('crypt');
1422 # Various disabled crypt passwords
1423 } elsif ( $pass eq '*' || $pass eq '!' || $pass eq '!!' ) {
1424 $self->_password_encoding('crypt');
1430 $self->_password($pass);
1436 if $passwordmin && length($pass) < $passwordmin
1437 or $passwordmax && length($pass) > $passwordmax;
1439 if ( $encoding eq 'crypt' ) {
1440 if ($encryption eq 'md5') {
1441 $pass = unix_md5_crypt($pass);
1442 } elsif ($encryption eq 'des') {
1443 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1446 } elsif ( $encoding eq 'ldap' ) {
1447 if ($encryption eq 'md5') {
1448 $pass = md5_base64($pass);
1449 } elsif ($encryption eq 'sha1') {
1450 $pass = sha1_base64($pass);
1451 } elsif ($encryption eq 'crypt') {
1452 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1454 # else $encryption eq 'plain', do nothing
1455 $pass = '{'.uc($encryption).'}'.$pass;
1457 # else encoding eq 'plain'
1459 $self->_password($pass);
1465 Internal function to check the username against the list of system usernames
1466 from the I<system_usernames> configuration value. Returns true if the username
1467 is listed on the system username list.
1473 scalar( grep { $self->username eq $_ || $self->email eq $_ }
1474 $conf->config('system_usernames')
1478 =item _check_duplicate
1480 Internal method to check for duplicates usernames, username@domain pairs and
1483 If the I<global_unique-username> configuration value is set to B<username> or
1484 B<username@domain>, enforces global username or username@domain uniqueness.
1486 In all cases, check for duplicate uids and usernames or username@domain pairs
1487 per export and with identical I<svcpart> values.
1491 sub _check_duplicate {
1494 my $global_unique = $conf->config('global_unique-username') || 'none';
1495 return '' if $global_unique eq 'disabled';
1499 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
1500 unless ( $part_svc ) {
1501 return 'unknown svcpart '. $self->svcpart;
1504 my @dup_user = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1505 qsearch( 'svc_acct', { 'username' => $self->username } );
1506 return gettext('username_in_use')
1507 if $global_unique eq 'username' && @dup_user;
1509 my @dup_userdomain = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1510 qsearch( 'svc_acct', { 'username' => $self->username,
1511 'domsvc' => $self->domsvc } );
1512 return gettext('username_in_use')
1513 if $global_unique eq 'username@domain' && @dup_userdomain;
1516 if ( $part_svc->part_svc_column('uid')->columnflag ne 'F'
1517 && $self->username !~ /^(toor|(hyla)?fax)$/ ) {
1518 @dup_uid = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1519 qsearch( 'svc_acct', { 'uid' => $self->uid } );
1524 if ( @dup_user || @dup_userdomain || @dup_uid ) {
1525 my $exports = FS::part_export::export_info('svc_acct');
1526 my %conflict_user_svcpart;
1527 my %conflict_userdomain_svcpart = ( $self->svcpart => 'SELF', );
1529 foreach my $part_export ( $part_svc->part_export ) {
1531 #this will catch to the same exact export
1532 my @svcparts = map { $_->svcpart } $part_export->export_svc;
1534 #this will catch to exports w/same exporthost+type ???
1535 #my @other_part_export = qsearch('part_export', {
1536 # 'machine' => $part_export->machine,
1537 # 'exporttype' => $part_export->exporttype,
1539 #foreach my $other_part_export ( @other_part_export ) {
1540 # push @svcparts, map { $_->svcpart }
1541 # qsearch('export_svc', { 'exportnum' => $part_export->exportnum });
1544 #my $nodomain = $exports->{$part_export->exporttype}{'nodomain'};
1545 #silly kludge to avoid uninitialized value errors
1546 my $nodomain = exists( $exports->{$part_export->exporttype}{'nodomain'} )
1547 ? $exports->{$part_export->exporttype}{'nodomain'}
1549 if ( $nodomain =~ /^Y/i ) {
1550 $conflict_user_svcpart{$_} = $part_export->exportnum
1553 $conflict_userdomain_svcpart{$_} = $part_export->exportnum
1558 foreach my $dup_user ( @dup_user ) {
1559 my $dup_svcpart = $dup_user->cust_svc->svcpart;
1560 if ( exists($conflict_user_svcpart{$dup_svcpart}) ) {
1561 return "duplicate username ". $self->username.
1562 ": conflicts with svcnum ". $dup_user->svcnum.
1563 " via exportnum ". $conflict_user_svcpart{$dup_svcpart};
1567 foreach my $dup_userdomain ( @dup_userdomain ) {
1568 my $dup_svcpart = $dup_userdomain->cust_svc->svcpart;
1569 if ( exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1570 return "duplicate username\@domain ". $self->email.
1571 ": conflicts with svcnum ". $dup_userdomain->svcnum.
1572 " via exportnum ". $conflict_userdomain_svcpart{$dup_svcpart};
1576 foreach my $dup_uid ( @dup_uid ) {
1577 my $dup_svcpart = $dup_uid->cust_svc->svcpart;
1578 if ( exists($conflict_user_svcpart{$dup_svcpart})
1579 || exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1580 return "duplicate uid ". $self->uid.
1581 ": conflicts with svcnum ". $dup_uid->svcnum.
1583 ( $conflict_user_svcpart{$dup_svcpart}
1584 || $conflict_userdomain_svcpart{$dup_svcpart} );
1596 Depriciated, use radius_reply instead.
1601 carp "FS::svc_acct::radius depriciated, use radius_reply";
1602 $_[0]->radius_reply;
1607 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1608 reply attributes of this record.
1610 Note that this is now the preferred method for reading RADIUS attributes -
1611 accessing the columns directly is discouraged, as the column names are
1612 expected to change in the future.
1619 return %{ $self->{'radius_reply'} }
1620 if exists $self->{'radius_reply'};
1625 my($column, $attrib) = ($1, $2);
1626 #$attrib =~ s/_/\-/g;
1627 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1628 } grep { /^radius_/ && $self->getfield($_) } fields( $self->table );
1630 if ( $self->slipip && $self->slipip ne '0e0' ) {
1631 $reply{$radius_ip} = $self->slipip;
1634 if ( $self->seconds !~ /^$/ ) {
1635 $reply{'Session-Timeout'} = $self->seconds;
1638 if ( $conf->exists('radius-chillispot-max') ) {
1639 #http://dev.coova.org/svn/coova-chilli/doc/dictionary.chillispot
1641 #hmm. just because sqlradius.pm says so?
1648 foreach my $what (qw( input output total )) {
1649 my $is = $whatis{$what}.'bytes';
1650 if ( $self->$is() =~ /\d/ ) {
1651 my $big = new Math::BigInt $self->$is();
1652 $big = new Math::BigInt '0' if $big->is_neg();
1653 my $att = "Chillispot-Max-\u$what";
1654 $reply{"$att-Octets"} = $big->copy->band(0xffffffff)->bstr;
1655 $reply{"$att-Gigawords"} = $big->copy->brsft(32)->bstr;
1666 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1667 check attributes of this record.
1669 Note that this is now the preferred method for reading RADIUS attributes -
1670 accessing the columns directly is discouraged, as the column names are
1671 expected to change in the future.
1678 return %{ $self->{'radius_check'} }
1679 if exists $self->{'radius_check'};
1684 my($column, $attrib) = ($1, $2);
1685 #$attrib =~ s/_/\-/g;
1686 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1687 } grep { /^rc_/ && $self->getfield($_) } fields( $self->table );
1690 my($pw_attrib, $password) = $self->radius_password;
1691 $check{$pw_attrib} = $password;
1693 my $cust_svc = $self->cust_svc;
1695 my $cust_pkg = $cust_svc->cust_pkg;
1696 if ( $cust_pkg && $cust_pkg->part_pkg->is_prepaid && $cust_pkg->bill ) {
1697 $check{'Expiration'} = time2str('%B %e %Y %T', $cust_pkg->bill ); #http://lists.cistron.nl/pipermail/freeradius-users/2005-January/040184.html
1700 warn "WARNING: no cust_svc record for svc_acct.svcnum ". $self->svcnum.
1701 "; can't set Expiration\n"
1709 =item radius_password
1711 Returns a key/value pair containing the RADIUS attribute name and value
1716 sub radius_password {
1720 if ( $self->_password_encoding eq 'ldap' ) {
1721 $pw_attrib = 'Password-With-Header';
1722 } elsif ( $self->_password_encoding eq 'crypt' ) {
1723 $pw_attrib = 'Crypt-Password';
1724 } elsif ( $self->_password_encoding eq 'plain' ) {
1725 $pw_attrib = $radius_password;
1727 $pw_attrib = length($self->_password) <= 12
1732 ($pw_attrib, $self->_password);
1738 This method instructs the object to "snapshot" or freeze RADIUS check and
1739 reply attributes to the current values.
1743 #bah, my english is too broken this morning
1744 #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
1745 #the FS::cust_pkg's replace method to trigger the correct export updates when
1746 #package dates change)
1751 $self->{$_} = { $self->$_() }
1752 foreach qw( radius_reply radius_check );
1756 =item forget_snapshot
1758 This methos instructs the object to forget any previously snapshotted
1759 RADIUS check and reply attributes.
1763 sub forget_snapshot {
1767 foreach qw( radius_reply radius_check );
1771 =item domain [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1773 Returns the domain associated with this account.
1775 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1782 die "svc_acct.domsvc is null for svcnum ". $self->svcnum unless $self->domsvc;
1783 my $svc_domain = $self->svc_domain(@_)
1784 or die "no svc_domain.svcnum for svc_acct.domsvc ". $self->domsvc;
1785 $svc_domain->domain;
1790 Returns the FS::svc_domain record for this account's domain (see
1795 # FS::h_svc_acct has a history-aware svc_domain override
1800 ? $self->{'_domsvc'}
1801 : qsearchs( 'svc_domain', { 'svcnum' => $self->domsvc } );
1806 Returns the FS::cust_svc record for this account (see L<FS::cust_svc>).
1810 #inherited from svc_Common
1812 =item email [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1814 Returns an email address associated with the account.
1816 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1823 $self->username. '@'. $self->domain(@_);
1828 Returns an array of FS::acct_snarf records associated with the account.
1829 If the acct_snarf table does not exist or there are no associated records,
1830 an empty list is returned
1836 return () unless dbdef->table('acct_snarf');
1837 eval "use FS::acct_snarf;";
1839 qsearch('acct_snarf', { 'svcnum' => $self->svcnum } );
1842 =item decrement_upbytes OCTETS
1844 Decrements the I<upbytes> field of this record by the given amount. If there
1845 is an error, returns the error, otherwise returns false.
1849 sub decrement_upbytes {
1850 shift->_op_usage('-', 'upbytes', @_);
1853 =item increment_upbytes OCTETS
1855 Increments the I<upbytes> field of this record by the given amount. If there
1856 is an error, returns the error, otherwise returns false.
1860 sub increment_upbytes {
1861 shift->_op_usage('+', 'upbytes', @_);
1864 =item decrement_downbytes OCTETS
1866 Decrements the I<downbytes> field of this record by the given amount. If there
1867 is an error, returns the error, otherwise returns false.
1871 sub decrement_downbytes {
1872 shift->_op_usage('-', 'downbytes', @_);
1875 =item increment_downbytes OCTETS
1877 Increments the I<downbytes> field of this record by the given amount. If there
1878 is an error, returns the error, otherwise returns false.
1882 sub increment_downbytes {
1883 shift->_op_usage('+', 'downbytes', @_);
1886 =item decrement_totalbytes OCTETS
1888 Decrements the I<totalbytes> field of this record by the given amount. If there
1889 is an error, returns the error, otherwise returns false.
1893 sub decrement_totalbytes {
1894 shift->_op_usage('-', 'totalbytes', @_);
1897 =item increment_totalbytes OCTETS
1899 Increments the I<totalbytes> field of this record by the given amount. If there
1900 is an error, returns the error, otherwise returns false.
1904 sub increment_totalbytes {
1905 shift->_op_usage('+', 'totalbytes', @_);
1908 =item decrement_seconds SECONDS
1910 Decrements the I<seconds> field of this record by the given amount. If there
1911 is an error, returns the error, otherwise returns false.
1915 sub decrement_seconds {
1916 shift->_op_usage('-', 'seconds', @_);
1919 =item increment_seconds SECONDS
1921 Increments the I<seconds> field of this record by the given amount. If there
1922 is an error, returns the error, otherwise returns false.
1926 sub increment_seconds {
1927 shift->_op_usage('+', 'seconds', @_);
1935 my %op2condition = (
1936 '-' => sub { my($self, $column, $amount) = @_;
1937 $self->$column - $amount <= 0;
1939 '+' => sub { my($self, $column, $amount) = @_;
1940 ($self->$column || 0) + $amount > 0;
1943 my %op2warncondition = (
1944 '-' => sub { my($self, $column, $amount) = @_;
1945 my $threshold = $column . '_threshold';
1946 $self->$column - $amount <= $self->$threshold + 0;
1948 '+' => sub { my($self, $column, $amount) = @_;
1949 ($self->$column || 0) + $amount > 0;
1954 my( $self, $op, $column, $amount ) = @_;
1956 warn "$me _op_usage called for $column on svcnum ". $self->svcnum.
1957 ' ('. $self->email. "): $op $amount\n"
1960 return '' unless $amount;
1962 local $SIG{HUP} = 'IGNORE';
1963 local $SIG{INT} = 'IGNORE';
1964 local $SIG{QUIT} = 'IGNORE';
1965 local $SIG{TERM} = 'IGNORE';
1966 local $SIG{TSTP} = 'IGNORE';
1967 local $SIG{PIPE} = 'IGNORE';
1969 my $oldAutoCommit = $FS::UID::AutoCommit;
1970 local $FS::UID::AutoCommit = 0;
1973 my $sql = "UPDATE svc_acct SET $column = ".
1974 " CASE WHEN $column IS NULL THEN 0 ELSE $column END ". #$column||0
1975 " $op ? WHERE svcnum = ?";
1979 my $sth = $dbh->prepare( $sql )
1980 or die "Error preparing $sql: ". $dbh->errstr;
1981 my $rv = $sth->execute($amount, $self->svcnum);
1982 die "Error executing $sql: ". $sth->errstr
1983 unless defined($rv);
1984 die "Can't update $column for svcnum". $self->svcnum
1987 #$self->snapshot; #not necessary, we retain the old values
1988 #create an object with the updated usage values
1989 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
1991 my $error = $new->replace($self);
1993 $dbh->rollback if $oldAutoCommit;
1994 return "Error replacing: $error";
1997 #overlimit_action eq 'cancel' handling
1998 my $cust_pkg = $self->cust_svc->cust_pkg;
2000 && $cust_pkg->part_pkg->option('overlimit_action', 1) eq 'cancel'
2001 && $op eq '-' && &{$op2condition{$op}}($self, $column, $amount)
2005 my $error = $cust_pkg->cancel; #XXX should have a reason
2007 $dbh->rollback if $oldAutoCommit;
2008 return "Error cancelling: $error";
2011 #nothing else is relevant if we're cancelling, so commit & return success
2012 warn "$me update successful; committing\n"
2014 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2019 my $action = $op2action{$op};
2021 if ( &{$op2condition{$op}}($self, $column, $amount) &&
2022 ( $action eq 'suspend' && !$self->overlimit
2023 || $action eq 'unsuspend' && $self->overlimit )
2026 my $error = $self->_op_overlimit($action);
2028 $dbh->rollback if $oldAutoCommit;
2034 if ( $conf->exists("svc_acct-usage_$action")
2035 && &{$op2condition{$op}}($self, $column, $amount) ) {
2036 #my $error = $self->$action();
2037 my $error = $self->cust_svc->cust_pkg->$action();
2038 # $error ||= $self->overlimit($action);
2040 $dbh->rollback if $oldAutoCommit;
2041 return "Error ${action}ing: $error";
2045 if ($warning_template && &{$op2warncondition{$op}}($self, $column, $amount)) {
2046 my $wqueue = new FS::queue {
2047 'svcnum' => $self->svcnum,
2048 'job' => 'FS::svc_acct::reached_threshold',
2053 $to = $warning_cc if &{$op2condition{$op}}($self, $column, $amount);
2057 my $error = $wqueue->insert(
2058 'svcnum' => $self->svcnum,
2060 'column' => $column,
2064 $dbh->rollback if $oldAutoCommit;
2065 return "Error queuing threshold activity: $error";
2069 warn "$me update successful; committing\n"
2071 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2077 my( $self, $action ) = @_;
2079 local $SIG{HUP} = 'IGNORE';
2080 local $SIG{INT} = 'IGNORE';
2081 local $SIG{QUIT} = 'IGNORE';
2082 local $SIG{TERM} = 'IGNORE';
2083 local $SIG{TSTP} = 'IGNORE';
2084 local $SIG{PIPE} = 'IGNORE';
2086 my $oldAutoCommit = $FS::UID::AutoCommit;
2087 local $FS::UID::AutoCommit = 0;
2090 my $cust_pkg = $self->cust_svc->cust_pkg;
2092 my $conf_overlimit =
2094 ? $conf->config('overlimit_groups', $cust_pkg->cust_main->agentnum )
2095 : $conf->config('overlimit_groups');
2097 foreach my $part_export ( $self->cust_svc->part_svc->part_export ) {
2099 my $groups = $conf_overlimit || $part_export->option('overlimit_groups');
2100 next unless $groups;
2102 my $gref = &{ $self->_fieldhandlers->{'usergroup'} }( $self, $groups );
2104 my $other = new FS::svc_acct $self->hashref;
2105 $other->usergroup( $gref );
2108 if ($action eq 'suspend') {
2111 } else { # $action eq 'unsuspend'
2116 my $error = $part_export->export_replace($new, $old)
2117 || $self->overlimit($action);
2120 $dbh->rollback if $oldAutoCommit;
2121 return "Error replacing radius groups: $error";
2126 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2132 my( $self, $valueref, %options ) = @_;
2134 warn "$me set_usage called for svcnum ". $self->svcnum.
2135 ' ('. $self->email. "): ".
2136 join(', ', map { "$_ => " . $valueref->{$_}} keys %$valueref) . "\n"
2139 local $SIG{HUP} = 'IGNORE';
2140 local $SIG{INT} = 'IGNORE';
2141 local $SIG{QUIT} = 'IGNORE';
2142 local $SIG{TERM} = 'IGNORE';
2143 local $SIG{TSTP} = 'IGNORE';
2144 local $SIG{PIPE} = 'IGNORE';
2146 local $FS::svc_Common::noexport_hack = 1;
2147 my $oldAutoCommit = $FS::UID::AutoCommit;
2148 local $FS::UID::AutoCommit = 0;
2153 if ( $options{null} ) {
2154 %handyhash = ( map { ( $_ => 'NULL', $_."_threshold" => 'NULL' ) }
2155 qw( seconds upbytes downbytes totalbytes )
2158 foreach my $field (keys %$valueref){
2159 $reset = 1 if $valueref->{$field};
2160 $self->setfield($field, $valueref->{$field});
2161 $self->setfield( $field.'_threshold',
2162 int($self->getfield($field)
2163 * ( $conf->exists('svc_acct-usage_threshold')
2164 ? 1 - $conf->config('svc_acct-usage_threshold')/100
2169 $handyhash{$field} = $self->getfield($field);
2170 $handyhash{$field.'_threshold'} = $self->getfield($field.'_threshold');
2172 #my $error = $self->replace; #NO! we avoid the call to ->check for
2173 #die $error if $error; #services not explicity changed via the UI
2175 my $sql = "UPDATE svc_acct SET " .
2176 join (',', map { "$_ = $handyhash{$_}" } (keys %handyhash) ).
2177 " WHERE svcnum = ". $self->svcnum;
2182 if (scalar(keys %handyhash)) {
2183 my $sth = $dbh->prepare( $sql )
2184 or die "Error preparing $sql: ". $dbh->errstr;
2185 my $rv = $sth->execute();
2186 die "Error executing $sql: ". $sth->errstr
2187 unless defined($rv);
2188 die "Can't update usage for svcnum ". $self->svcnum
2192 #$self->snapshot; #not necessary, we retain the old values
2193 #create an object with the updated usage values
2194 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2195 local($FS::Record::nowarn_identical) = 1;
2196 my $error = $new->replace($self); #call exports
2198 $dbh->rollback if $oldAutoCommit;
2199 return "Error replacing: $error";
2206 $error = $self->_op_overlimit('unsuspend')
2207 if $self->overlimit;;
2209 $error ||= $self->cust_svc->cust_pkg->unsuspend
2210 if $conf->exists("svc_acct-usage_unsuspend");
2213 $dbh->rollback if $oldAutoCommit;
2214 return "Error unsuspending: $error";
2219 warn "$me update successful; committing\n"
2221 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2227 =item recharge HASHREF
2229 Increments usage columns by the amount specified in HASHREF as
2230 column=>amount pairs.
2235 my ($self, $vhash) = @_;
2238 warn "[$me] recharge called on $self: ". Dumper($self).
2239 "\nwith vhash: ". Dumper($vhash);
2242 my $oldAutoCommit = $FS::UID::AutoCommit;
2243 local $FS::UID::AutoCommit = 0;
2247 foreach my $column (keys %$vhash){
2248 $error ||= $self->_op_usage('+', $column, $vhash->{$column});
2252 $dbh->rollback if $oldAutoCommit;
2254 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2259 =item is_rechargeable
2261 Returns true if this svc_account can be "recharged" and false otherwise.
2265 sub is_rechargable {
2267 $self->seconds ne ''
2268 || $self->upbytes ne ''
2269 || $self->downbytes ne ''
2270 || $self->totalbytes ne '';
2273 =item seconds_since TIMESTAMP
2275 Returns the number of seconds this account has been online since TIMESTAMP,
2276 according to the session monitor (see L<FS::Session>).
2278 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2279 L<Time::Local> and L<Date::Parse> for conversion functions.
2283 #note: POD here, implementation in FS::cust_svc
2286 $self->cust_svc->seconds_since(@_);
2289 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2291 Returns the numbers of seconds this account has been online between
2292 TIMESTAMP_START (inclusive) and TIMESTAMP_END (exclusive), according to an
2293 external SQL radacct table, specified via sqlradius export. Sessions which
2294 started in the specified range but are still open are counted from session
2295 start to the end of the range (unless they are over 1 day old, in which case
2296 they are presumed missing their stop record and not counted). Also, sessions
2297 which end in the range but started earlier are counted from the start of the
2298 range to session end. Finally, sessions which start before the range but end
2299 after are counted for the entire range.
2301 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2302 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2307 #note: POD here, implementation in FS::cust_svc
2308 sub seconds_since_sqlradacct {
2310 $self->cust_svc->seconds_since_sqlradacct(@_);
2313 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2315 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2316 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2317 TIMESTAMP_END (exclusive).
2319 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2320 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2325 #note: POD here, implementation in FS::cust_svc
2326 sub attribute_since_sqlradacct {
2328 $self->cust_svc->attribute_since_sqlradacct(@_);
2331 =item get_session_history TIMESTAMP_START TIMESTAMP_END
2333 Returns an array of hash references of this customers login history for the
2334 given time range. (document this better)
2338 sub get_session_history {
2340 $self->cust_svc->get_session_history(@_);
2343 =item last_login_text
2345 Returns text describing the time of last login.
2349 sub last_login_text {
2351 $self->last_login ? ctime($self->last_login) : 'unknown';
2354 =item get_cdrs TIMESTAMP_START TIMESTAMP_END [ 'OPTION' => 'VALUE ... ]
2359 my($self, $start, $end, %opt ) = @_;
2361 my $did = $self->username; #yup
2363 my $prefix = $opt{'default_prefix'}; #convergent.au '+61'
2365 my $for_update = $opt{'for_update'} ? 'FOR UPDATE' : '';
2367 #SELECT $for_update * FROM cdr
2368 # WHERE calldate >= $start #need a conversion
2369 # AND calldate < $end #ditto
2370 # AND ( charged_party = "$did"
2371 # OR charged_party = "$prefix$did" #if length($prefix);
2372 # OR ( ( charged_party IS NULL OR charged_party = '' )
2374 # ( src = "$did" OR src = "$prefix$did" ) # if length($prefix)
2377 # AND ( freesidestatus IS NULL OR freesidestatus = '' )
2380 if ( length($prefix) ) {
2382 " AND ( charged_party = '$did'
2383 OR charged_party = '$prefix$did'
2384 OR ( ( charged_party IS NULL OR charged_party = '' )
2386 ( src = '$did' OR src = '$prefix$did' )
2392 " AND ( charged_party = '$did'
2393 OR ( ( charged_party IS NULL OR charged_party = '' )
2403 'select' => "$for_update *",
2406 #( freesidestatus IS NULL OR freesidestatus = '' )
2407 'freesidestatus' => '',
2409 'extra_sql' => $charged_or_src,
2417 Returns all RADIUS groups for this account (see L<FS::radius_usergroup>).
2423 if ( $self->usergroup ) {
2424 confess "explicitly specified usergroup not an arrayref: ". $self->usergroup
2425 unless ref($self->usergroup) eq 'ARRAY';
2426 #when provisioning records, export callback runs in svc_Common.pm before
2427 #radius_usergroup records can be inserted...
2428 @{$self->usergroup};
2430 map { $_->groupname }
2431 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } );
2435 =item clone_suspended
2437 Constructor used by FS::part_export::_export_suspend fallback. Document
2442 sub clone_suspended {
2444 my %hash = $self->hash;
2445 $hash{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
2446 new FS::svc_acct \%hash;
2449 =item clone_kludge_unsuspend
2451 Constructor used by FS::part_export::_export_unsuspend fallback. Document
2456 sub clone_kludge_unsuspend {
2458 my %hash = $self->hash;
2459 $hash{_password} = '';
2460 new FS::svc_acct \%hash;
2463 =item check_password
2465 Checks the supplied password against the (possibly encrypted) password in the
2466 database. Returns true for a successful authentication, false for no match.
2468 Currently supported encryptions are: classic DES crypt() and MD5
2472 sub check_password {
2473 my($self, $check_password) = @_;
2475 #remove old-style SUSPENDED kludge, they should be allowed to login to
2476 #self-service and pay up
2477 ( my $password = $self->_password ) =~ s/^\*SUSPENDED\* //;
2479 if ( $self->_password_encoding eq 'ldap' ) {
2481 my $auth = from_rfc2307 Authen::Passphrase $self->_password;
2482 return $auth->match($check_password);
2484 } elsif ( $self->_password_encoding eq 'crypt' ) {
2486 my $auth = from_crypt Authen::Passphrase $self->_password;
2487 return $auth->match($check_password);
2489 } elsif ( $self->_password_encoding eq 'plain' ) {
2491 return $check_password eq $password;
2495 #XXX this could be replaced with Authen::Passphrase stuff
2497 if ( $password =~ /^(\*|!!?)$/ ) { #no self-service login
2499 } elsif ( length($password) < 13 ) { #plaintext
2500 $check_password eq $password;
2501 } elsif ( length($password) == 13 ) { #traditional DES crypt
2502 crypt($check_password, $password) eq $password;
2503 } elsif ( $password =~ /^\$1\$/ ) { #MD5 crypt
2504 unix_md5_crypt($check_password, $password) eq $password;
2505 } elsif ( $password =~ /^\$2a?\$/ ) { #Blowfish
2506 warn "Can't check password: Blowfish encryption not yet supported, ".
2507 "svcnum ". $self->svcnum. "\n";
2510 warn "Can't check password: Unrecognized encryption for svcnum ".
2511 $self->svcnum. "\n";
2519 =item crypt_password [ DEFAULT_ENCRYPTION_TYPE ]
2521 Returns an encrypted password, either by passing through an encrypted password
2522 in the database or by encrypting a plaintext password from the database.
2524 The optional DEFAULT_ENCRYPTION_TYPE parameter can be set to I<crypt> (classic
2525 UNIX DES crypt), I<md5> (md5 crypt supported by most modern Linux and BSD
2526 distrubtions), or (eventually) I<blowfish> (blowfish hashing supported by
2527 OpenBSD, SuSE, other Linux distibutions with pam_unix2, etc.). The default
2528 encryption type is only used if the password is not already encrypted in the
2533 sub crypt_password {
2536 if ( $self->_password_encoding eq 'ldap' ) {
2538 if ( $self->_password =~ /^\{(PLAIN|CLEARTEXT)\}(.+)$/ ) {
2541 #XXX this could be replaced with Authen::Passphrase stuff
2543 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2544 if ( $encryption eq 'crypt' ) {
2547 $saltset[int(rand(64))].$saltset[int(rand(64))]
2549 } elsif ( $encryption eq 'md5' ) {
2550 unix_md5_crypt( $self->_password );
2551 } elsif ( $encryption eq 'blowfish' ) {
2552 croak "unknown encryption method $encryption";
2554 croak "unknown encryption method $encryption";
2557 } elsif ( $self->_password =~ /^\{CRYPT\}(.+)$/ ) {
2561 } elsif ( $self->_password_encoding eq 'crypt' ) {
2563 return $self->_password;
2565 } elsif ( $self->_password_encoding eq 'plain' ) {
2567 #XXX this could be replaced with Authen::Passphrase stuff
2569 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2570 if ( $encryption eq 'crypt' ) {
2573 $saltset[int(rand(64))].$saltset[int(rand(64))]
2575 } elsif ( $encryption eq 'md5' ) {
2576 unix_md5_crypt( $self->_password );
2577 } elsif ( $encryption eq 'blowfish' ) {
2578 croak "unknown encryption method $encryption";
2580 croak "unknown encryption method $encryption";
2585 if ( length($self->_password) == 13
2586 || $self->_password =~ /^\$(1|2a?)\$/
2587 || $self->_password =~ /^(\*|NP|\*LK\*|!!?)$/
2593 #XXX this could be replaced with Authen::Passphrase stuff
2595 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2596 if ( $encryption eq 'crypt' ) {
2599 $saltset[int(rand(64))].$saltset[int(rand(64))]
2601 } elsif ( $encryption eq 'md5' ) {
2602 unix_md5_crypt( $self->_password );
2603 } elsif ( $encryption eq 'blowfish' ) {
2604 croak "unknown encryption method $encryption";
2606 croak "unknown encryption method $encryption";
2615 =item ldap_password [ DEFAULT_ENCRYPTION_TYPE ]
2617 Returns an encrypted password in "LDAP" format, with a curly-bracked prefix
2618 describing the format, for example, "{PLAIN}himom", "{CRYPT}94pAVyK/4oIBk" or
2619 "{MD5}5426824942db4253f87a1009fd5d2d4".
2621 The optional DEFAULT_ENCRYPTION_TYPE is not yet used, but the idea is for it
2622 to work the same as the B</crypt_password> method.
2628 #eventually should check a "password-encoding" field
2630 if ( $self->_password_encoding eq 'ldap' ) {
2632 return $self->_password;
2634 } elsif ( $self->_password_encoding eq 'crypt' ) {
2636 if ( length($self->_password) == 13 ) { #crypt
2637 return '{CRYPT}'. $self->_password;
2638 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2640 #} elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2641 # die "Blowfish encryption not supported in this context, svcnum ".
2642 # $self->svcnum. "\n";
2644 warn "encryption method not (yet?) supported in LDAP context";
2645 return '{CRYPT}*'; #unsupported, should not auth
2648 } elsif ( $self->_password_encoding eq 'plain' ) {
2650 return '{PLAIN}'. $self->_password;
2652 #return '{CLEARTEXT}'. $self->_password; #?
2656 if ( length($self->_password) == 13 ) { #crypt
2657 return '{CRYPT}'. $self->_password;
2658 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2660 } elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2661 warn "Blowfish encryption not supported in this context, svcnum ".
2662 $self->svcnum. "\n";
2665 #are these two necessary anymore?
2666 } elsif ( $self->_password =~ /^(\w{48})$/ ) { #LDAP SSHA
2667 return '{SSHA}'. $1;
2668 } elsif ( $self->_password =~ /^(\w{64})$/ ) { #LDAP NS-MTA-MD5
2669 return '{NS-MTA-MD5}'. $1;
2672 return '{PLAIN}'. $self->_password;
2674 #return '{CLEARTEXT}'. $self->_password; #?
2676 #XXX this could be replaced with Authen::Passphrase stuff if it gets used
2677 #my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2678 #if ( $encryption eq 'crypt' ) {
2679 # return '{CRYPT}'. crypt(
2681 # $saltset[int(rand(64))].$saltset[int(rand(64))]
2683 #} elsif ( $encryption eq 'md5' ) {
2684 # unix_md5_crypt( $self->_password );
2685 #} elsif ( $encryption eq 'blowfish' ) {
2686 # croak "unknown encryption method $encryption";
2688 # croak "unknown encryption method $encryption";
2696 =item domain_slash_username
2698 Returns $domain/$username/
2702 sub domain_slash_username {
2704 $self->domain. '/'. $self->username. '/';
2707 =item virtual_maildir
2709 Returns $domain/maildirs/$username/
2713 sub virtual_maildir {
2715 $self->domain. '/maildirs/'. $self->username. '/';
2720 =head1 CLASS METHODS
2724 =item search HASHREF
2726 Class method which returns a qsearch hash expression to search for parameters
2727 specified in HASHREF. Valid parameters are
2741 Arrayref of pkgparts
2747 Arrayref of additional WHERE clauses, will be ANDed together.
2758 my ($class, $params) = @_;
2763 if ( $params->{'domain'} ) {
2764 my $svc_domain = qsearchs('svc_domain', { 'domain'=>$params->{'domain'} } );
2765 #preserve previous behavior & bubble up an error if $svc_domain not found?
2766 push @where, 'domsvc = '. $svc_domain->svcnum if $svc_domain;
2770 if ( $params->{'domsvc'} =~ /^(\d+)$/ ) {
2771 push @where, "domsvc = $1";
2775 push @where, 'pkgnum IS NULL' if $params->{'unlinked'};
2778 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2779 push @where, "agentnum = $1";
2783 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2784 push @where, "custnum = $1";
2788 if ( $params->{'pkgpart'} && scalar(@{ $params->{'pkgpart'} }) ) {
2789 #XXX untaint or sql quote
2791 'cust_pkg.pkgpart IN ('. join(',', @{ $params->{'pkgpart'} } ). ')';
2795 if ( $params->{'popnum'} =~ /^(\d+)$/ ) {
2796 push @where, "popnum = $1";
2800 if ( $params->{'svcpart'} =~ /^(\d+)$/ ) {
2801 push @where, "svcpart = $1";
2805 # here is the agent virtualization
2806 #if ($params->{CurrentUser}) {
2808 # qsearchs('access_user', { username => $params->{CurrentUser} });
2810 # if ($access_user) {
2811 # push @where, $access_user->agentnums_sql('table'=>'cust_main');
2813 # push @where, "1=0";
2816 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql(
2817 'table' => 'cust_main',
2818 'null_right' => 'View/link unlinked services',
2822 push @where, @{ $params->{'where'} } if $params->{'where'};
2824 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2826 my $addl_from = ' LEFT JOIN cust_svc USING ( svcnum ) '.
2827 ' LEFT JOIN part_svc USING ( svcpart ) '.
2828 ' LEFT JOIN cust_pkg USING ( pkgnum ) '.
2829 ' LEFT JOIN cust_main USING ( custnum ) ';
2831 my $count_query = "SELECT COUNT(*) FROM svc_acct $addl_from $extra_sql";
2832 #if ( keys %svc_acct ) {
2833 # $count_query .= ' WHERE '.
2834 # join(' AND ', map "$_ = ". dbh->quote($svc_acct{$_}),
2840 'table' => 'svc_acct',
2841 'hashref' => {}, # \%svc_acct,
2842 'select' => join(', ',
2845 'cust_main.custnum',
2846 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
2848 'addl_from' => $addl_from,
2849 'extra_sql' => $extra_sql,
2850 'order_by' => $params->{'order_by'},
2851 'count_query' => $count_query,
2864 This is the FS::svc_acct job-queue-able version. It still uses
2865 FS::Misc::send_email under-the-hood.
2872 eval "use FS::Misc qw(send_email)";
2875 $opt{mimetype} ||= 'text/plain';
2876 $opt{mimetype} .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2878 my $error = send_email(
2879 'from' => $opt{from},
2881 'subject' => $opt{subject},
2882 'content-type' => $opt{mimetype},
2883 'body' => [ map "$_\n", split("\n", $opt{body}) ],
2885 die $error if $error;
2888 =item check_and_rebuild_fuzzyfiles
2892 sub check_and_rebuild_fuzzyfiles {
2893 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2894 -e "$dir/svc_acct.username"
2895 or &rebuild_fuzzyfiles;
2898 =item rebuild_fuzzyfiles
2902 sub rebuild_fuzzyfiles {
2904 use Fcntl qw(:flock);
2906 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2910 open(USERNAMELOCK,">>$dir/svc_acct.username")
2911 or die "can't open $dir/svc_acct.username: $!";
2912 flock(USERNAMELOCK,LOCK_EX)
2913 or die "can't lock $dir/svc_acct.username: $!";
2915 my @all_username = map $_->getfield('username'), qsearch('svc_acct', {});
2917 open (USERNAMECACHE,">$dir/svc_acct.username.tmp")
2918 or die "can't open $dir/svc_acct.username.tmp: $!";
2919 print USERNAMECACHE join("\n", @all_username), "\n";
2920 close USERNAMECACHE or die "can't close $dir/svc_acct.username.tmp: $!";
2922 rename "$dir/svc_acct.username.tmp", "$dir/svc_acct.username";
2932 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2933 open(USERNAMECACHE,"<$dir/svc_acct.username")
2934 or die "can't open $dir/svc_acct.username: $!";
2935 my @array = map { chomp; $_; } <USERNAMECACHE>;
2936 close USERNAMECACHE;
2940 =item append_fuzzyfiles USERNAME
2944 sub append_fuzzyfiles {
2945 my $username = shift;
2947 &check_and_rebuild_fuzzyfiles;
2949 use Fcntl qw(:flock);
2951 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2953 open(USERNAME,">>$dir/svc_acct.username")
2954 or die "can't open $dir/svc_acct.username: $!";
2955 flock(USERNAME,LOCK_EX)
2956 or die "can't lock $dir/svc_acct.username: $!";
2958 print USERNAME "$username\n";
2960 flock(USERNAME,LOCK_UN)
2961 or die "can't unlock $dir/svc_acct.username: $!";
2969 =item radius_usergroup_selector GROUPS_ARRAYREF [ SELECTNAME ]
2973 sub radius_usergroup_selector {
2974 my $sel_groups = shift;
2975 my %sel_groups = map { $_=>1 } @$sel_groups;
2977 my $selectname = shift || 'radius_usergroup';
2980 my $sth = $dbh->prepare(
2981 'SELECT DISTINCT(groupname) FROM radius_usergroup ORDER BY groupname'
2982 ) or die $dbh->errstr;
2983 $sth->execute() or die $sth->errstr;
2984 my @all_groups = map { $_->[0] } @{$sth->fetchall_arrayref};
2988 function ${selectname}_doadd(object) {
2989 var myvalue = object.${selectname}_add.value;
2990 var optionName = new Option(myvalue,myvalue,false,true);
2991 var length = object.$selectname.length;
2992 object.$selectname.options[length] = optionName;
2993 object.${selectname}_add.value = "";
2996 <SELECT MULTIPLE NAME="$selectname">
2999 foreach my $group ( @all_groups ) {
3000 $html .= qq(<OPTION VALUE="$group");
3001 if ( $sel_groups{$group} ) {
3002 $html .= ' SELECTED';
3003 $sel_groups{$group} = 0;
3005 $html .= ">$group</OPTION>\n";
3007 foreach my $group ( grep { $sel_groups{$_} } keys %sel_groups ) {
3008 $html .= qq(<OPTION VALUE="$group" SELECTED>$group</OPTION>\n);
3010 $html .= '</SELECT>';
3012 $html .= qq!<BR><INPUT TYPE="text" NAME="${selectname}_add">!.
3013 qq!<INPUT TYPE="button" VALUE="Add new group" onClick="${selectname}_doadd(this.form)">!;
3018 =item reached_threshold
3020 Performs some activities when svc_acct thresholds (such as number of seconds
3021 remaining) are reached.
3025 sub reached_threshold {
3028 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } );
3029 die "Cannot find svc_acct with svcnum " . $opt{'svcnum'} unless $svc_acct;
3031 if ( $opt{'op'} eq '+' ){
3032 $svc_acct->setfield( $opt{'column'}.'_threshold',
3033 int($svc_acct->getfield($opt{'column'})
3034 * ( $conf->exists('svc_acct-usage_threshold')
3035 ? $conf->config('svc_acct-usage_threshold')/100
3040 my $error = $svc_acct->replace;
3041 die $error if $error;
3042 }elsif ( $opt{'op'} eq '-' ){
3044 my $threshold = $svc_acct->getfield( $opt{'column'}.'_threshold' );
3045 return '' if ($threshold eq '' );
3047 $svc_acct->setfield( $opt{'column'}.'_threshold', 0 );
3048 my $error = $svc_acct->replace;
3049 die $error if $error; # email next time, i guess
3051 if ( $warning_template ) {
3052 eval "use FS::Misc qw(send_email)";
3055 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3056 my $cust_main = $cust_pkg->cust_main;
3058 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ }
3059 $cust_main->invoicing_list,
3060 ($opt{'to'} ? $opt{'to'} : ())
3063 my $mimetype = $warning_mimetype;
3064 $mimetype .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
3066 my $body = $warning_template->fill_in( HASH => {
3067 'custnum' => $cust_main->custnum,
3068 'username' => $svc_acct->username,
3069 'password' => $svc_acct->_password,
3070 'first' => $cust_main->first,
3071 'last' => $cust_main->getfield('last'),
3072 'pkg' => $cust_pkg->part_pkg->pkg,
3073 'column' => $opt{'column'},
3074 'amount' => $opt{'column'} =~/bytes/
3075 ? FS::UI::bytecount::display_bytecount($svc_acct->getfield($opt{'column'}))
3076 : $svc_acct->getfield($opt{'column'}),
3077 'threshold' => $opt{'column'} =~/bytes/
3078 ? FS::UI::bytecount::display_bytecount($threshold)
3083 my $error = send_email(
3084 'from' => $warning_from,
3086 'subject' => $warning_subject,
3087 'content-type' => $mimetype,
3088 'body' => [ map "$_\n", split("\n", $body) ],
3090 die $error if $error;
3093 die "unknown op: " . $opt{'op'};
3101 The $recref stuff in sub check should be cleaned up.
3103 The suspend, unsuspend and cancel methods update the database, but not the
3104 current object. This is probably a bug as it's unexpected and
3107 radius_usergroup_selector? putting web ui components in here? they should
3108 probably live somewhere else...
3110 insertion of RADIUS group stuff in insert could be done with child_objects now
3111 (would probably clean up export of them too)
3113 _op_usage and set_usage bypass the history... maybe they shouldn't
3117 L<FS::svc_Common>, edit/part_svc.cgi from an installed web interface,
3118 export.html from the base documentation, L<FS::Record>, L<FS::Conf>,
3119 L<FS::cust_svc>, L<FS::part_svc>, L<FS::cust_pkg>, L<FS::queue>,
3120 L<freeside-queued>), L<FS::svc_acct_pop>,
3121 schema.html from the base documentation.
3125 =item domain_select_hash %OPTIONS
3127 Returns a hash SVCNUM => DOMAIN ... representing the domains this customer
3128 may at present purchase.
3130 Currently available options are: I<pkgnum> I<svcpart>
3134 sub domain_select_hash {
3135 my ($self, %options) = @_;
3141 $part_svc = $self->part_svc;
3142 $cust_pkg = $self->cust_svc->cust_pkg
3146 $part_svc = qsearchs('part_svc', { 'svcpart' => $options{svcpart} })
3147 if $options{'svcpart'};
3149 $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $options{pkgnum} })
3150 if $options{'pkgnum'};
3152 if ($part_svc && ( $part_svc->part_svc_column('domsvc')->columnflag eq 'S'
3153 || $part_svc->part_svc_column('domsvc')->columnflag eq 'F')) {
3154 %domains = map { $_->svcnum => $_->domain }
3155 map { qsearchs('svc_domain', { 'svcnum' => $_ }) }
3156 split(',', $part_svc->part_svc_column('domsvc')->columnvalue);
3157 }elsif ($cust_pkg && !$conf->exists('svc_acct-alldomains') ) {
3158 %domains = map { $_->svcnum => $_->domain }
3159 map { qsearchs('svc_domain', { 'svcnum' => $_->svcnum }) }
3160 map { qsearch('cust_svc', { 'pkgnum' => $_->pkgnum } ) }
3161 qsearch('cust_pkg', { 'custnum' => $cust_pkg->custnum });
3163 %domains = map { $_->svcnum => $_->domain } qsearch('svc_domain', {} );
3166 if ($part_svc && $part_svc->part_svc_column('domsvc')->columnflag eq 'D') {
3167 my $svc_domain = qsearchs('svc_domain',
3168 { 'svcnum' => $part_svc->part_svc_column('domsvc')->columnvalue } );
3169 if ( $svc_domain ) {
3170 $domains{$svc_domain->svcnum} = $svc_domain->domain;
3172 warn "unknown svc_domain.svcnum for part_svc_column domsvc: ".
3173 $part_svc->part_svc_column('domsvc')->columnvalue;