4 use base qw( FS::svc_Domain_Mixin FS::svc_CGP_Mixin FS::svc_CGPRule_Mixin
6 use vars qw( $DEBUG $me $conf $skip_fuzzyfiles
7 $dir_prefix @shells $usernamemin
8 $usernamemax $passwordmin $passwordmax
9 $username_ampersand $username_letter $username_letterfirst
10 $username_noperiod $username_nounderscore $username_nodash
11 $username_uppercase $username_percent $username_colon
12 $username_slash $username_equals $username_pound
13 $password_noampersand $password_noexclamation
14 $warning_template $warning_from $warning_subject $warning_mimetype
17 $radius_password $radius_ip
20 use Scalar::Util qw( blessed );
25 use Crypt::PasswdMD5 1.2;
26 use Digest::SHA1 'sha1_base64';
27 use Digest::MD5 'md5_base64';
30 use Authen::Passphrase;
31 use FS::UID qw( datasrc driver_name );
33 use FS::Record qw( qsearch qsearchs fields dbh dbdef );
34 use FS::Msgcat qw(gettext);
35 use FS::UI::bytecount;
40 use FS::cust_main_invoice;
45 use FS::radius_usergroup;
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 $username_slash = $conf->exists('username-slash');
79 $username_equals = $conf->exists('username-equals');
80 $username_pound = $conf->exists('username-pound');
81 $password_noampersand = $conf->exists('password-noexclamation');
82 $password_noexclamation = $conf->exists('password-noexclamation');
83 $dirhash = $conf->config('dirhash') || 0;
84 if ( $conf->exists('warning_email') ) {
85 $warning_template = new Text::Template (
87 SOURCE => [ map "$_\n", $conf->config('warning_email') ]
88 ) or warn "can't create warning email template: $Text::Template::ERROR";
89 $warning_from = $conf->config('warning_email-from'); # || 'your-isp-is-dum'
90 $warning_subject = $conf->config('warning_email-subject') || 'Warning';
91 $warning_mimetype = $conf->config('warning_email-mimetype') || 'text/plain';
92 $warning_cc = $conf->config('warning_email-cc');
94 $warning_template = '';
96 $warning_subject = '';
97 $warning_mimetype = '';
100 $smtpmachine = $conf->config('smtpmachine');
101 $radius_password = $conf->config('radius-password') || 'Password';
102 $radius_ip = $conf->config('radius-ip') || 'Framed-IP-Address';
103 @pw_set = ( 'A'..'Z' ) if $conf->exists('password-generated-allcaps');
107 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '.' , '/' );
108 @pw_set = ( 'a'..'z', 'A'..'Z', '0'..'9', '(', ')', '#', '.', ',' );
112 my ( $hashref, $cache ) = @_;
113 if ( $hashref->{'svc_acct_svcnum'} ) {
114 $self->{'_domsvc'} = FS::svc_domain->new( {
115 'svcnum' => $hashref->{'domsvc'},
116 'domain' => $hashref->{'svc_acct_domain'},
117 'catchall' => $hashref->{'svc_acct_catchall'},
124 FS::svc_acct - Object methods for svc_acct records
130 $record = new FS::svc_acct \%hash;
131 $record = new FS::svc_acct { 'column' => 'value' };
133 $error = $record->insert;
135 $error = $new_record->replace($old_record);
137 $error = $record->delete;
139 $error = $record->check;
141 $error = $record->suspend;
143 $error = $record->unsuspend;
145 $error = $record->cancel;
147 %hash = $record->radius;
149 %hash = $record->radius_reply;
151 %hash = $record->radius_check;
153 $domain = $record->domain;
155 $svc_domain = $record->svc_domain;
157 $email = $record->email;
159 $seconds_since = $record->seconds_since($timestamp);
163 An FS::svc_acct object represents an account. FS::svc_acct inherits from
164 FS::svc_Common. The following fields are currently supported:
170 Primary key (assigned automatcially for new accounts)
178 =item _password_encoding
180 plain, crypt, ldap (or empty for autodetection)
188 Point of presence (see L<FS::svc_acct_pop>)
200 set automatically if blank (and uid is not)
220 svcnum from svc_domain
224 Optional svcnum from svc_pbx
226 =item radius_I<Radius_Attribute>
228 I<Radius-Attribute> (reply)
230 =item rc_I<Radius_Attribute>
232 I<Radius-Attribute> (check)
242 Creates a new account. To add the account to the database, see L<"insert">.
249 'longname_plural' => 'Access accounts and mailboxes',
250 'sorts' => [ 'username', 'uid', 'seconds', 'last_login' ],
251 'display_weight' => 10,
252 'cancel_weight' => 50,
254 'dir' => 'Home directory',
257 def_info => 'set to fixed and blank for no UIDs',
260 'slipip' => 'IP address',
261 # 'popnum' => qq!<A HREF="$p/browse/svc_acct_pop.cgi/">POP number</A>!,
263 label => 'Access number',
265 select_table => 'svc_acct_pop',
266 select_key => 'popnum',
267 select_label => 'city',
273 disable_default => 1,
277 'password_selfchange' => { label => 'Password modification',
280 'password_recover' => { label => 'Password recovery',
284 label => 'Quota', #Mail storage limit
286 disable_inventory => 1,
290 label => 'File storage limit',
292 disable_inventory => 1,
296 label => 'Number of files limit',
298 disable_inventory => 1,
302 label => 'File size limit',
304 disable_inventory => 1,
307 '_password' => 'Password',
310 def_info => 'when blank, defaults to UID',
315 def_info => 'set to blank for no shell tracking',
317 #select_list => [ $conf->config('shells') ],
318 select_list => [ $conf ? $conf->config('shells') : () ],
319 disable_inventory => 1,
322 'finger' => 'Real name', # (GECOS)',
326 select_table => 'svc_domain',
327 select_key => 'svcnum',
328 select_label => 'domain',
329 disable_inventory => 1,
331 'pbxsvc' => { label => 'PBX',
332 type => 'select-svc_pbx.html',
333 disable_inventory => 1,
334 disable_select => 1, #UI wonky, pry works otherwise
337 label => 'RADIUS groups',
338 type => 'radius_usergroup_selector',
339 disable_inventory => 1,
342 'seconds' => { label => 'Seconds',
343 label_sort => 'with Time Remaining',
345 disable_inventory => 1,
347 disable_part_svc_column => 1,
349 'upbytes' => { label => 'Upload',
351 disable_inventory => 1,
353 'format' => \&FS::UI::bytecount::display_bytecount,
354 'parse' => \&FS::UI::bytecount::parse_bytecount,
355 disable_part_svc_column => 1,
357 'downbytes' => { label => 'Download',
359 disable_inventory => 1,
361 'format' => \&FS::UI::bytecount::display_bytecount,
362 'parse' => \&FS::UI::bytecount::parse_bytecount,
363 disable_part_svc_column => 1,
365 'totalbytes'=> { label => 'Total up and download',
367 disable_inventory => 1,
369 'format' => \&FS::UI::bytecount::display_bytecount,
370 'parse' => \&FS::UI::bytecount::parse_bytecount,
371 disable_part_svc_column => 1,
373 'seconds_threshold' => { label => 'Seconds threshold',
375 disable_inventory => 1,
377 disable_part_svc_column => 1,
379 'upbytes_threshold' => { label => 'Upload threshold',
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 'downbytes_threshold' => { label => 'Download threshold',
389 disable_inventory => 1,
391 'format' => \&FS::UI::bytecount::display_bytecount,
392 'parse' => \&FS::UI::bytecount::parse_bytecount,
393 disable_part_svc_column => 1,
395 'totalbytes_threshold'=> { label => 'Total up and download threshold',
397 disable_inventory => 1,
399 'format' => \&FS::UI::bytecount::display_bytecount,
400 'parse' => \&FS::UI::bytecount::parse_bytecount,
401 disable_part_svc_column => 1,
404 label => 'Last login',
408 label => 'Last logout',
413 label => 'Communigate aliases',
415 disable_inventory => 1,
420 label => 'Communigate account type',
422 select_list => [qw( MultiMailbox TextMailbox MailDirMailbox AGrade BGrade CGrade )],
423 disable_inventory => 1,
426 'cgp_accessmodes' => {
427 label => 'Communigate enabled services',
428 type => 'communigate_pro-accessmodes',
429 disable_inventory => 1,
432 'cgp_rulesallowed' => {
433 label => 'Allowed mail rules',
435 select_list => [ '', 'No', 'Filter Only', 'All But Exec', 'Any' ],
436 disable_inventory => 1,
439 'cgp_rpopallowed' => { label => 'RPOP modifications',
442 'cgp_mailtoall' => { label => 'Accepts mail to "all"',
445 'cgp_addmailtrailer' => { label => 'Add trailer to sent mail',
448 'cgp_archiveafter' => {
449 label => 'Archive messages after',
452 -2 => 'default(730 days)',
459 1209600 => '2 weeks',
460 2592000 => '30 days',
461 7776000 => '90 days',
462 15552000 => '180 days',
463 31536000 => '365 days',
464 63072000 => '730 days',
466 disable_inventory => 1,
472 'cgp_deletemode' => {
473 label => 'Communigate message delete method',
475 select_list => [ 'Move To Trash', 'Immediately', 'Mark' ],
476 disable_inventory => 1,
479 'cgp_emptytrash' => {
480 label => 'Communigate on logout remove trash',
482 select_list => __PACKAGE__->cgp_emptytrash_values,
483 disable_inventory => 1,
487 label => 'Communigate language',
489 select_list => [ '', qw( English Arabic Chinese Dutch French German Hebrew Italian Japanese Portuguese Russian Slovak Spanish Thai ) ],
490 disable_inventory => 1,
494 label => 'Communigate time zone',
496 select_list => __PACKAGE__->cgp_timezone_values,
497 disable_inventory => 1,
501 label => 'Communigate layout',
503 select_list => [ '', '***', 'GoldFleece', 'Skin2' ],
504 disable_inventory => 1,
507 'cgp_prontoskinname' => {
508 label => 'Communigate Pronto style',
510 select_list => [ '', 'Pronto', 'Pronto-darkflame', 'Pronto-steel', 'Pronto-twilight', ],
511 disable_inventory => 1,
514 'cgp_sendmdnmode' => {
515 label => 'Communigate send read receipts',
517 select_list => [ '', 'Never', 'Manually', 'Automatically' ],
518 disable_inventory => 1,
529 sub table { 'svc_acct'; }
531 sub table_dupcheck_fields { ( 'username', 'domsvc' ); }
535 #false laziness with edit/svc_acct.cgi
537 my( $self, $groups ) = @_;
538 if ( ref($groups) eq 'ARRAY' ) {
540 } elsif ( length($groups) ) {
541 [ split(/\s*,\s*/, $groups) ];
550 shift->_lastlog('in', @_);
554 shift->_lastlog('out', @_);
558 my( $self, $op, $time ) = @_;
560 if ( defined($time) ) {
561 warn "$me last_log$op called on svcnum ". $self->svcnum.
562 ' ('. $self->email. "): $time\n"
567 my $sql = "UPDATE svc_acct SET last_log$op = ? WHERE svcnum = ?";
571 my $sth = $dbh->prepare( $sql )
572 or die "Error preparing $sql: ". $dbh->errstr;
573 my $rv = $sth->execute($time, $self->svcnum);
574 die "Error executing $sql: ". $sth->errstr
576 die "Can't update last_log$op for svcnum". $self->svcnum
579 $self->{'Hash'}->{"last_log$op"} = $time;
581 $self->getfield("last_log$op");
585 =item search_sql STRING
587 Class method which returns an SQL fragment to search for the given string.
592 my( $class, $string ) = @_;
593 if ( $string =~ /^([^@]+)@([^@]+)$/ ) {
594 my( $username, $domain ) = ( $1, $2 );
595 my $q_username = dbh->quote($username);
596 my @svc_domain = qsearch('svc_domain', { 'domain' => $domain } );
598 "svc_acct.username = $q_username AND ( ".
599 join( ' OR ', map { "svc_acct.domsvc = ". $_->svcnum; } @svc_domain ).
604 } elsif ( $string =~ /^(\d{1,3}\.){3}\d{1,3}$/ ) {
606 $class->search_sql_field('slipip', $string ).
608 $class->search_sql_field('username', $string ).
611 $class->search_sql_field('username', $string);
615 =item label [ END_TIMESTAMP [ START_TIMESTAMP ] ]
617 Returns the "username@domain" string for this account.
619 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
629 =item label_long [ END_TIMESTAMP [ START_TIMESTAMP ] ]
631 Returns a longer string label for this acccount ("Real Name <username@domain>"
632 if available, or "username@domain").
634 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
641 my $label = $self->label(@_);
642 my $finger = $self->finger;
643 return $label unless $finger =~ /\S/;
644 my $maxlen = 40 - length($label) - length($self->cust_svc->part_svc->svc);
645 $finger = substr($finger, 0, $maxlen-3).'...' if length($finger) > $maxlen;
649 =item insert [ , OPTION => VALUE ... ]
651 Adds this account to the database. If there is an error, returns the error,
652 otherwise returns false.
654 The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be
655 defined. An FS::cust_svc record will be created and inserted.
657 The additional field I<usergroup> can optionally be defined; if so it should
658 contain an arrayref of group names. See L<FS::radius_usergroup>.
660 The additional field I<child_objects> can optionally be defined; if so it
661 should contain an arrayref of FS::tablename objects. They will have their
662 svcnum fields set and will be inserted after this record, but before any
663 exports are run. Each element of the array can also optionally be a
664 two-element array reference containing the child object and the name of an
665 alternate field to be filled in with the newly-inserted svcnum, for example
666 C<[ $svc_forward, 'srcsvc' ]>
668 Currently available options are: I<depend_jobnum>
670 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
671 jobnums), all provisioning jobs will have a dependancy on the supplied
672 jobnum(s) (they will not run until the specific job(s) complete(s)).
674 (TODOC: L<FS::queue> and L<freeside-queued>)
676 (TODOC: new exports!)
685 warn "[$me] insert called on $self: ". Dumper($self).
686 "\nwith options: ". Dumper(%options);
689 local $SIG{HUP} = 'IGNORE';
690 local $SIG{INT} = 'IGNORE';
691 local $SIG{QUIT} = 'IGNORE';
692 local $SIG{TERM} = 'IGNORE';
693 local $SIG{TSTP} = 'IGNORE';
694 local $SIG{PIPE} = 'IGNORE';
696 my $oldAutoCommit = $FS::UID::AutoCommit;
697 local $FS::UID::AutoCommit = 0;
701 my $error = $self->SUPER::insert(
702 'jobnums' => \@jobnums,
703 'child_objects' => $self->child_objects,
707 $dbh->rollback if $oldAutoCommit;
711 if ( $self->usergroup ) {
712 foreach my $groupname ( @{$self->usergroup} ) {
713 my $radius_usergroup = new FS::radius_usergroup ( {
714 svcnum => $self->svcnum,
715 groupname => $groupname,
717 my $error = $radius_usergroup->insert;
719 $dbh->rollback if $oldAutoCommit;
725 unless ( $skip_fuzzyfiles ) {
726 $error = $self->queue_fuzzyfiles_update;
728 $dbh->rollback if $oldAutoCommit;
729 return "updating fuzzy search cache: $error";
733 my $cust_pkg = $self->cust_svc->cust_pkg;
736 my $cust_main = $cust_pkg->cust_main;
737 my $agentnum = $cust_main->agentnum;
739 if ( $conf->exists('emailinvoiceautoalways')
740 || $conf->exists('emailinvoiceauto')
741 && ! $cust_main->invoicing_list_emailonly
743 my @invoicing_list = $cust_main->invoicing_list;
744 push @invoicing_list, $self->email;
745 $cust_main->invoicing_list(\@invoicing_list);
749 my @welcome_exclude_svcparts = $conf->config('svc_acct_welcome_exclude');
750 unless ( grep { $_ eq $self->svcpart } @welcome_exclude_svcparts ) {
752 my $msgnum = $conf->config('welcome_msgnum', $agentnum);
754 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
755 $error = $msg_template->send('cust_main' => $cust_main,
759 my ($to,$welcome_template,$welcome_from,$welcome_subject,$welcome_subject_template,$welcome_mimetype)
760 = ('','','','','','');
762 if ( $conf->exists('welcome_email', $agentnum) ) {
763 $welcome_template = new Text::Template (
765 SOURCE => [ map "$_\n", $conf->config('welcome_email', $agentnum) ]
766 ) or warn "can't create welcome email template: $Text::Template::ERROR";
767 $welcome_from = $conf->config('welcome_email-from', $agentnum);
768 # || 'your-isp-is-dum'
769 $welcome_subject = $conf->config('welcome_email-subject', $agentnum)
771 $welcome_subject_template = new Text::Template (
773 SOURCE => $welcome_subject,
774 ) or warn "can't create welcome email subject template: $Text::Template::ERROR";
775 $welcome_mimetype = $conf->config('welcome_email-mimetype', $agentnum)
778 if ( $welcome_template ) {
779 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
783 'custnum' => $self->custnum,
784 'username' => $self->username,
785 'password' => $self->_password,
786 'first' => $cust_main->first,
787 'last' => $cust_main->getfield('last'),
788 'pkg' => $cust_pkg->part_pkg->pkg,
790 my $wqueue = new FS::queue {
791 'svcnum' => $self->svcnum,
792 'job' => 'FS::svc_acct::send_email'
794 my $error = $wqueue->insert(
796 'from' => $welcome_from,
797 'subject' => $welcome_subject_template->fill_in( HASH => \%hash, ),
798 'mimetype' => $welcome_mimetype,
799 'body' => $welcome_template->fill_in( HASH => \%hash, ),
802 $dbh->rollback if $oldAutoCommit;
803 return "error queuing welcome email: $error";
806 if ( $options{'depend_jobnum'} ) {
807 warn "$me depend_jobnum found; adding to welcome email dependancies"
809 if ( ref($options{'depend_jobnum'}) ) {
810 warn "$me adding jobs ". join(', ', @{$options{'depend_jobnum'}} ).
811 "to welcome email dependancies"
813 push @jobnums, @{ $options{'depend_jobnum'} };
815 warn "$me adding job $options{'depend_jobnum'} ".
816 "to welcome email dependancies"
818 push @jobnums, $options{'depend_jobnum'};
822 foreach my $jobnum ( @jobnums ) {
823 my $error = $wqueue->depend_insert($jobnum);
825 $dbh->rollback if $oldAutoCommit;
826 return "error queuing welcome email job dependancy: $error";
832 } # if $welcome_template
837 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
841 # set usage fields and thresholds if unset but set in a package def
842 # AND the package already has a last bill date (otherwise they get double added)
843 sub preinsert_hook_first {
846 return '' unless $self->pkgnum;
848 my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
849 return '' unless $cust_pkg && $cust_pkg->last_bill;
851 my $part_pkg = $cust_pkg->part_pkg;
852 return '' unless $part_pkg && $part_pkg->can('usage_valuehash');
854 my %values = $part_pkg->usage_valuehash;
855 my $multiplier = $conf->exists('svc_acct-usage_threshold')
856 ? 1 - $conf->config('svc_acct-usage_threshold')/100
857 : 0.20; #doesn't matter
859 foreach ( keys %values ) {
860 next if $self->getfield($_);
861 $self->setfield( $_, $values{$_} );
862 $self->setfield( $_. '_threshold', int( $values{$_} * $multiplier ) )
863 if $conf->exists('svc_acct-usage_threshold');
871 Deletes this account from the database. If there is an error, returns the
872 error, otherwise returns false.
874 The corresponding FS::cust_svc record will be deleted as well.
876 (TODOC: new exports!)
883 return "can't delete system account" if $self->_check_system;
885 return "Can't delete an account which is a (svc_forward) source!"
886 if qsearch( 'svc_forward', { 'srcsvc' => $self->svcnum } );
888 return "Can't delete an account which is a (svc_forward) destination!"
889 if qsearch( 'svc_forward', { 'dstsvc' => $self->svcnum } );
891 return "Can't delete an account with (svc_www) web service!"
892 if qsearch( 'svc_www', { 'usersvc' => $self->svcnum } );
894 # what about records in session ? (they should refer to history table)
896 local $SIG{HUP} = 'IGNORE';
897 local $SIG{INT} = 'IGNORE';
898 local $SIG{QUIT} = 'IGNORE';
899 local $SIG{TERM} = 'IGNORE';
900 local $SIG{TSTP} = 'IGNORE';
901 local $SIG{PIPE} = 'IGNORE';
903 my $oldAutoCommit = $FS::UID::AutoCommit;
904 local $FS::UID::AutoCommit = 0;
907 foreach my $cust_main_invoice (
908 qsearch( 'cust_main_invoice', { 'dest' => $self->svcnum } )
910 unless ( defined($cust_main_invoice) ) {
911 warn "WARNING: something's wrong with qsearch";
914 my %hash = $cust_main_invoice->hash;
915 $hash{'dest'} = $self->email;
916 my $new = new FS::cust_main_invoice \%hash;
917 my $error = $new->replace($cust_main_invoice);
919 $dbh->rollback if $oldAutoCommit;
924 foreach my $svc_domain (
925 qsearch( 'svc_domain', { 'catchall' => $self->svcnum } )
927 my %hash = new FS::svc_domain->hash;
928 $hash{'catchall'} = '';
929 my $new = new FS::svc_domain \%hash;
930 my $error = $new->replace($svc_domain);
932 $dbh->rollback if $oldAutoCommit;
937 my $error = $self->SUPER::delete;
939 $dbh->rollback if $oldAutoCommit;
943 foreach my $radius_usergroup (
944 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } )
946 my $error = $radius_usergroup->delete;
948 $dbh->rollback if $oldAutoCommit;
953 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
957 =item replace OLD_RECORD
959 Replaces OLD_RECORD with this one in the database. If there is an error,
960 returns the error, otherwise returns false.
962 The additional field I<usergroup> can optionally be defined; if so it should
963 contain an arrayref of group names. See L<FS::radius_usergroup>.
971 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
975 warn "$me replacing $old with $new\n" if $DEBUG;
979 return "can't modify system account" if $old->_check_system;
982 #no warnings 'numeric'; #alas, a 5.006-ism
985 foreach my $xid (qw( uid gid )) {
987 return "Can't change $xid!"
988 if ! $conf->exists("svc_acct-edit_$xid")
989 && $old->$xid() != $new->$xid()
990 && $new->cust_svc->part_svc->part_svc_column($xid)->columnflag ne 'F'
995 #change homdir when we change username
996 $new->setfield('dir', '') if $old->username ne $new->username;
998 local $SIG{HUP} = 'IGNORE';
999 local $SIG{INT} = 'IGNORE';
1000 local $SIG{QUIT} = 'IGNORE';
1001 local $SIG{TERM} = 'IGNORE';
1002 local $SIG{TSTP} = 'IGNORE';
1003 local $SIG{PIPE} = 'IGNORE';
1005 my $oldAutoCommit = $FS::UID::AutoCommit;
1006 local $FS::UID::AutoCommit = 0;
1009 # redundant, but so $new->usergroup gets set
1010 $error = $new->check;
1011 return $error if $error;
1013 $old->usergroup( [ $old->radius_groups ] );
1015 warn $old->email. " old groups: ". join(' ',@{$old->usergroup}). "\n";
1016 warn $new->email. "new groups: ". join(' ',@{$new->usergroup}). "\n";
1018 if ( $new->usergroup ) {
1019 #(sorta) false laziness with FS::part_export::sqlradius::_export_replace
1020 my @newgroups = @{$new->usergroup};
1021 foreach my $oldgroup ( @{$old->usergroup} ) {
1022 if ( grep { $oldgroup eq $_ } @newgroups ) {
1023 @newgroups = grep { $oldgroup ne $_ } @newgroups;
1026 my $radius_usergroup = qsearchs('radius_usergroup', {
1027 svcnum => $old->svcnum,
1028 groupname => $oldgroup,
1030 my $error = $radius_usergroup->delete;
1032 $dbh->rollback if $oldAutoCommit;
1033 return "error deleting radius_usergroup $oldgroup: $error";
1037 foreach my $newgroup ( @newgroups ) {
1038 my $radius_usergroup = new FS::radius_usergroup ( {
1039 svcnum => $new->svcnum,
1040 groupname => $newgroup,
1042 my $error = $radius_usergroup->insert;
1044 $dbh->rollback if $oldAutoCommit;
1045 return "error adding radius_usergroup $newgroup: $error";
1051 $error = $new->SUPER::replace($old, @_);
1053 $dbh->rollback if $oldAutoCommit;
1054 return $error if $error;
1057 if ( $new->username ne $old->username && ! $skip_fuzzyfiles ) {
1058 $error = $new->queue_fuzzyfiles_update;
1060 $dbh->rollback if $oldAutoCommit;
1061 return "updating fuzzy search cache: $error";
1065 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1069 =item queue_fuzzyfiles_update
1071 Used by insert & replace to update the fuzzy search cache
1075 sub queue_fuzzyfiles_update {
1078 local $SIG{HUP} = 'IGNORE';
1079 local $SIG{INT} = 'IGNORE';
1080 local $SIG{QUIT} = 'IGNORE';
1081 local $SIG{TERM} = 'IGNORE';
1082 local $SIG{TSTP} = 'IGNORE';
1083 local $SIG{PIPE} = 'IGNORE';
1085 my $oldAutoCommit = $FS::UID::AutoCommit;
1086 local $FS::UID::AutoCommit = 0;
1089 my $queue = new FS::queue {
1090 'svcnum' => $self->svcnum,
1091 'job' => 'FS::svc_acct::append_fuzzyfiles'
1093 my $error = $queue->insert($self->username);
1095 $dbh->rollback if $oldAutoCommit;
1096 return "queueing job (transaction rolled back): $error";
1099 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1107 Suspends this account by calling export-specific suspend hooks. If there is
1108 an error, returns the error, otherwise returns false.
1110 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1116 return "can't suspend system account" if $self->_check_system;
1117 $self->SUPER::suspend(@_);
1122 Unsuspends this account by by calling export-specific suspend hooks. If there
1123 is an error, returns the error, otherwise returns false.
1125 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1131 my %hash = $self->hash;
1132 if ( $hash{_password} =~ /^\*SUSPENDED\* (.*)$/ ) {
1133 $hash{_password} = $1;
1134 my $new = new FS::svc_acct ( \%hash );
1135 my $error = $new->replace($self);
1136 return $error if $error;
1139 $self->SUPER::unsuspend(@_);
1144 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
1146 If the B<auto_unset_catchall> configuration option is set, this method will
1147 automatically remove any references to the canceled service in the catchall
1148 field of svc_domain. This allows packages that contain both a svc_domain and
1149 its catchall svc_acct to be canceled in one step.
1154 # Only one thing to do at this level
1156 foreach my $svc_domain (
1157 qsearch( 'svc_domain', { catchall => $self->svcnum } ) ) {
1158 if($conf->exists('auto_unset_catchall')) {
1159 my %hash = $svc_domain->hash;
1160 $hash{catchall} = '';
1161 my $new = new FS::svc_domain ( \%hash );
1162 my $error = $new->replace($svc_domain);
1163 return $error if $error;
1165 return "cannot unprovision svc_acct #".$self->svcnum.
1166 " while assigned as catchall for svc_domain #".$svc_domain->svcnum;
1170 $self->SUPER::cancel(@_);
1176 Checks all fields to make sure this is a valid service. If there is an error,
1177 returns the error, otherwise returns false. Called by the insert and replace
1180 Sets any fixed values; see L<FS::part_svc>.
1187 my($recref) = $self->hashref;
1189 my $x = $self->setfixed( $self->_fieldhandlers );
1190 return $x unless ref($x);
1193 if ( $part_svc->part_svc_column('usergroup')->columnflag eq "F" ) {
1195 [ split(',', $part_svc->part_svc_column('usergroup')->columnvalue) ] );
1198 my $error = $self->ut_numbern('svcnum')
1199 #|| $self->ut_number('domsvc')
1200 || $self->ut_foreign_key( 'domsvc', 'svc_domain', 'svcnum' )
1201 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
1202 || $self->ut_textn('sec_phrase')
1203 || $self->ut_snumbern('seconds')
1204 || $self->ut_snumbern('upbytes')
1205 || $self->ut_snumbern('downbytes')
1206 || $self->ut_snumbern('totalbytes')
1207 || $self->ut_snumbern('seconds_threshold')
1208 || $self->ut_snumbern('upbytes_threshold')
1209 || $self->ut_snumbern('downbytes_threshold')
1210 || $self->ut_snumbern('totalbytes_threshold')
1211 || $self->ut_enum('_password_encoding', ['',qw(plain crypt ldap)])
1212 || $self->ut_enum('password_selfchange', [ '', 'Y' ])
1213 || $self->ut_enum('password_recover', [ '', 'Y' ])
1215 || $self->ut_anything('cf_privatekey')
1217 || $self->ut_textn('cgp_accessmodes')
1218 || $self->ut_alphan('cgp_type')
1219 || $self->ut_textn('cgp_aliases' ) #well
1221 || $self->ut_alphasn('cgp_rulesallowed')
1222 || $self->ut_enum('cgp_rpopallowed', [ '', 'Y' ])
1223 || $self->ut_enum('cgp_mailtoall', [ '', 'Y' ])
1224 || $self->ut_enum('cgp_addmailtrailer', [ '', 'Y' ])
1225 || $self->ut_snumbern('cgp_archiveafter')
1227 || $self->ut_alphasn('cgp_deletemode')
1228 || $self->ut_enum('cgp_emptytrash', $self->cgp_emptytrash_values)
1229 || $self->ut_alphan('cgp_language')
1230 || $self->ut_textn('cgp_timezone')
1231 || $self->ut_textn('cgp_skinname')
1232 || $self->ut_textn('cgp_prontoskinname')
1233 || $self->ut_alphan('cgp_sendmdnmode')
1235 return $error if $error;
1238 local $username_letter = $username_letter;
1239 if ($self->svcnum) {
1240 my $cust_svc = $self->cust_svc
1241 or return "no cust_svc record found for svcnum ". $self->svcnum;
1242 my $cust_pkg = $cust_svc->cust_pkg;
1244 if ($self->pkgnum) {
1245 $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $self->pkgnum } );#complain?
1249 $conf->exists('username-letter', $cust_pkg->cust_main->agentnum);
1252 my $ulen = $usernamemax || $self->dbdef_table->column('username')->length;
1254 $recref->{username} =~ /^([a-z0-9_\-\.\&\%\:\/\=\#]{$usernamemin,$ulen})$/i
1255 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
1256 $recref->{username} = $1;
1258 unless ( $username_uppercase ) {
1259 $recref->{username} =~ /[A-Z]/ and return gettext('illegal_username');
1261 if ( $username_letterfirst ) {
1262 $recref->{username} =~ /^[a-z]/ or return gettext('illegal_username');
1263 } elsif ( $username_letter ) {
1264 $recref->{username} =~ /[a-z]/ or return gettext('illegal_username');
1266 if ( $username_noperiod ) {
1267 $recref->{username} =~ /\./ and return gettext('illegal_username');
1269 if ( $username_nounderscore ) {
1270 $recref->{username} =~ /_/ and return gettext('illegal_username');
1272 if ( $username_nodash ) {
1273 $recref->{username} =~ /\-/ and return gettext('illegal_username');
1275 unless ( $username_ampersand ) {
1276 $recref->{username} =~ /\&/ and return gettext('illegal_username');
1278 unless ( $username_percent ) {
1279 $recref->{username} =~ /\%/ and return gettext('illegal_username');
1281 unless ( $username_colon ) {
1282 $recref->{username} =~ /\:/ and return gettext('illegal_username');
1284 unless ( $username_slash ) {
1285 $recref->{username} =~ /\// and return gettext('illegal_username');
1287 unless ( $username_equals ) {
1288 $recref->{username} =~ /\=/ and return gettext('illegal_username');
1290 unless ( $username_pound ) {
1291 $recref->{username} =~ /\#/ and return gettext('illegal_username');
1295 $recref->{popnum} =~ /^(\d*)$/ or return "Illegal popnum: ".$recref->{popnum};
1296 $recref->{popnum} = $1;
1297 return "Unknown popnum" unless
1298 ! $recref->{popnum} ||
1299 qsearchs('svc_acct_pop',{'popnum'=> $recref->{popnum} } );
1301 unless ( $part_svc->part_svc_column('uid')->columnflag eq 'F' ) {
1303 $recref->{uid} =~ /^(\d*)$/ or return "Illegal uid";
1304 $recref->{uid} = $1 eq '' ? $self->unique('uid') : $1;
1306 $recref->{gid} =~ /^(\d*)$/ or return "Illegal gid";
1307 $recref->{gid} = $1 eq '' ? $recref->{uid} : $1;
1308 #not all systems use gid=uid
1309 #you can set a fixed gid in part_svc
1311 return "Only root can have uid 0"
1312 if $recref->{uid} == 0
1313 && $recref->{username} !~ /^(root|toor|smtp)$/;
1315 unless ( $recref->{username} eq 'sync' ) {
1316 if ( grep $_ eq $recref->{shell}, @shells ) {
1317 $recref->{shell} = (grep $_ eq $recref->{shell}, @shells)[0];
1319 return "Illegal shell \`". $self->shell. "\'; ".
1320 "shells configuration value contains: @shells";
1323 $recref->{shell} = '/bin/sync';
1327 $recref->{gid} ne '' ?
1328 return "Can't have gid without uid" : ( $recref->{gid}='' );
1329 #$recref->{dir} ne '' ?
1330 # return "Can't have directory without uid" : ( $recref->{dir}='' );
1331 $recref->{shell} ne '' ?
1332 return "Can't have shell without uid" : ( $recref->{shell}='' );
1335 unless ( $part_svc->part_svc_column('dir')->columnflag eq 'F' ) {
1337 $recref->{dir} =~ /^([\/\w\-\.\&\:\#]*)$/
1338 or return "Illegal directory: ". $recref->{dir};
1339 $recref->{dir} = $1;
1340 return "Illegal directory"
1341 if $recref->{dir} =~ /(^|\/)\.+(\/|$)/; #no .. component
1342 return "Illegal directory"
1343 if $recref->{dir} =~ /\&/ && ! $username_ampersand;
1344 unless ( $recref->{dir} ) {
1345 $recref->{dir} = $dir_prefix . '/';
1346 if ( $dirhash > 0 ) {
1347 for my $h ( 1 .. $dirhash ) {
1348 $recref->{dir} .= substr($recref->{username}, $h-1, 1). '/';
1350 } elsif ( $dirhash < 0 ) {
1351 for my $h ( reverse $dirhash .. -1 ) {
1352 $recref->{dir} .= substr($recref->{username}, $h, 1). '/';
1355 $recref->{dir} .= $recref->{username};
1361 # $error = $self->ut_textn('finger');
1362 # return $error if $error;
1363 if ( $self->getfield('finger') eq '' ) {
1364 my $cust_pkg = $self->svcnum
1365 ? $self->cust_svc->cust_pkg
1366 : qsearchs('cust_pkg', { 'pkgnum' => $self->getfield('pkgnum') } );
1368 my $cust_main = $cust_pkg->cust_main;
1369 $self->setfield('finger', $cust_main->first.' '.$cust_main->get('last') );
1372 $self->getfield('finger') =~
1373 /^([µ_0123456789aAáÁàÀâÂåÅäÄãêæÆbBcCçÇdDðÐeEéÉèÈêÊëËfFgGhHiIíÍìÌîÎïÏjJkKlLmMnNñÑoOóÓòÒôÔöÖõÕøغpPqQrRsSßtTuUúÚùÙûÛüÜvVwWxXyYýÝÿzZþÞ \t\!\@\#\$\%\&\(\)\-\+\;\'\"\,\.\?\/\*\<\>]*)$/
1374 or return "Illegal finger: ". $self->getfield('finger');
1375 $self->setfield('finger', $1);
1377 for (qw( quota file_quota file_maxsize )) {
1378 $recref->{$_} =~ /^(\w*)$/ or return "Illegal $_";
1381 $recref->{file_maxnum} =~ /^\s*(\d*)\s*$/ or return "Illegal file_maxnum";
1382 $recref->{file_maxnum} = $1;
1384 unless ( $part_svc->part_svc_column('slipip')->columnflag eq 'F' ) {
1385 if ( $recref->{slipip} eq '' ) {
1386 $recref->{slipip} = '';
1387 } elsif ( $recref->{slipip} eq '0e0' ) {
1388 $recref->{slipip} = '0e0';
1390 $recref->{slipip} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/
1391 or return "Illegal slipip: ". $self->slipip;
1392 $recref->{slipip} = $1;
1397 #arbitrary RADIUS stuff; allow ut_textn for now
1398 foreach ( grep /^radius_/, fields('svc_acct') ) {
1399 $self->ut_textn($_);
1402 # First, if _password is blank, generate one and set default encoding.
1403 if ( ! $recref->{_password} ) {
1404 $error = $self->set_password('');
1406 # But if there's a _password but no encoding, assume it's plaintext and
1407 # set it to default encoding.
1408 elsif ( ! $recref->{_password_encoding} ) {
1409 $error = $self->set_password($recref->{_password});
1411 return $error if $error;
1413 # Next, check _password to ensure compliance with the encoding.
1414 if ( $recref->{_password_encoding} eq 'ldap' ) {
1416 if ( $recref->{_password} =~ /^(\{[\w\-]+\})(!?.{0,64})$/ ) {
1417 $recref->{_password} = uc($1).$2;
1419 return 'Illegal (ldap-encoded) password: '. $recref->{_password};
1422 } elsif ( $recref->{_password_encoding} eq 'crypt' ) {
1424 if ( $recref->{_password} =~
1425 #/^(\$\w+\$.*|[\w\+\/]{13}|_[\w\+\/]{19}|\*)$/
1426 /^(!!?)?(\$\w+\$.*|[\w\+\/\.]{13}|_[\w\+\/\.]{19}|\*)$/
1429 $recref->{_password} = ( defined($1) ? $1 : '' ). $2;
1432 return 'Illegal (crypt-encoded) password: '. $recref->{_password};
1435 } elsif ( $recref->{_password_encoding} eq 'plain' ) {
1436 # Password randomization is now in set_password.
1437 # Strip whitespace characters, check length requirements, etc.
1438 if ( $recref->{_password} =~ /^([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1439 $recref->{_password} = $1;
1441 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1442 FS::Msgcat::_gettext('illegal_password_characters').
1443 ": ". $recref->{_password};
1446 if ( $password_noampersand ) {
1447 $recref->{_password} =~ /\&/ and return gettext('illegal_password');
1449 if ( $password_noexclamation ) {
1450 $recref->{_password} =~ /\!/ and return gettext('illegal_password');
1454 return "invalid password encoding ('".$recref->{_password_encoding}."'";
1456 $self->SUPER::check;
1461 sub _password_encryption {
1463 my $encoding = lc($self->_password_encoding);
1464 return if !$encoding;
1465 return 'plain' if $encoding eq 'plain';
1466 if($encoding eq 'crypt') {
1467 my $pass = $self->_password;
1468 $pass =~ s/^\*SUSPENDED\* //;
1470 return 'md5' if $pass =~ /^\$1\$/;
1471 #return 'blowfish' if $self->_password =~ /^\$2\$/;
1472 return 'des' if length($pass) == 13;
1475 if($encoding eq 'ldap') {
1476 uc($self->_password) =~ /^\{([\w-]+)\}/;
1477 return 'crypt' if $1 eq 'CRYPT' or $1 eq 'DES';
1478 return 'plain' if $1 eq 'PLAIN' or $1 eq 'CLEARTEXT';
1479 return 'md5' if $1 eq 'MD5';
1480 return 'sha1' if $1 eq 'SHA' or $1 eq 'SHA-1';
1487 sub get_cleartext_password {
1489 if($self->_password_encryption eq 'plain') {
1490 if($self->_password_encoding eq 'ldap') {
1491 $self->_password =~ /\{\w+\}(.*)$/;
1495 return $self->_password;
1504 Set the cleartext password for the account. If _password_encoding is set, the
1505 new password will be encoded according to the existing method (including
1506 encryption mode, if it can be determined). Otherwise,
1507 config('default-password-encoding') is used.
1509 If no password is supplied (or a zero-length password when minimum password length
1510 is >0), one will be generated randomly.
1515 my( $self, $pass ) = ( shift, shift );
1517 warn "[$me] set_password (to $pass) called on $self: ". Dumper($self)
1520 my $failure = gettext('illegal_password'). " $passwordmin-$passwordmax ".
1521 FS::Msgcat::_gettext('illegal_password_characters').
1524 my( $encoding, $encryption ) = ('', '');
1526 if ( $self->_password_encoding ) {
1527 $encoding = $self->_password_encoding;
1528 # identify existing encryption method, try to use it.
1529 $encryption = $self->_password_encryption;
1531 # use the system default
1537 # set encoding to system default
1538 ($encoding, $encryption) =
1539 split(/-/, lc($conf->config('default-password-encoding')));
1540 $encoding ||= 'legacy';
1541 $self->_password_encoding($encoding);
1544 if ( $encoding eq 'legacy' ) {
1546 # The legacy behavior from check():
1547 # If the password is blank, randomize it and set encoding to 'plain'.
1548 if(!defined($pass) or (length($pass) == 0 and $passwordmin)) {
1549 $pass = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1550 $self->_password_encoding('plain');
1552 # Prefix + valid-length password
1553 if ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1555 $self->_password_encoding('plain');
1556 # Prefix + crypt string
1557 } elsif ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([\w\.\/\$\;\+]{13,64})$/ ) {
1559 $self->_password_encoding('crypt');
1560 # Various disabled crypt passwords
1561 } elsif ( $pass eq '*' || $pass eq '!' || $pass eq '!!' ) {
1562 $self->_password_encoding('crypt');
1568 $self->_password($pass);
1574 if $passwordmin && length($pass) < $passwordmin
1575 or $passwordmax && length($pass) > $passwordmax;
1577 if ( $encoding eq 'crypt' ) {
1578 if ($encryption eq 'md5') {
1579 $pass = unix_md5_crypt($pass);
1580 } elsif ($encryption eq 'des') {
1581 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1584 } elsif ( $encoding eq 'ldap' ) {
1585 if ($encryption eq 'md5') {
1586 $pass = md5_base64($pass);
1587 } elsif ($encryption eq 'sha1') {
1588 $pass = sha1_base64($pass);
1589 } elsif ($encryption eq 'crypt') {
1590 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1592 # else $encryption eq 'plain', do nothing
1593 $pass = '{'.uc($encryption).'}'.$pass;
1595 # else encoding eq 'plain'
1597 $self->_password($pass);
1603 Internal function to check the username against the list of system usernames
1604 from the I<system_usernames> configuration value. Returns true if the username
1605 is listed on the system username list.
1611 scalar( grep { $self->username eq $_ || $self->email eq $_ }
1612 $conf->config('system_usernames')
1616 =item _check_duplicate
1618 Internal method to check for duplicates usernames, username@domain pairs and
1621 If the I<global_unique-username> configuration value is set to B<username> or
1622 B<username@domain>, enforces global username or username@domain uniqueness.
1624 In all cases, check for duplicate uids and usernames or username@domain pairs
1625 per export and with identical I<svcpart> values.
1629 sub _check_duplicate {
1632 my $global_unique = $conf->config('global_unique-username') || 'none';
1633 return '' if $global_unique eq 'disabled';
1637 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
1638 unless ( $part_svc ) {
1639 return 'unknown svcpart '. $self->svcpart;
1642 my @dup_user = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1643 qsearch( 'svc_acct', { 'username' => $self->username } );
1644 return gettext('username_in_use')
1645 if $global_unique eq 'username' && @dup_user;
1647 my @dup_userdomain = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1648 qsearch( 'svc_acct', { 'username' => $self->username,
1649 'domsvc' => $self->domsvc } );
1650 return gettext('username_in_use')
1651 if $global_unique eq 'username@domain' && @dup_userdomain;
1654 if ( $part_svc->part_svc_column('uid')->columnflag ne 'F'
1655 && $self->username !~ /^(toor|(hyla)?fax)$/ ) {
1656 @dup_uid = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1657 qsearch( 'svc_acct', { 'uid' => $self->uid } );
1662 if ( @dup_user || @dup_userdomain || @dup_uid ) {
1663 my $exports = FS::part_export::export_info('svc_acct');
1664 my %conflict_user_svcpart;
1665 my %conflict_userdomain_svcpart = ( $self->svcpart => 'SELF', );
1667 foreach my $part_export ( $part_svc->part_export ) {
1669 #this will catch to the same exact export
1670 my @svcparts = map { $_->svcpart } $part_export->export_svc;
1672 #this will catch to exports w/same exporthost+type ???
1673 #my @other_part_export = qsearch('part_export', {
1674 # 'machine' => $part_export->machine,
1675 # 'exporttype' => $part_export->exporttype,
1677 #foreach my $other_part_export ( @other_part_export ) {
1678 # push @svcparts, map { $_->svcpart }
1679 # qsearch('export_svc', { 'exportnum' => $part_export->exportnum });
1682 #my $nodomain = $exports->{$part_export->exporttype}{'nodomain'};
1683 #silly kludge to avoid uninitialized value errors
1684 my $nodomain = exists( $exports->{$part_export->exporttype}{'nodomain'} )
1685 ? $exports->{$part_export->exporttype}{'nodomain'}
1687 if ( $nodomain =~ /^Y/i ) {
1688 $conflict_user_svcpart{$_} = $part_export->exportnum
1691 $conflict_userdomain_svcpart{$_} = $part_export->exportnum
1696 foreach my $dup_user ( @dup_user ) {
1697 my $dup_svcpart = $dup_user->cust_svc->svcpart;
1698 if ( exists($conflict_user_svcpart{$dup_svcpart}) ) {
1699 return "duplicate username ". $self->username.
1700 ": conflicts with svcnum ". $dup_user->svcnum.
1701 " via exportnum ". $conflict_user_svcpart{$dup_svcpart};
1705 foreach my $dup_userdomain ( @dup_userdomain ) {
1706 my $dup_svcpart = $dup_userdomain->cust_svc->svcpart;
1707 if ( exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1708 return "duplicate username\@domain ". $self->email.
1709 ": conflicts with svcnum ". $dup_userdomain->svcnum.
1710 " via exportnum ". $conflict_userdomain_svcpart{$dup_svcpart};
1714 foreach my $dup_uid ( @dup_uid ) {
1715 my $dup_svcpart = $dup_uid->cust_svc->svcpart;
1716 if ( exists($conflict_user_svcpart{$dup_svcpart})
1717 || exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1718 return "duplicate uid ". $self->uid.
1719 ": conflicts with svcnum ". $dup_uid->svcnum.
1721 ( $conflict_user_svcpart{$dup_svcpart}
1722 || $conflict_userdomain_svcpart{$dup_svcpart} );
1734 Depriciated, use radius_reply instead.
1739 carp "FS::svc_acct::radius depriciated, use radius_reply";
1740 $_[0]->radius_reply;
1745 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1746 reply attributes of this record.
1748 Note that this is now the preferred method for reading RADIUS attributes -
1749 accessing the columns directly is discouraged, as the column names are
1750 expected to change in the future.
1757 return %{ $self->{'radius_reply'} }
1758 if exists $self->{'radius_reply'};
1763 my($column, $attrib) = ($1, $2);
1764 #$attrib =~ s/_/\-/g;
1765 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1766 } grep { /^radius_/ && $self->getfield($_) } fields( $self->table );
1768 if ( $self->slipip && $self->slipip ne '0e0' ) {
1769 $reply{$radius_ip} = $self->slipip;
1772 if ( $self->seconds !~ /^$/ ) {
1773 $reply{'Session-Timeout'} = $self->seconds;
1776 if ( $conf->exists('radius-chillispot-max') ) {
1777 #http://dev.coova.org/svn/coova-chilli/doc/dictionary.chillispot
1779 #hmm. just because sqlradius.pm says so?
1786 foreach my $what (qw( input output total )) {
1787 my $is = $whatis{$what}.'bytes';
1788 if ( $self->$is() =~ /\d/ ) {
1789 my $big = new Math::BigInt $self->$is();
1790 $big = new Math::BigInt '0' if $big->is_neg();
1791 my $att = "Chillispot-Max-\u$what";
1792 $reply{"$att-Octets"} = $big->copy->band(0xffffffff)->bstr;
1793 $reply{"$att-Gigawords"} = $big->copy->brsft(32)->bstr;
1804 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1805 check attributes of this record.
1807 Note that this is now the preferred method for reading RADIUS attributes -
1808 accessing the columns directly is discouraged, as the column names are
1809 expected to change in the future.
1816 return %{ $self->{'radius_check'} }
1817 if exists $self->{'radius_check'};
1822 my($column, $attrib) = ($1, $2);
1823 #$attrib =~ s/_/\-/g;
1824 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1825 } grep { /^rc_/ && $self->getfield($_) } fields( $self->table );
1828 my($pw_attrib, $password) = $self->radius_password;
1829 $check{$pw_attrib} = $password;
1831 my $cust_svc = $self->cust_svc;
1833 my $cust_pkg = $cust_svc->cust_pkg;
1834 if ( $cust_pkg && $cust_pkg->part_pkg->is_prepaid && $cust_pkg->bill ) {
1835 $check{'Expiration'} = time2str('%B %e %Y %T', $cust_pkg->bill ); #http://lists.cistron.nl/pipermail/freeradius-users/2005-January/040184.html
1838 warn "WARNING: no cust_svc record for svc_acct.svcnum ". $self->svcnum.
1839 "; can't set Expiration\n"
1847 =item radius_password
1849 Returns a key/value pair containing the RADIUS attribute name and value
1854 sub radius_password {
1858 if ( $self->_password_encoding eq 'ldap' ) {
1859 $pw_attrib = 'Password-With-Header';
1860 } elsif ( $self->_password_encoding eq 'crypt' ) {
1861 $pw_attrib = 'Crypt-Password';
1862 } elsif ( $self->_password_encoding eq 'plain' ) {
1863 $pw_attrib = $radius_password;
1865 $pw_attrib = length($self->_password) <= 12
1870 ($pw_attrib, $self->_password);
1876 This method instructs the object to "snapshot" or freeze RADIUS check and
1877 reply attributes to the current values.
1881 #bah, my english is too broken this morning
1882 #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
1883 #the FS::cust_pkg's replace method to trigger the correct export updates when
1884 #package dates change)
1889 $self->{$_} = { $self->$_() }
1890 foreach qw( radius_reply radius_check );
1894 =item forget_snapshot
1896 This methos instructs the object to forget any previously snapshotted
1897 RADIUS check and reply attributes.
1901 sub forget_snapshot {
1905 foreach qw( radius_reply radius_check );
1909 =item domain [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1911 Returns the domain associated with this account.
1913 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1920 die "svc_acct.domsvc is null for svcnum ". $self->svcnum unless $self->domsvc;
1921 my $svc_domain = $self->svc_domain(@_)
1922 or die "no svc_domain.svcnum for svc_acct.domsvc ". $self->domsvc;
1923 $svc_domain->domain;
1928 Returns the FS::cust_svc record for this account (see L<FS::cust_svc>).
1932 #inherited from svc_Common
1934 =item email [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1936 Returns an email address associated with the account.
1938 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1945 $self->username. '@'. $self->domain(@_);
1950 Returns an array of FS::acct_snarf records associated with the account.
1957 'table' => 'acct_snarf',
1958 'hashref' => { 'svcnum' => $self->svcnum },
1959 #'order_by' => 'ORDER BY priority ASC',
1963 =item cgp_rpop_hashref
1965 Returns an arrayref of RPOP data suitable for Communigate Pro API commands.
1969 sub cgp_rpop_hashref {
1971 { map { $_->snarfname => $_->cgp_hashref } $self->acct_snarf };
1974 =item decrement_upbytes OCTETS
1976 Decrements the I<upbytes> field of this record by the given amount. If there
1977 is an error, returns the error, otherwise returns false.
1981 sub decrement_upbytes {
1982 shift->_op_usage('-', 'upbytes', @_);
1985 =item increment_upbytes OCTETS
1987 Increments the I<upbytes> field of this record by the given amount. If there
1988 is an error, returns the error, otherwise returns false.
1992 sub increment_upbytes {
1993 shift->_op_usage('+', 'upbytes', @_);
1996 =item decrement_downbytes OCTETS
1998 Decrements the I<downbytes> field of this record by the given amount. If there
1999 is an error, returns the error, otherwise returns false.
2003 sub decrement_downbytes {
2004 shift->_op_usage('-', 'downbytes', @_);
2007 =item increment_downbytes OCTETS
2009 Increments the I<downbytes> field of this record by the given amount. If there
2010 is an error, returns the error, otherwise returns false.
2014 sub increment_downbytes {
2015 shift->_op_usage('+', 'downbytes', @_);
2018 =item decrement_totalbytes OCTETS
2020 Decrements the I<totalbytes> field of this record by the given amount. If there
2021 is an error, returns the error, otherwise returns false.
2025 sub decrement_totalbytes {
2026 shift->_op_usage('-', 'totalbytes', @_);
2029 =item increment_totalbytes OCTETS
2031 Increments the I<totalbytes> field of this record by the given amount. If there
2032 is an error, returns the error, otherwise returns false.
2036 sub increment_totalbytes {
2037 shift->_op_usage('+', 'totalbytes', @_);
2040 =item decrement_seconds SECONDS
2042 Decrements the I<seconds> field of this record by the given amount. If there
2043 is an error, returns the error, otherwise returns false.
2047 sub decrement_seconds {
2048 shift->_op_usage('-', 'seconds', @_);
2051 =item increment_seconds SECONDS
2053 Increments the I<seconds> field of this record by the given amount. If there
2054 is an error, returns the error, otherwise returns false.
2058 sub increment_seconds {
2059 shift->_op_usage('+', 'seconds', @_);
2067 my %op2condition = (
2068 '-' => sub { my($self, $column, $amount) = @_;
2069 $self->$column - $amount <= 0;
2071 '+' => sub { my($self, $column, $amount) = @_;
2072 ($self->$column || 0) + $amount > 0;
2075 my %op2warncondition = (
2076 '-' => sub { my($self, $column, $amount) = @_;
2077 my $threshold = $column . '_threshold';
2078 $self->$column - $amount <= $self->$threshold + 0;
2080 '+' => sub { my($self, $column, $amount) = @_;
2081 ($self->$column || 0) + $amount > 0;
2086 my( $self, $op, $column, $amount ) = @_;
2088 warn "$me _op_usage called for $column on svcnum ". $self->svcnum.
2089 ' ('. $self->email. "): $op $amount\n"
2092 return '' unless $amount;
2094 local $SIG{HUP} = 'IGNORE';
2095 local $SIG{INT} = 'IGNORE';
2096 local $SIG{QUIT} = 'IGNORE';
2097 local $SIG{TERM} = 'IGNORE';
2098 local $SIG{TSTP} = 'IGNORE';
2099 local $SIG{PIPE} = 'IGNORE';
2101 my $oldAutoCommit = $FS::UID::AutoCommit;
2102 local $FS::UID::AutoCommit = 0;
2105 my $sql = "UPDATE svc_acct SET $column = ".
2106 " CASE WHEN $column IS NULL THEN 0 ELSE $column END ". #$column||0
2107 " $op ? WHERE svcnum = ?";
2111 my $sth = $dbh->prepare( $sql )
2112 or die "Error preparing $sql: ". $dbh->errstr;
2113 my $rv = $sth->execute($amount, $self->svcnum);
2114 die "Error executing $sql: ". $sth->errstr
2115 unless defined($rv);
2116 die "Can't update $column for svcnum". $self->svcnum
2119 #$self->snapshot; #not necessary, we retain the old values
2120 #create an object with the updated usage values
2121 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2123 my $error = $new->replace($self);
2125 $dbh->rollback if $oldAutoCommit;
2126 return "Error replacing: $error";
2129 #overlimit_action eq 'cancel' handling
2130 my $cust_pkg = $self->cust_svc->cust_pkg;
2132 && $cust_pkg->part_pkg->option('overlimit_action', 1) eq 'cancel'
2133 && $op eq '-' && &{$op2condition{$op}}($self, $column, $amount)
2137 my $error = $cust_pkg->cancel; #XXX should have a reason
2139 $dbh->rollback if $oldAutoCommit;
2140 return "Error cancelling: $error";
2143 #nothing else is relevant if we're cancelling, so commit & return success
2144 warn "$me update successful; committing\n"
2146 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2151 my $action = $op2action{$op};
2153 if ( &{$op2condition{$op}}($self, $column, $amount) &&
2154 ( $action eq 'suspend' && !$self->overlimit
2155 || $action eq 'unsuspend' && $self->overlimit )
2158 my $error = $self->_op_overlimit($action);
2160 $dbh->rollback if $oldAutoCommit;
2166 if ( $conf->exists("svc_acct-usage_$action")
2167 && &{$op2condition{$op}}($self, $column, $amount) ) {
2168 #my $error = $self->$action();
2169 my $error = $self->cust_svc->cust_pkg->$action();
2170 # $error ||= $self->overlimit($action);
2172 $dbh->rollback if $oldAutoCommit;
2173 return "Error ${action}ing: $error";
2177 if ($warning_template && &{$op2warncondition{$op}}($self, $column, $amount)) {
2178 my $wqueue = new FS::queue {
2179 'svcnum' => $self->svcnum,
2180 'job' => 'FS::svc_acct::reached_threshold',
2185 $to = $warning_cc if &{$op2condition{$op}}($self, $column, $amount);
2189 my $error = $wqueue->insert(
2190 'svcnum' => $self->svcnum,
2192 'column' => $column,
2196 $dbh->rollback if $oldAutoCommit;
2197 return "Error queuing threshold activity: $error";
2201 warn "$me update successful; committing\n"
2203 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2209 my( $self, $action ) = @_;
2211 local $SIG{HUP} = 'IGNORE';
2212 local $SIG{INT} = 'IGNORE';
2213 local $SIG{QUIT} = 'IGNORE';
2214 local $SIG{TERM} = 'IGNORE';
2215 local $SIG{TSTP} = 'IGNORE';
2216 local $SIG{PIPE} = 'IGNORE';
2218 my $oldAutoCommit = $FS::UID::AutoCommit;
2219 local $FS::UID::AutoCommit = 0;
2222 my $cust_pkg = $self->cust_svc->cust_pkg;
2224 my $conf_overlimit =
2226 ? $conf->config('overlimit_groups', $cust_pkg->cust_main->agentnum )
2227 : $conf->config('overlimit_groups');
2229 foreach my $part_export ( $self->cust_svc->part_svc->part_export ) {
2231 my $groups = $conf_overlimit || $part_export->option('overlimit_groups');
2232 next unless $groups;
2234 my $gref = &{ $self->_fieldhandlers->{'usergroup'} }( $self, $groups );
2236 my $other = new FS::svc_acct $self->hashref;
2237 $other->usergroup( $gref );
2240 if ($action eq 'suspend') {
2243 } else { # $action eq 'unsuspend'
2248 my $error = $part_export->export_replace($new, $old)
2249 || $self->overlimit($action);
2252 $dbh->rollback if $oldAutoCommit;
2253 return "Error replacing radius groups: $error";
2258 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2264 my( $self, $valueref, %options ) = @_;
2266 warn "$me set_usage called for svcnum ". $self->svcnum.
2267 ' ('. $self->email. "): ".
2268 join(', ', map { "$_ => " . $valueref->{$_}} keys %$valueref) . "\n"
2271 local $SIG{HUP} = 'IGNORE';
2272 local $SIG{INT} = 'IGNORE';
2273 local $SIG{QUIT} = 'IGNORE';
2274 local $SIG{TERM} = 'IGNORE';
2275 local $SIG{TSTP} = 'IGNORE';
2276 local $SIG{PIPE} = 'IGNORE';
2278 local $FS::svc_Common::noexport_hack = 1;
2279 my $oldAutoCommit = $FS::UID::AutoCommit;
2280 local $FS::UID::AutoCommit = 0;
2285 if ( $options{null} ) {
2286 %handyhash = ( map { ( $_ => undef, $_."_threshold" => undef ) }
2287 qw( seconds upbytes downbytes totalbytes )
2290 foreach my $field (keys %$valueref){
2291 $reset = 1 if $valueref->{$field};
2292 $self->setfield($field, $valueref->{$field});
2293 $self->setfield( $field.'_threshold',
2294 int($self->getfield($field)
2295 * ( $conf->exists('svc_acct-usage_threshold')
2296 ? 1 - $conf->config('svc_acct-usage_threshold')/100
2301 $handyhash{$field} = $self->getfield($field);
2302 $handyhash{$field.'_threshold'} = $self->getfield($field.'_threshold');
2304 #my $error = $self->replace; #NO! we avoid the call to ->check for
2305 #die $error if $error; #services not explicity changed via the UI
2307 my $sql = "UPDATE svc_acct SET " .
2308 join (',', map { "$_ = ?" } (keys %handyhash) ).
2309 " WHERE svcnum = ". $self->svcnum;
2314 if (scalar(keys %handyhash)) {
2315 my $sth = $dbh->prepare( $sql )
2316 or die "Error preparing $sql: ". $dbh->errstr;
2317 my $rv = $sth->execute(values %handyhash);
2318 die "Error executing $sql: ". $sth->errstr
2319 unless defined($rv);
2320 die "Can't update usage for svcnum ". $self->svcnum
2324 #$self->snapshot; #not necessary, we retain the old values
2325 #create an object with the updated usage values
2326 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2327 local($FS::Record::nowarn_identical) = 1;
2328 my $error = $new->replace($self); #call exports
2330 $dbh->rollback if $oldAutoCommit;
2331 return "Error replacing: $error";
2338 $error = $self->_op_overlimit('unsuspend')
2339 if $self->overlimit;;
2341 $error ||= $self->cust_svc->cust_pkg->unsuspend
2342 if $conf->exists("svc_acct-usage_unsuspend");
2345 $dbh->rollback if $oldAutoCommit;
2346 return "Error unsuspending: $error";
2351 warn "$me update successful; committing\n"
2353 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2359 =item recharge HASHREF
2361 Increments usage columns by the amount specified in HASHREF as
2362 column=>amount pairs.
2367 my ($self, $vhash) = @_;
2370 warn "[$me] recharge called on $self: ". Dumper($self).
2371 "\nwith vhash: ". Dumper($vhash);
2374 my $oldAutoCommit = $FS::UID::AutoCommit;
2375 local $FS::UID::AutoCommit = 0;
2379 foreach my $column (keys %$vhash){
2380 $error ||= $self->_op_usage('+', $column, $vhash->{$column});
2384 $dbh->rollback if $oldAutoCommit;
2386 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2391 =item is_rechargeable
2393 Returns true if this svc_account can be "recharged" and false otherwise.
2397 sub is_rechargable {
2399 $self->seconds ne ''
2400 || $self->upbytes ne ''
2401 || $self->downbytes ne ''
2402 || $self->totalbytes ne '';
2405 =item seconds_since TIMESTAMP
2407 Returns the number of seconds this account has been online since TIMESTAMP,
2408 according to the session monitor (see L<FS::Session>).
2410 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2411 L<Time::Local> and L<Date::Parse> for conversion functions.
2415 #note: POD here, implementation in FS::cust_svc
2418 $self->cust_svc->seconds_since(@_);
2421 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2423 Returns the numbers of seconds this account has been online between
2424 TIMESTAMP_START (inclusive) and TIMESTAMP_END (exclusive), according to an
2425 external SQL radacct table, specified via sqlradius export. Sessions which
2426 started in the specified range but are still open are counted from session
2427 start to the end of the range (unless they are over 1 day old, in which case
2428 they are presumed missing their stop record and not counted). Also, sessions
2429 which end in the range but started earlier are counted from the start of the
2430 range to session end. Finally, sessions which start before the range but end
2431 after are counted for the entire range.
2433 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2434 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2439 #note: POD here, implementation in FS::cust_svc
2440 sub seconds_since_sqlradacct {
2442 $self->cust_svc->seconds_since_sqlradacct(@_);
2445 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2447 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2448 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2449 TIMESTAMP_END (exclusive).
2451 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2452 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2457 #note: POD here, implementation in FS::cust_svc
2458 sub attribute_since_sqlradacct {
2460 $self->cust_svc->attribute_since_sqlradacct(@_);
2463 =item get_session_history TIMESTAMP_START TIMESTAMP_END
2465 Returns an array of hash references of this customers login history for the
2466 given time range. (document this better)
2470 sub get_session_history {
2472 $self->cust_svc->get_session_history(@_);
2475 =item last_login_text
2477 Returns text describing the time of last login.
2481 sub last_login_text {
2483 $self->last_login ? ctime($self->last_login) : 'unknown';
2486 =item get_cdrs TIMESTAMP_START TIMESTAMP_END [ 'OPTION' => 'VALUE ... ]
2491 my($self, $start, $end, %opt ) = @_;
2493 my $did = $self->username; #yup
2495 my $prefix = $opt{'default_prefix'}; #convergent.au '+61'
2497 my $for_update = $opt{'for_update'} ? 'FOR UPDATE' : '';
2499 #SELECT $for_update * FROM cdr
2500 # WHERE calldate >= $start #need a conversion
2501 # AND calldate < $end #ditto
2502 # AND ( charged_party = "$did"
2503 # OR charged_party = "$prefix$did" #if length($prefix);
2504 # OR ( ( charged_party IS NULL OR charged_party = '' )
2506 # ( src = "$did" OR src = "$prefix$did" ) # if length($prefix)
2509 # AND ( freesidestatus IS NULL OR freesidestatus = '' )
2512 if ( length($prefix) ) {
2514 " AND ( charged_party = '$did'
2515 OR charged_party = '$prefix$did'
2516 OR ( ( charged_party IS NULL OR charged_party = '' )
2518 ( src = '$did' OR src = '$prefix$did' )
2524 " AND ( charged_party = '$did'
2525 OR ( ( charged_party IS NULL OR charged_party = '' )
2535 'select' => "$for_update *",
2538 #( freesidestatus IS NULL OR freesidestatus = '' )
2539 'freesidestatus' => '',
2541 'extra_sql' => $charged_or_src,
2549 Returns all RADIUS groups for this account (see L<FS::radius_usergroup>).
2555 if ( $self->usergroup ) {
2556 confess "explicitly specified usergroup not an arrayref: ". $self->usergroup
2557 unless ref($self->usergroup) eq 'ARRAY';
2558 #when provisioning records, export callback runs in svc_Common.pm before
2559 #radius_usergroup records can be inserted...
2560 @{$self->usergroup};
2562 map { $_->groupname }
2563 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } );
2567 =item clone_suspended
2569 Constructor used by FS::part_export::_export_suspend fallback. Document
2574 sub clone_suspended {
2576 my %hash = $self->hash;
2577 $hash{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
2578 new FS::svc_acct \%hash;
2581 =item clone_kludge_unsuspend
2583 Constructor used by FS::part_export::_export_unsuspend fallback. Document
2588 sub clone_kludge_unsuspend {
2590 my %hash = $self->hash;
2591 $hash{_password} = '';
2592 new FS::svc_acct \%hash;
2595 =item check_password
2597 Checks the supplied password against the (possibly encrypted) password in the
2598 database. Returns true for a successful authentication, false for no match.
2600 Currently supported encryptions are: classic DES crypt() and MD5
2604 sub check_password {
2605 my($self, $check_password) = @_;
2607 #remove old-style SUSPENDED kludge, they should be allowed to login to
2608 #self-service and pay up
2609 ( my $password = $self->_password ) =~ s/^\*SUSPENDED\* //;
2611 if ( $self->_password_encoding eq 'ldap' ) {
2613 my $auth = from_rfc2307 Authen::Passphrase $self->_password;
2614 return $auth->match($check_password);
2616 } elsif ( $self->_password_encoding eq 'crypt' ) {
2618 my $auth = from_crypt Authen::Passphrase $self->_password;
2619 return $auth->match($check_password);
2621 } elsif ( $self->_password_encoding eq 'plain' ) {
2623 return $check_password eq $password;
2627 #XXX this could be replaced with Authen::Passphrase stuff
2629 if ( $password =~ /^(\*|!!?)$/ ) { #no self-service login
2631 } elsif ( length($password) < 13 ) { #plaintext
2632 $check_password eq $password;
2633 } elsif ( length($password) == 13 ) { #traditional DES crypt
2634 crypt($check_password, $password) eq $password;
2635 } elsif ( $password =~ /^\$1\$/ ) { #MD5 crypt
2636 unix_md5_crypt($check_password, $password) eq $password;
2637 } elsif ( $password =~ /^\$2a?\$/ ) { #Blowfish
2638 warn "Can't check password: Blowfish encryption not yet supported, ".
2639 "svcnum ". $self->svcnum. "\n";
2642 warn "Can't check password: Unrecognized encryption for svcnum ".
2643 $self->svcnum. "\n";
2651 =item crypt_password [ DEFAULT_ENCRYPTION_TYPE ]
2653 Returns an encrypted password, either by passing through an encrypted password
2654 in the database or by encrypting a plaintext password from the database.
2656 The optional DEFAULT_ENCRYPTION_TYPE parameter can be set to I<crypt> (classic
2657 UNIX DES crypt), I<md5> (md5 crypt supported by most modern Linux and BSD
2658 distrubtions), or (eventually) I<blowfish> (blowfish hashing supported by
2659 OpenBSD, SuSE, other Linux distibutions with pam_unix2, etc.). The default
2660 encryption type is only used if the password is not already encrypted in the
2665 sub crypt_password {
2668 if ( $self->_password_encoding eq 'ldap' ) {
2670 if ( $self->_password =~ /^\{(PLAIN|CLEARTEXT)\}(.+)$/ ) {
2673 #XXX this could be replaced with Authen::Passphrase stuff
2675 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2676 if ( $encryption eq 'crypt' ) {
2679 $saltset[int(rand(64))].$saltset[int(rand(64))]
2681 } elsif ( $encryption eq 'md5' ) {
2682 unix_md5_crypt( $self->_password );
2683 } elsif ( $encryption eq 'blowfish' ) {
2684 croak "unknown encryption method $encryption";
2686 croak "unknown encryption method $encryption";
2689 } elsif ( $self->_password =~ /^\{CRYPT\}(.+)$/ ) {
2693 } elsif ( $self->_password_encoding eq 'crypt' ) {
2695 return $self->_password;
2697 } elsif ( $self->_password_encoding eq 'plain' ) {
2699 #XXX this could be replaced with Authen::Passphrase stuff
2701 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2702 if ( $encryption eq 'crypt' ) {
2705 $saltset[int(rand(64))].$saltset[int(rand(64))]
2707 } elsif ( $encryption eq 'md5' ) {
2708 unix_md5_crypt( $self->_password );
2709 } elsif ( $encryption eq 'blowfish' ) {
2710 croak "unknown encryption method $encryption";
2712 croak "unknown encryption method $encryption";
2717 if ( length($self->_password) == 13
2718 || $self->_password =~ /^\$(1|2a?)\$/
2719 || $self->_password =~ /^(\*|NP|\*LK\*|!!?)$/
2725 #XXX this could be replaced with Authen::Passphrase stuff
2727 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2728 if ( $encryption eq 'crypt' ) {
2731 $saltset[int(rand(64))].$saltset[int(rand(64))]
2733 } elsif ( $encryption eq 'md5' ) {
2734 unix_md5_crypt( $self->_password );
2735 } elsif ( $encryption eq 'blowfish' ) {
2736 croak "unknown encryption method $encryption";
2738 croak "unknown encryption method $encryption";
2747 =item ldap_password [ DEFAULT_ENCRYPTION_TYPE ]
2749 Returns an encrypted password in "LDAP" format, with a curly-bracked prefix
2750 describing the format, for example, "{PLAIN}himom", "{CRYPT}94pAVyK/4oIBk" or
2751 "{MD5}5426824942db4253f87a1009fd5d2d4".
2753 The optional DEFAULT_ENCRYPTION_TYPE is not yet used, but the idea is for it
2754 to work the same as the B</crypt_password> method.
2760 #eventually should check a "password-encoding" field
2762 if ( $self->_password_encoding eq 'ldap' ) {
2764 return $self->_password;
2766 } elsif ( $self->_password_encoding eq 'crypt' ) {
2768 if ( length($self->_password) == 13 ) { #crypt
2769 return '{CRYPT}'. $self->_password;
2770 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2772 #} elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2773 # die "Blowfish encryption not supported in this context, svcnum ".
2774 # $self->svcnum. "\n";
2776 warn "encryption method not (yet?) supported in LDAP context";
2777 return '{CRYPT}*'; #unsupported, should not auth
2780 } elsif ( $self->_password_encoding eq 'plain' ) {
2782 return '{PLAIN}'. $self->_password;
2784 #return '{CLEARTEXT}'. $self->_password; #?
2788 if ( length($self->_password) == 13 ) { #crypt
2789 return '{CRYPT}'. $self->_password;
2790 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2792 } elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2793 warn "Blowfish encryption not supported in this context, svcnum ".
2794 $self->svcnum. "\n";
2797 #are these two necessary anymore?
2798 } elsif ( $self->_password =~ /^(\w{48})$/ ) { #LDAP SSHA
2799 return '{SSHA}'. $1;
2800 } elsif ( $self->_password =~ /^(\w{64})$/ ) { #LDAP NS-MTA-MD5
2801 return '{NS-MTA-MD5}'. $1;
2804 return '{PLAIN}'. $self->_password;
2806 #return '{CLEARTEXT}'. $self->_password; #?
2808 #XXX this could be replaced with Authen::Passphrase stuff if it gets used
2809 #my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2810 #if ( $encryption eq 'crypt' ) {
2811 # return '{CRYPT}'. crypt(
2813 # $saltset[int(rand(64))].$saltset[int(rand(64))]
2815 #} elsif ( $encryption eq 'md5' ) {
2816 # unix_md5_crypt( $self->_password );
2817 #} elsif ( $encryption eq 'blowfish' ) {
2818 # croak "unknown encryption method $encryption";
2820 # croak "unknown encryption method $encryption";
2828 =item domain_slash_username
2830 Returns $domain/$username/
2834 sub domain_slash_username {
2836 $self->domain. '/'. $self->username. '/';
2839 =item virtual_maildir
2841 Returns $domain/maildirs/$username/
2845 sub virtual_maildir {
2847 $self->domain. '/maildirs/'. $self->username. '/';
2852 =head1 CLASS METHODS
2856 =item search HASHREF
2858 Class method which returns a qsearch hash expression to search for parameters
2859 specified in HASHREF. Valid parameters are
2873 Arrayref of pkgparts
2879 Arrayref of additional WHERE clauses, will be ANDed together.
2890 my ($class, $params) = @_;
2895 if ( $params->{'domain'} ) {
2896 my $svc_domain = qsearchs('svc_domain', { 'domain'=>$params->{'domain'} } );
2897 #preserve previous behavior & bubble up an error if $svc_domain not found?
2898 push @where, 'domsvc = '. $svc_domain->svcnum if $svc_domain;
2902 if ( $params->{'domsvc'} =~ /^(\d+)$/ ) {
2903 push @where, "domsvc = $1";
2907 push @where, 'pkgnum IS NULL' if $params->{'unlinked'};
2910 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2911 push @where, "agentnum = $1";
2915 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2916 push @where, "custnum = $1";
2920 if ( $params->{'pkgpart'} && scalar(@{ $params->{'pkgpart'} }) ) {
2921 #XXX untaint or sql quote
2923 'cust_pkg.pkgpart IN ('. join(',', @{ $params->{'pkgpart'} } ). ')';
2927 if ( $params->{'popnum'} =~ /^(\d+)$/ ) {
2928 push @where, "popnum = $1";
2932 if ( $params->{'svcpart'} =~ /^(\d+)$/ ) {
2933 push @where, "svcpart = $1";
2937 # here is the agent virtualization
2938 #if ($params->{CurrentUser}) {
2940 # qsearchs('access_user', { username => $params->{CurrentUser} });
2942 # if ($access_user) {
2943 # push @where, $access_user->agentnums_sql('table'=>'cust_main');
2945 # push @where, "1=0";
2948 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql(
2949 'table' => 'cust_main',
2950 'null_right' => 'View/link unlinked services',
2954 push @where, @{ $params->{'where'} } if $params->{'where'};
2956 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2958 my $addl_from = ' LEFT JOIN cust_svc USING ( svcnum ) '.
2959 ' LEFT JOIN part_svc USING ( svcpart ) '.
2960 ' LEFT JOIN cust_pkg USING ( pkgnum ) '.
2961 ' LEFT JOIN cust_main USING ( custnum ) ';
2963 my $count_query = "SELECT COUNT(*) FROM svc_acct $addl_from $extra_sql";
2964 #if ( keys %svc_acct ) {
2965 # $count_query .= ' WHERE '.
2966 # join(' AND ', map "$_ = ". dbh->quote($svc_acct{$_}),
2972 'table' => 'svc_acct',
2973 'hashref' => {}, # \%svc_acct,
2974 'select' => join(', ',
2977 'cust_main.custnum',
2978 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
2980 'addl_from' => $addl_from,
2981 'extra_sql' => $extra_sql,
2982 'order_by' => $params->{'order_by'},
2983 'count_query' => $count_query,
2996 This is the FS::svc_acct job-queue-able version. It still uses
2997 FS::Misc::send_email under-the-hood.
3004 eval "use FS::Misc qw(send_email)";
3007 $opt{mimetype} ||= 'text/plain';
3008 $opt{mimetype} .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
3010 my $error = send_email(
3011 'from' => $opt{from},
3013 'subject' => $opt{subject},
3014 'content-type' => $opt{mimetype},
3015 'body' => [ map "$_\n", split("\n", $opt{body}) ],
3017 die $error if $error;
3020 =item check_and_rebuild_fuzzyfiles
3024 sub check_and_rebuild_fuzzyfiles {
3025 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3026 -e "$dir/svc_acct.username"
3027 or &rebuild_fuzzyfiles;
3030 =item rebuild_fuzzyfiles
3034 sub rebuild_fuzzyfiles {
3036 use Fcntl qw(:flock);
3038 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3042 open(USERNAMELOCK,">>$dir/svc_acct.username")
3043 or die "can't open $dir/svc_acct.username: $!";
3044 flock(USERNAMELOCK,LOCK_EX)
3045 or die "can't lock $dir/svc_acct.username: $!";
3047 my @all_username = map $_->getfield('username'), qsearch('svc_acct', {});
3049 open (USERNAMECACHE,">$dir/svc_acct.username.tmp")
3050 or die "can't open $dir/svc_acct.username.tmp: $!";
3051 print USERNAMECACHE join("\n", @all_username), "\n";
3052 close USERNAMECACHE or die "can't close $dir/svc_acct.username.tmp: $!";
3054 rename "$dir/svc_acct.username.tmp", "$dir/svc_acct.username";
3064 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3065 open(USERNAMECACHE,"<$dir/svc_acct.username")
3066 or die "can't open $dir/svc_acct.username: $!";
3067 my @array = map { chomp; $_; } <USERNAMECACHE>;
3068 close USERNAMECACHE;
3072 =item append_fuzzyfiles USERNAME
3076 sub append_fuzzyfiles {
3077 my $username = shift;
3079 &check_and_rebuild_fuzzyfiles;
3081 use Fcntl qw(:flock);
3083 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3085 open(USERNAME,">>$dir/svc_acct.username")
3086 or die "can't open $dir/svc_acct.username: $!";
3087 flock(USERNAME,LOCK_EX)
3088 or die "can't lock $dir/svc_acct.username: $!";
3090 print USERNAME "$username\n";
3092 flock(USERNAME,LOCK_UN)
3093 or die "can't unlock $dir/svc_acct.username: $!";
3101 =item radius_usergroup_selector GROUPS_ARRAYREF [ SELECTNAME ]
3105 sub radius_usergroup_selector {
3106 my $sel_groups = shift;
3107 my %sel_groups = map { $_=>1 } @$sel_groups;
3109 my $selectname = shift || 'radius_usergroup';
3112 my $sth = $dbh->prepare(
3113 'SELECT DISTINCT(groupname) FROM radius_usergroup ORDER BY groupname'
3114 ) or die $dbh->errstr;
3115 $sth->execute() or die $sth->errstr;
3116 my @all_groups = map { $_->[0] } @{$sth->fetchall_arrayref};
3120 function ${selectname}_doadd(object) {
3121 var myvalue = object.${selectname}_add.value;
3122 var optionName = new Option(myvalue,myvalue,false,true);
3123 var length = object.$selectname.length;
3124 object.$selectname.options[length] = optionName;
3125 object.${selectname}_add.value = "";
3128 <SELECT MULTIPLE NAME="$selectname">
3131 foreach my $group ( @all_groups ) {
3132 $html .= qq(<OPTION VALUE="$group");
3133 if ( $sel_groups{$group} ) {
3134 $html .= ' SELECTED';
3135 $sel_groups{$group} = 0;
3137 $html .= ">$group</OPTION>\n";
3139 foreach my $group ( grep { $sel_groups{$_} } keys %sel_groups ) {
3140 $html .= qq(<OPTION VALUE="$group" SELECTED>$group</OPTION>\n);
3142 $html .= '</SELECT>';
3144 $html .= qq!<BR><INPUT TYPE="text" NAME="${selectname}_add">!.
3145 qq!<INPUT TYPE="button" VALUE="Add new group" onClick="${selectname}_doadd(this.form)">!;
3150 =item reached_threshold
3152 Performs some activities when svc_acct thresholds (such as number of seconds
3153 remaining) are reached.
3157 sub reached_threshold {
3160 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } );
3161 die "Cannot find svc_acct with svcnum " . $opt{'svcnum'} unless $svc_acct;
3163 if ( $opt{'op'} eq '+' ){
3164 $svc_acct->setfield( $opt{'column'}.'_threshold',
3165 int($svc_acct->getfield($opt{'column'})
3166 * ( $conf->exists('svc_acct-usage_threshold')
3167 ? $conf->config('svc_acct-usage_threshold')/100
3172 my $error = $svc_acct->replace;
3173 die $error if $error;
3174 }elsif ( $opt{'op'} eq '-' ){
3176 my $threshold = $svc_acct->getfield( $opt{'column'}.'_threshold' );
3177 return '' if ($threshold eq '' );
3179 $svc_acct->setfield( $opt{'column'}.'_threshold', 0 );
3180 my $error = $svc_acct->replace;
3181 die $error if $error; # email next time, i guess
3183 if ( $warning_template ) {
3184 eval "use FS::Misc qw(send_email)";
3187 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3188 my $cust_main = $cust_pkg->cust_main;
3190 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ }
3191 $cust_main->invoicing_list,
3192 ($opt{'to'} ? $opt{'to'} : ())
3195 my $mimetype = $warning_mimetype;
3196 $mimetype .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
3198 my $body = $warning_template->fill_in( HASH => {
3199 'custnum' => $cust_main->custnum,
3200 'username' => $svc_acct->username,
3201 'password' => $svc_acct->_password,
3202 'first' => $cust_main->first,
3203 'last' => $cust_main->getfield('last'),
3204 'pkg' => $cust_pkg->part_pkg->pkg,
3205 'column' => $opt{'column'},
3206 'amount' => $opt{'column'} =~/bytes/
3207 ? FS::UI::bytecount::display_bytecount($svc_acct->getfield($opt{'column'}))
3208 : $svc_acct->getfield($opt{'column'}),
3209 'threshold' => $opt{'column'} =~/bytes/
3210 ? FS::UI::bytecount::display_bytecount($threshold)
3215 my $error = send_email(
3216 'from' => $warning_from,
3218 'subject' => $warning_subject,
3219 'content-type' => $mimetype,
3220 'body' => [ map "$_\n", split("\n", $body) ],
3222 die $error if $error;
3225 die "unknown op: " . $opt{'op'};
3233 The $recref stuff in sub check should be cleaned up.
3235 The suspend, unsuspend and cancel methods update the database, but not the
3236 current object. This is probably a bug as it's unexpected and
3239 radius_usergroup_selector? putting web ui components in here? they should
3240 probably live somewhere else...
3242 insertion of RADIUS group stuff in insert could be done with child_objects now
3243 (would probably clean up export of them too)
3245 _op_usage and set_usage bypass the history... maybe they shouldn't
3249 L<FS::svc_Common>, edit/part_svc.cgi from an installed web interface,
3250 export.html from the base documentation, L<FS::Record>, L<FS::Conf>,
3251 L<FS::cust_svc>, L<FS::part_svc>, L<FS::cust_pkg>, L<FS::queue>,
3252 L<freeside-queued>), L<FS::svc_acct_pop>,
3253 schema.html from the base documentation.