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
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 $password_noampersand = $conf->exists('password-noexclamation');
81 $password_noexclamation = $conf->exists('password-noexclamation');
82 $dirhash = $conf->config('dirhash') || 0;
83 if ( $conf->exists('warning_email') ) {
84 $warning_template = new Text::Template (
86 SOURCE => [ map "$_\n", $conf->config('warning_email') ]
87 ) or warn "can't create warning email template: $Text::Template::ERROR";
88 $warning_from = $conf->config('warning_email-from'); # || 'your-isp-is-dum'
89 $warning_subject = $conf->config('warning_email-subject') || 'Warning';
90 $warning_mimetype = $conf->config('warning_email-mimetype') || 'text/plain';
91 $warning_cc = $conf->config('warning_email-cc');
93 $warning_template = '';
95 $warning_subject = '';
96 $warning_mimetype = '';
99 $smtpmachine = $conf->config('smtpmachine');
100 $radius_password = $conf->config('radius-password') || 'Password';
101 $radius_ip = $conf->config('radius-ip') || 'Framed-IP-Address';
102 @pw_set = ( 'A'..'Z' ) if $conf->exists('password-generated-allcaps');
106 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '.' , '/' );
107 @pw_set = ( 'a'..'z', 'A'..'Z', '0'..'9', '(', ')', '#', '.', ',' );
111 my ( $hashref, $cache ) = @_;
112 if ( $hashref->{'svc_acct_svcnum'} ) {
113 $self->{'_domsvc'} = FS::svc_domain->new( {
114 'svcnum' => $hashref->{'domsvc'},
115 'domain' => $hashref->{'svc_acct_domain'},
116 'catchall' => $hashref->{'svc_acct_catchall'},
123 FS::svc_acct - Object methods for svc_acct records
129 $record = new FS::svc_acct \%hash;
130 $record = new FS::svc_acct { 'column' => 'value' };
132 $error = $record->insert;
134 $error = $new_record->replace($old_record);
136 $error = $record->delete;
138 $error = $record->check;
140 $error = $record->suspend;
142 $error = $record->unsuspend;
144 $error = $record->cancel;
146 %hash = $record->radius;
148 %hash = $record->radius_reply;
150 %hash = $record->radius_check;
152 $domain = $record->domain;
154 $svc_domain = $record->svc_domain;
156 $email = $record->email;
158 $seconds_since = $record->seconds_since($timestamp);
162 An FS::svc_acct object represents an account. FS::svc_acct inherits from
163 FS::svc_Common. The following fields are currently supported:
169 Primary key (assigned automatcially for new accounts)
177 =item _password_encoding
179 plain, crypt, ldap (or empty for autodetection)
187 Point of presence (see L<FS::svc_acct_pop>)
199 set automatically if blank (and uid is not)
219 svcnum from svc_domain
223 Optional svcnum from svc_pbx
225 =item radius_I<Radius_Attribute>
227 I<Radius-Attribute> (reply)
229 =item rc_I<Radius_Attribute>
231 I<Radius-Attribute> (check)
241 Creates a new account. To add the account to the database, see L<"insert">.
248 'longname_plural' => 'Access accounts and mailboxes',
249 'sorts' => [ 'username', 'uid', 'seconds', 'last_login' ],
250 'display_weight' => 10,
251 'cancel_weight' => 50,
253 'dir' => 'Home directory',
256 def_info => 'set to fixed and blank for no UIDs',
259 'slipip' => 'IP address',
260 # 'popnum' => qq!<A HREF="$p/browse/svc_acct_pop.cgi/">POP number</A>!,
262 label => 'Access number',
264 select_table => 'svc_acct_pop',
265 select_key => 'popnum',
266 select_label => 'city',
272 disable_default => 1,
276 'password_selfchange' => { label => 'Password modification',
279 'password_recover' => { label => 'Password recovery',
283 label => 'Quota', #Mail storage limit
285 disable_inventory => 1,
289 label => 'File storage limit',
291 disable_inventory => 1,
295 label => 'Number of files limit',
297 disable_inventory => 1,
301 label => 'File size limit',
303 disable_inventory => 1,
306 '_password' => 'Password',
309 def_info => 'when blank, defaults to UID',
314 def_info => 'set to blank for no shell tracking',
316 #select_list => [ $conf->config('shells') ],
317 select_list => [ $conf ? $conf->config('shells') : () ],
318 disable_inventory => 1,
321 'finger' => 'Real name', # (GECOS)',
325 select_table => 'svc_domain',
326 select_key => 'svcnum',
327 select_label => 'domain',
328 disable_inventory => 1,
330 'pbxsvc' => { label => 'PBX',
331 type => 'select-svc_pbx.html',
332 disable_inventory => 1,
333 disable_select => 1, #UI wonky, pry works otherwise
336 label => 'RADIUS groups',
337 type => 'radius_usergroup_selector',
338 disable_inventory => 1,
341 'seconds' => { label => 'Seconds',
342 label_sort => 'with Time Remaining',
344 disable_inventory => 1,
346 disable_part_svc_column => 1,
348 'upbytes' => { label => 'Upload',
350 disable_inventory => 1,
352 'format' => \&FS::UI::bytecount::display_bytecount,
353 'parse' => \&FS::UI::bytecount::parse_bytecount,
354 disable_part_svc_column => 1,
356 'downbytes' => { label => 'Download',
358 disable_inventory => 1,
360 'format' => \&FS::UI::bytecount::display_bytecount,
361 'parse' => \&FS::UI::bytecount::parse_bytecount,
362 disable_part_svc_column => 1,
364 'totalbytes'=> { label => 'Total up and download',
366 disable_inventory => 1,
368 'format' => \&FS::UI::bytecount::display_bytecount,
369 'parse' => \&FS::UI::bytecount::parse_bytecount,
370 disable_part_svc_column => 1,
372 'seconds_threshold' => { label => 'Seconds threshold',
374 disable_inventory => 1,
376 disable_part_svc_column => 1,
378 'upbytes_threshold' => { label => 'Upload threshold',
380 disable_inventory => 1,
382 'format' => \&FS::UI::bytecount::display_bytecount,
383 'parse' => \&FS::UI::bytecount::parse_bytecount,
384 disable_part_svc_column => 1,
386 'downbytes_threshold' => { label => 'Download threshold',
388 disable_inventory => 1,
390 'format' => \&FS::UI::bytecount::display_bytecount,
391 'parse' => \&FS::UI::bytecount::parse_bytecount,
392 disable_part_svc_column => 1,
394 'totalbytes_threshold'=> { label => 'Total up and download threshold',
396 disable_inventory => 1,
398 'format' => \&FS::UI::bytecount::display_bytecount,
399 'parse' => \&FS::UI::bytecount::parse_bytecount,
400 disable_part_svc_column => 1,
403 label => 'Last login',
407 label => 'Last logout',
412 label => 'Communigate aliases',
414 disable_inventory => 1,
419 label => 'Communigate account type',
421 select_list => [qw( MultiMailbox TextMailbox MailDirMailbox AGrade BGrade CGrade )],
422 disable_inventory => 1,
425 'cgp_accessmodes' => {
426 label => 'Communigate enabled services',
427 type => 'communigate_pro-accessmodes',
428 disable_inventory => 1,
431 'cgp_rulesallowed' => {
432 label => 'Allowed mail rules',
434 select_list => [ '', 'No', 'Filter Only', 'All But Exec', 'Any' ],
435 disable_inventory => 1,
438 'cgp_rpopallowed' => { label => 'RPOP modifications',
441 'cgp_mailtoall' => { label => 'Accepts mail to "all"',
444 'cgp_addmailtrailer' => { label => 'Add trailer to sent mail',
447 'cgp_archiveafter' => {
448 label => 'Archive messages after',
451 -2 => 'default(730 days)',
458 1209600 => '2 weeks',
459 2592000 => '30 days',
460 7776000 => '90 days',
461 15552000 => '180 days',
462 31536000 => '365 days',
463 63072000 => '730 days',
465 disable_inventory => 1,
471 'cgp_deletemode' => {
472 label => 'Communigate message delete method',
474 select_list => [ 'Move To Trash', 'Immediately', 'Mark' ],
475 disable_inventory => 1,
478 'cgp_emptytrash' => {
479 label => 'Communigate on logout remove trash',
481 select_list => __PACKAGE__->cgp_emptytrash_values,
482 disable_inventory => 1,
486 label => 'Communigate language',
488 select_list => [ '', qw( English Arabic Chinese Dutch French German Hebrew Italian Japanese Portuguese Russian Slovak Spanish Thai ) ],
489 disable_inventory => 1,
493 label => 'Communigate time zone',
495 select_list => __PACKAGE__->cgp_timezone_values,
496 disable_inventory => 1,
500 label => 'Communigate layout',
502 select_list => [ '', '***', 'GoldFleece', 'Skin2' ],
503 disable_inventory => 1,
506 'cgp_prontoskinname' => {
507 label => 'Communigate Pronto style',
509 select_list => [ '', 'Pronto', 'Pronto-darkflame', 'Pronto-steel', 'Pronto-twilight', ],
510 disable_inventory => 1,
513 'cgp_sendmdnmode' => {
514 label => 'Communigate send read receipts',
516 select_list => [ '', 'Never', 'Manually', 'Automatically' ],
517 disable_inventory => 1,
528 sub table { 'svc_acct'; }
530 sub table_dupcheck_fields { ( 'username', 'domsvc' ); }
534 #false laziness with edit/svc_acct.cgi
536 my( $self, $groups ) = @_;
537 if ( ref($groups) eq 'ARRAY' ) {
539 } elsif ( length($groups) ) {
540 [ split(/\s*,\s*/, $groups) ];
549 shift->_lastlog('in', @_);
553 shift->_lastlog('out', @_);
557 my( $self, $op, $time ) = @_;
559 if ( defined($time) ) {
560 warn "$me last_log$op called on svcnum ". $self->svcnum.
561 ' ('. $self->email. "): $time\n"
566 my $sql = "UPDATE svc_acct SET last_log$op = ? WHERE svcnum = ?";
570 my $sth = $dbh->prepare( $sql )
571 or die "Error preparing $sql: ". $dbh->errstr;
572 my $rv = $sth->execute($time, $self->svcnum);
573 die "Error executing $sql: ". $sth->errstr
575 die "Can't update last_log$op for svcnum". $self->svcnum
578 $self->{'Hash'}->{"last_log$op"} = $time;
580 $self->getfield("last_log$op");
584 =item search_sql STRING
586 Class method which returns an SQL fragment to search for the given string.
591 my( $class, $string ) = @_;
592 if ( $string =~ /^([^@]+)@([^@]+)$/ ) {
593 my( $username, $domain ) = ( $1, $2 );
594 my $q_username = dbh->quote($username);
595 my @svc_domain = qsearch('svc_domain', { 'domain' => $domain } );
597 "svc_acct.username = $q_username AND ( ".
598 join( ' OR ', map { "svc_acct.domsvc = ". $_->svcnum; } @svc_domain ).
603 } elsif ( $string =~ /^(\d{1,3}\.){3}\d{1,3}$/ ) {
605 $class->search_sql_field('slipip', $string ).
607 $class->search_sql_field('username', $string ).
610 $class->search_sql_field('username', $string);
614 =item label [ END_TIMESTAMP [ START_TIMESTAMP ] ]
616 Returns the "username@domain" string for this account.
618 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
628 =item label_long [ END_TIMESTAMP [ START_TIMESTAMP ] ]
630 Returns a longer string label for this acccount ("Real Name <username@domain>"
631 if available, or "username@domain").
633 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
640 my $label = $self->label(@_);
641 my $finger = $self->finger;
642 return $label unless $finger =~ /\S/;
643 my $maxlen = 40 - length($label) - length($self->cust_svc->part_svc->svc);
644 $finger = substr($finger, 0, $maxlen-3).'...' if length($finger) > $maxlen;
648 =item insert [ , OPTION => VALUE ... ]
650 Adds this account to the database. If there is an error, returns the error,
651 otherwise returns false.
653 The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be
654 defined. An FS::cust_svc record will be created and inserted.
656 The additional field I<usergroup> can optionally be defined; if so it should
657 contain an arrayref of group names. See L<FS::radius_usergroup>.
659 The additional field I<child_objects> can optionally be defined; if so it
660 should contain an arrayref of FS::tablename objects. They will have their
661 svcnum fields set and will be inserted after this record, but before any
662 exports are run. Each element of the array can also optionally be a
663 two-element array reference containing the child object and the name of an
664 alternate field to be filled in with the newly-inserted svcnum, for example
665 C<[ $svc_forward, 'srcsvc' ]>
667 Currently available options are: I<depend_jobnum>
669 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
670 jobnums), all provisioning jobs will have a dependancy on the supplied
671 jobnum(s) (they will not run until the specific job(s) complete(s)).
673 (TODOC: L<FS::queue> and L<freeside-queued>)
675 (TODOC: new exports!)
684 warn "[$me] insert called on $self: ". Dumper($self).
685 "\nwith options: ". Dumper(%options);
688 local $SIG{HUP} = 'IGNORE';
689 local $SIG{INT} = 'IGNORE';
690 local $SIG{QUIT} = 'IGNORE';
691 local $SIG{TERM} = 'IGNORE';
692 local $SIG{TSTP} = 'IGNORE';
693 local $SIG{PIPE} = 'IGNORE';
695 my $oldAutoCommit = $FS::UID::AutoCommit;
696 local $FS::UID::AutoCommit = 0;
700 my $error = $self->SUPER::insert(
701 'jobnums' => \@jobnums,
702 'child_objects' => $self->child_objects,
706 $dbh->rollback if $oldAutoCommit;
710 if ( $self->usergroup ) {
711 foreach my $groupname ( @{$self->usergroup} ) {
712 my $radius_usergroup = new FS::radius_usergroup ( {
713 svcnum => $self->svcnum,
714 groupname => $groupname,
716 my $error = $radius_usergroup->insert;
718 $dbh->rollback if $oldAutoCommit;
724 unless ( $skip_fuzzyfiles ) {
725 $error = $self->queue_fuzzyfiles_update;
727 $dbh->rollback if $oldAutoCommit;
728 return "updating fuzzy search cache: $error";
732 my $cust_pkg = $self->cust_svc->cust_pkg;
735 my $cust_main = $cust_pkg->cust_main;
736 my $agentnum = $cust_main->agentnum;
738 if ( $conf->exists('emailinvoiceautoalways')
739 || $conf->exists('emailinvoiceauto')
740 && ! $cust_main->invoicing_list_emailonly
742 my @invoicing_list = $cust_main->invoicing_list;
743 push @invoicing_list, $self->email;
744 $cust_main->invoicing_list(\@invoicing_list);
749 my $msgnum = $conf->config('welcome_msgnum', $agentnum);
751 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
752 $error = $msg_template->send('cust_main' => $cust_main);
755 my ($to,$welcome_template,$welcome_from,$welcome_subject,$welcome_subject_template,$welcome_mimetype)
756 = ('','','','','','');
758 if ( $conf->exists('welcome_email', $agentnum) ) {
759 $welcome_template = new Text::Template (
761 SOURCE => [ map "$_\n", $conf->config('welcome_email', $agentnum) ]
762 ) or warn "can't create welcome email template: $Text::Template::ERROR";
763 $welcome_from = $conf->config('welcome_email-from', $agentnum);
764 # || 'your-isp-is-dum'
765 $welcome_subject = $conf->config('welcome_email-subject', $agentnum)
767 $welcome_subject_template = new Text::Template (
769 SOURCE => $welcome_subject,
770 ) or warn "can't create welcome email subject template: $Text::Template::ERROR";
771 $welcome_mimetype = $conf->config('welcome_email-mimetype', $agentnum)
774 if ( $welcome_template ) {
775 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
779 'custnum' => $self->custnum,
780 'username' => $self->username,
781 'password' => $self->_password,
782 'first' => $cust_main->first,
783 'last' => $cust_main->getfield('last'),
784 'pkg' => $cust_pkg->part_pkg->pkg,
786 my $wqueue = new FS::queue {
787 'svcnum' => $self->svcnum,
788 'job' => 'FS::svc_acct::send_email'
790 my $error = $wqueue->insert(
792 'from' => $welcome_from,
793 'subject' => $welcome_subject_template->fill_in( HASH => \%hash, ),
794 'mimetype' => $welcome_mimetype,
795 'body' => $welcome_template->fill_in( HASH => \%hash, ),
798 $dbh->rollback if $oldAutoCommit;
799 return "error queuing welcome email: $error";
802 if ( $options{'depend_jobnum'} ) {
803 warn "$me depend_jobnum found; adding to welcome email dependancies"
805 if ( ref($options{'depend_jobnum'}) ) {
806 warn "$me adding jobs ". join(', ', @{$options{'depend_jobnum'}} ).
807 "to welcome email dependancies"
809 push @jobnums, @{ $options{'depend_jobnum'} };
811 warn "$me adding job $options{'depend_jobnum'} ".
812 "to welcome email dependancies"
814 push @jobnums, $options{'depend_jobnum'};
818 foreach my $jobnum ( @jobnums ) {
819 my $error = $wqueue->depend_insert($jobnum);
821 $dbh->rollback if $oldAutoCommit;
822 return "error queuing welcome email job dependancy: $error";
828 } # if $welcome_template
832 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
836 # set usage fields and thresholds if unset but set in a package def
837 # AND the package already has a last bill date (otherwise they get double added)
838 sub preinsert_hook_first {
841 return '' unless $self->pkgnum;
843 my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
844 return '' unless $cust_pkg && $cust_pkg->last_bill;
846 my $part_pkg = $cust_pkg->part_pkg;
847 return '' unless $part_pkg && $part_pkg->can('usage_valuehash');
849 my %values = $part_pkg->usage_valuehash;
850 my $multiplier = $conf->exists('svc_acct-usage_threshold')
851 ? 1 - $conf->config('svc_acct-usage_threshold')/100
852 : 0.20; #doesn't matter
854 foreach ( keys %values ) {
855 next if $self->getfield($_);
856 $self->setfield( $_, $values{$_} );
857 $self->setfield( $_. '_threshold', int( $values{$_} * $multiplier ) )
858 if $conf->exists('svc_acct-usage_threshold');
866 Deletes this account from the database. If there is an error, returns the
867 error, otherwise returns false.
869 The corresponding FS::cust_svc record will be deleted as well.
871 (TODOC: new exports!)
878 return "can't delete system account" if $self->_check_system;
880 return "Can't delete an account which is a (svc_forward) source!"
881 if qsearch( 'svc_forward', { 'srcsvc' => $self->svcnum } );
883 return "Can't delete an account which is a (svc_forward) destination!"
884 if qsearch( 'svc_forward', { 'dstsvc' => $self->svcnum } );
886 return "Can't delete an account with (svc_www) web service!"
887 if qsearch( 'svc_www', { 'usersvc' => $self->svcnum } );
889 # what about records in session ? (they should refer to history table)
891 local $SIG{HUP} = 'IGNORE';
892 local $SIG{INT} = 'IGNORE';
893 local $SIG{QUIT} = 'IGNORE';
894 local $SIG{TERM} = 'IGNORE';
895 local $SIG{TSTP} = 'IGNORE';
896 local $SIG{PIPE} = 'IGNORE';
898 my $oldAutoCommit = $FS::UID::AutoCommit;
899 local $FS::UID::AutoCommit = 0;
902 foreach my $cust_main_invoice (
903 qsearch( 'cust_main_invoice', { 'dest' => $self->svcnum } )
905 unless ( defined($cust_main_invoice) ) {
906 warn "WARNING: something's wrong with qsearch";
909 my %hash = $cust_main_invoice->hash;
910 $hash{'dest'} = $self->email;
911 my $new = new FS::cust_main_invoice \%hash;
912 my $error = $new->replace($cust_main_invoice);
914 $dbh->rollback if $oldAutoCommit;
919 foreach my $svc_domain (
920 qsearch( 'svc_domain', { 'catchall' => $self->svcnum } )
922 my %hash = new FS::svc_domain->hash;
923 $hash{'catchall'} = '';
924 my $new = new FS::svc_domain \%hash;
925 my $error = $new->replace($svc_domain);
927 $dbh->rollback if $oldAutoCommit;
932 my $error = $self->SUPER::delete;
934 $dbh->rollback if $oldAutoCommit;
938 foreach my $radius_usergroup (
939 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } )
941 my $error = $radius_usergroup->delete;
943 $dbh->rollback if $oldAutoCommit;
948 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
952 =item replace OLD_RECORD
954 Replaces OLD_RECORD with this one in the database. If there is an error,
955 returns the error, otherwise returns false.
957 The additional field I<usergroup> can optionally be defined; if so it should
958 contain an arrayref of group names. See L<FS::radius_usergroup>.
966 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
970 warn "$me replacing $old with $new\n" if $DEBUG;
974 return "can't modify system account" if $old->_check_system;
977 #no warnings 'numeric'; #alas, a 5.006-ism
980 foreach my $xid (qw( uid gid )) {
982 return "Can't change $xid!"
983 if ! $conf->exists("svc_acct-edit_$xid")
984 && $old->$xid() != $new->$xid()
985 && $new->cust_svc->part_svc->part_svc_column($xid)->columnflag ne 'F'
990 #change homdir when we change username
991 $new->setfield('dir', '') if $old->username ne $new->username;
993 local $SIG{HUP} = 'IGNORE';
994 local $SIG{INT} = 'IGNORE';
995 local $SIG{QUIT} = 'IGNORE';
996 local $SIG{TERM} = 'IGNORE';
997 local $SIG{TSTP} = 'IGNORE';
998 local $SIG{PIPE} = 'IGNORE';
1000 my $oldAutoCommit = $FS::UID::AutoCommit;
1001 local $FS::UID::AutoCommit = 0;
1004 # redundant, but so $new->usergroup gets set
1005 $error = $new->check;
1006 return $error if $error;
1008 $old->usergroup( [ $old->radius_groups ] );
1010 warn $old->email. " old groups: ". join(' ',@{$old->usergroup}). "\n";
1011 warn $new->email. "new groups: ". join(' ',@{$new->usergroup}). "\n";
1013 if ( $new->usergroup ) {
1014 #(sorta) false laziness with FS::part_export::sqlradius::_export_replace
1015 my @newgroups = @{$new->usergroup};
1016 foreach my $oldgroup ( @{$old->usergroup} ) {
1017 if ( grep { $oldgroup eq $_ } @newgroups ) {
1018 @newgroups = grep { $oldgroup ne $_ } @newgroups;
1021 my $radius_usergroup = qsearchs('radius_usergroup', {
1022 svcnum => $old->svcnum,
1023 groupname => $oldgroup,
1025 my $error = $radius_usergroup->delete;
1027 $dbh->rollback if $oldAutoCommit;
1028 return "error deleting radius_usergroup $oldgroup: $error";
1032 foreach my $newgroup ( @newgroups ) {
1033 my $radius_usergroup = new FS::radius_usergroup ( {
1034 svcnum => $new->svcnum,
1035 groupname => $newgroup,
1037 my $error = $radius_usergroup->insert;
1039 $dbh->rollback if $oldAutoCommit;
1040 return "error adding radius_usergroup $newgroup: $error";
1046 $error = $new->SUPER::replace($old, @_);
1048 $dbh->rollback if $oldAutoCommit;
1049 return $error if $error;
1052 if ( $new->username ne $old->username && ! $skip_fuzzyfiles ) {
1053 $error = $new->queue_fuzzyfiles_update;
1055 $dbh->rollback if $oldAutoCommit;
1056 return "updating fuzzy search cache: $error";
1060 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1064 =item queue_fuzzyfiles_update
1066 Used by insert & replace to update the fuzzy search cache
1070 sub queue_fuzzyfiles_update {
1073 local $SIG{HUP} = 'IGNORE';
1074 local $SIG{INT} = 'IGNORE';
1075 local $SIG{QUIT} = 'IGNORE';
1076 local $SIG{TERM} = 'IGNORE';
1077 local $SIG{TSTP} = 'IGNORE';
1078 local $SIG{PIPE} = 'IGNORE';
1080 my $oldAutoCommit = $FS::UID::AutoCommit;
1081 local $FS::UID::AutoCommit = 0;
1084 my $queue = new FS::queue {
1085 'svcnum' => $self->svcnum,
1086 'job' => 'FS::svc_acct::append_fuzzyfiles'
1088 my $error = $queue->insert($self->username);
1090 $dbh->rollback if $oldAutoCommit;
1091 return "queueing job (transaction rolled back): $error";
1094 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1102 Suspends this account by calling export-specific suspend hooks. If there is
1103 an error, returns the error, otherwise returns false.
1105 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1111 return "can't suspend system account" if $self->_check_system;
1112 $self->SUPER::suspend(@_);
1117 Unsuspends this account by by calling export-specific suspend hooks. If there
1118 is an error, returns the error, otherwise returns false.
1120 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1126 my %hash = $self->hash;
1127 if ( $hash{_password} =~ /^\*SUSPENDED\* (.*)$/ ) {
1128 $hash{_password} = $1;
1129 my $new = new FS::svc_acct ( \%hash );
1130 my $error = $new->replace($self);
1131 return $error if $error;
1134 $self->SUPER::unsuspend(@_);
1139 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
1141 If the B<auto_unset_catchall> configuration option is set, this method will
1142 automatically remove any references to the canceled service in the catchall
1143 field of svc_domain. This allows packages that contain both a svc_domain and
1144 its catchall svc_acct to be canceled in one step.
1149 # Only one thing to do at this level
1151 foreach my $svc_domain (
1152 qsearch( 'svc_domain', { catchall => $self->svcnum } ) ) {
1153 if($conf->exists('auto_unset_catchall')) {
1154 my %hash = $svc_domain->hash;
1155 $hash{catchall} = '';
1156 my $new = new FS::svc_domain ( \%hash );
1157 my $error = $new->replace($svc_domain);
1158 return $error if $error;
1160 return "cannot unprovision svc_acct #".$self->svcnum.
1161 " while assigned as catchall for svc_domain #".$svc_domain->svcnum;
1165 $self->SUPER::cancel(@_);
1171 Checks all fields to make sure this is a valid service. If there is an error,
1172 returns the error, otherwise returns false. Called by the insert and replace
1175 Sets any fixed values; see L<FS::part_svc>.
1182 my($recref) = $self->hashref;
1184 my $x = $self->setfixed( $self->_fieldhandlers );
1185 return $x unless ref($x);
1188 if ( $part_svc->part_svc_column('usergroup')->columnflag eq "F" ) {
1190 [ split(',', $part_svc->part_svc_column('usergroup')->columnvalue) ] );
1193 my $error = $self->ut_numbern('svcnum')
1194 #|| $self->ut_number('domsvc')
1195 || $self->ut_foreign_key( 'domsvc', 'svc_domain', 'svcnum' )
1196 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
1197 || $self->ut_textn('sec_phrase')
1198 || $self->ut_snumbern('seconds')
1199 || $self->ut_snumbern('upbytes')
1200 || $self->ut_snumbern('downbytes')
1201 || $self->ut_snumbern('totalbytes')
1202 || $self->ut_snumbern('seconds_threshold')
1203 || $self->ut_snumbern('upbytes_threshold')
1204 || $self->ut_snumbern('downbytes_threshold')
1205 || $self->ut_snumbern('totalbytes_threshold')
1206 || $self->ut_enum('_password_encoding', ['',qw(plain crypt ldap)])
1207 || $self->ut_enum('password_selfchange', [ '', 'Y' ])
1208 || $self->ut_enum('password_recover', [ '', 'Y' ])
1209 || $self->ut_textn('cgp_accessmodes')
1210 || $self->ut_alphan('cgp_type')
1211 || $self->ut_textn('cgp_aliases' ) #well
1213 || $self->ut_alphasn('cgp_rulesallowed')
1214 || $self->ut_enum('cgp_rpopallowed', [ '', 'Y' ])
1215 || $self->ut_enum('cgp_mailtoall', [ '', 'Y' ])
1216 || $self->ut_enum('cgp_addmailtrailer', [ '', 'Y' ])
1217 || $self->ut_snumbern('cgp_archiveafter')
1219 || $self->ut_alphasn('cgp_deletemode')
1220 || $self->ut_enum('cgp_emptytrash', $self->cgp_emptytrash_values)
1221 || $self->ut_alphan('cgp_language')
1222 || $self->ut_textn('cgp_timezone')
1223 || $self->ut_textn('cgp_skinname')
1224 || $self->ut_textn('cgp_prontoskinname')
1225 || $self->ut_alphan('cgp_sendmdnmode')
1228 return $error if $error;
1231 local $username_letter = $username_letter;
1232 if ($self->svcnum) {
1233 my $cust_svc = $self->cust_svc
1234 or return "no cust_svc record found for svcnum ". $self->svcnum;
1235 my $cust_pkg = $cust_svc->cust_pkg;
1237 if ($self->pkgnum) {
1238 $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $self->pkgnum } );#complain?
1242 $conf->exists('username-letter', $cust_pkg->cust_main->agentnum);
1245 my $ulen = $usernamemax || $self->dbdef_table->column('username')->length;
1247 $recref->{username} =~ /^([a-z0-9_\-\.\&\%\:\/\=]{$usernamemin,$ulen})$/i
1248 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
1249 $recref->{username} = $1;
1251 unless ( $username_uppercase ) {
1252 $recref->{username} =~ /[A-Z]/ and return gettext('illegal_username');
1254 if ( $username_letterfirst ) {
1255 $recref->{username} =~ /^[a-z]/ or return gettext('illegal_username');
1256 } elsif ( $username_letter ) {
1257 $recref->{username} =~ /[a-z]/ or return gettext('illegal_username');
1259 if ( $username_noperiod ) {
1260 $recref->{username} =~ /\./ and return gettext('illegal_username');
1262 if ( $username_nounderscore ) {
1263 $recref->{username} =~ /_/ and return gettext('illegal_username');
1265 if ( $username_nodash ) {
1266 $recref->{username} =~ /\-/ and return gettext('illegal_username');
1268 unless ( $username_ampersand ) {
1269 $recref->{username} =~ /\&/ and return gettext('illegal_username');
1271 unless ( $username_percent ) {
1272 $recref->{username} =~ /\%/ and return gettext('illegal_username');
1274 unless ( $username_colon ) {
1275 $recref->{username} =~ /\:/ and return gettext('illegal_username');
1277 unless ( $username_slash ) {
1278 $recref->{username} =~ /\// and return gettext('illegal_username');
1280 unless ( $username_equals ) {
1281 $recref->{username} =~ /\=/ and return gettext('illegal_username');
1284 $recref->{popnum} =~ /^(\d*)$/ or return "Illegal popnum: ".$recref->{popnum};
1285 $recref->{popnum} = $1;
1286 return "Unknown popnum" unless
1287 ! $recref->{popnum} ||
1288 qsearchs('svc_acct_pop',{'popnum'=> $recref->{popnum} } );
1290 unless ( $part_svc->part_svc_column('uid')->columnflag eq 'F' ) {
1292 $recref->{uid} =~ /^(\d*)$/ or return "Illegal uid";
1293 $recref->{uid} = $1 eq '' ? $self->unique('uid') : $1;
1295 $recref->{gid} =~ /^(\d*)$/ or return "Illegal gid";
1296 $recref->{gid} = $1 eq '' ? $recref->{uid} : $1;
1297 #not all systems use gid=uid
1298 #you can set a fixed gid in part_svc
1300 return "Only root can have uid 0"
1301 if $recref->{uid} == 0
1302 && $recref->{username} !~ /^(root|toor|smtp)$/;
1304 unless ( $recref->{username} eq 'sync' ) {
1305 if ( grep $_ eq $recref->{shell}, @shells ) {
1306 $recref->{shell} = (grep $_ eq $recref->{shell}, @shells)[0];
1308 return "Illegal shell \`". $self->shell. "\'; ".
1309 "shells configuration value contains: @shells";
1312 $recref->{shell} = '/bin/sync';
1316 $recref->{gid} ne '' ?
1317 return "Can't have gid without uid" : ( $recref->{gid}='' );
1318 #$recref->{dir} ne '' ?
1319 # return "Can't have directory without uid" : ( $recref->{dir}='' );
1320 $recref->{shell} ne '' ?
1321 return "Can't have shell without uid" : ( $recref->{shell}='' );
1324 unless ( $part_svc->part_svc_column('dir')->columnflag eq 'F' ) {
1326 $recref->{dir} =~ /^([\/\w\-\.\&]*)$/
1327 or return "Illegal directory: ". $recref->{dir};
1328 $recref->{dir} = $1;
1329 return "Illegal directory"
1330 if $recref->{dir} =~ /(^|\/)\.+(\/|$)/; #no .. component
1331 return "Illegal directory"
1332 if $recref->{dir} =~ /\&/ && ! $username_ampersand;
1333 unless ( $recref->{dir} ) {
1334 $recref->{dir} = $dir_prefix . '/';
1335 if ( $dirhash > 0 ) {
1336 for my $h ( 1 .. $dirhash ) {
1337 $recref->{dir} .= substr($recref->{username}, $h-1, 1). '/';
1339 } elsif ( $dirhash < 0 ) {
1340 for my $h ( reverse $dirhash .. -1 ) {
1341 $recref->{dir} .= substr($recref->{username}, $h, 1). '/';
1344 $recref->{dir} .= $recref->{username};
1350 # $error = $self->ut_textn('finger');
1351 # return $error if $error;
1352 if ( $self->getfield('finger') eq '' ) {
1353 my $cust_pkg = $self->svcnum
1354 ? $self->cust_svc->cust_pkg
1355 : qsearchs('cust_pkg', { 'pkgnum' => $self->getfield('pkgnum') } );
1357 my $cust_main = $cust_pkg->cust_main;
1358 $self->setfield('finger', $cust_main->first.' '.$cust_main->get('last') );
1361 $self->getfield('finger') =~
1362 /^([µ_0123456789aAáÁàÀâÂåÅäÄãêæÆbBcCçÇdDðÐeEéÉèÈêÊëËfFgGhHiIíÍìÌîÎïÏjJkKlLmMnNñÑoOóÓòÒôÔöÖõÕøغpPqQrRsSßtTuUúÚùÙûÛüÜvVwWxXyYýÝÿzZþÞ \t\!\@\#\$\%\&\(\)\-\+\;\'\"\,\.\?\/\*\<\>]*)$/
1363 or return "Illegal finger: ". $self->getfield('finger');
1364 $self->setfield('finger', $1);
1366 for (qw( quota file_quota file_maxsize )) {
1367 $recref->{$_} =~ /^(\w*)$/ or return "Illegal $_";
1370 $recref->{file_maxnum} =~ /^\s*(\d*)\s*$/ or return "Illegal file_maxnum";
1371 $recref->{file_maxnum} = $1;
1373 unless ( $part_svc->part_svc_column('slipip')->columnflag eq 'F' ) {
1374 if ( $recref->{slipip} eq '' ) {
1375 $recref->{slipip} = '';
1376 } elsif ( $recref->{slipip} eq '0e0' ) {
1377 $recref->{slipip} = '0e0';
1379 $recref->{slipip} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/
1380 or return "Illegal slipip: ". $self->slipip;
1381 $recref->{slipip} = $1;
1386 #arbitrary RADIUS stuff; allow ut_textn for now
1387 foreach ( grep /^radius_/, fields('svc_acct') ) {
1388 $self->ut_textn($_);
1391 # First, if _password is blank, generate one and set default encoding.
1392 if ( ! $recref->{_password} ) {
1393 $error = $self->set_password('');
1395 # But if there's a _password but no encoding, assume it's plaintext and
1396 # set it to default encoding.
1397 elsif ( ! $recref->{_password_encoding} ) {
1398 $error = $self->set_password($recref->{_password});
1400 return $error if $error;
1402 # Next, check _password to ensure compliance with the encoding.
1403 if ( $recref->{_password_encoding} eq 'ldap' ) {
1405 if ( $recref->{_password} =~ /^(\{[\w\-]+\})(!?.{0,64})$/ ) {
1406 $recref->{_password} = uc($1).$2;
1408 return 'Illegal (ldap-encoded) password: '. $recref->{_password};
1411 } elsif ( $recref->{_password_encoding} eq 'crypt' ) {
1413 if ( $recref->{_password} =~
1414 #/^(\$\w+\$.*|[\w\+\/]{13}|_[\w\+\/]{19}|\*)$/
1415 /^(!!?)?(\$\w+\$.*|[\w\+\/\.]{13}|_[\w\+\/\.]{19}|\*)$/
1418 $recref->{_password} = ( defined($1) ? $1 : '' ). $2;
1421 return 'Illegal (crypt-encoded) password: '. $recref->{_password};
1424 } elsif ( $recref->{_password_encoding} eq 'plain' ) {
1425 # Password randomization is now in set_password.
1426 # Strip whitespace characters, check length requirements, etc.
1427 if ( $recref->{_password} =~ /^([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1428 $recref->{_password} = $1;
1430 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1431 FS::Msgcat::_gettext('illegal_password_characters').
1432 ": ". $recref->{_password};
1435 if ( $password_noampersand ) {
1436 $recref->{_password} =~ /\&/ and return gettext('illegal_password');
1438 if ( $password_noexclamation ) {
1439 $recref->{_password} =~ /\!/ and return gettext('illegal_password');
1443 return "invalid password encoding ('".$recref->{_password_encoding}."'";
1445 $self->SUPER::check;
1450 sub _password_encryption {
1452 my $encoding = lc($self->_password_encoding);
1453 return if !$encoding;
1454 return 'plain' if $encoding eq 'plain';
1455 if($encoding eq 'crypt') {
1456 my $pass = $self->_password;
1457 $pass =~ s/^\*SUSPENDED\* //;
1459 return 'md5' if $pass =~ /^\$1\$/;
1460 #return 'blowfish' if $self->_password =~ /^\$2\$/;
1461 return 'des' if length($pass) == 13;
1464 if($encoding eq 'ldap') {
1465 uc($self->_password) =~ /^\{([\w-]+)\}/;
1466 return 'crypt' if $1 eq 'CRYPT' or $1 eq 'DES';
1467 return 'plain' if $1 eq 'PLAIN' or $1 eq 'CLEARTEXT';
1468 return 'md5' if $1 eq 'MD5';
1469 return 'sha1' if $1 eq 'SHA' or $1 eq 'SHA-1';
1476 sub get_cleartext_password {
1478 if($self->_password_encryption eq 'plain') {
1479 if($self->_password_encoding eq 'ldap') {
1480 $self->_password =~ /\{\w+\}(.*)$/;
1484 return $self->_password;
1493 Set the cleartext password for the account. If _password_encoding is set, the
1494 new password will be encoded according to the existing method (including
1495 encryption mode, if it can be determined). Otherwise,
1496 config('default-password-encoding') is used.
1498 If no password is supplied (or a zero-length password when minimum password length
1499 is >0), one will be generated randomly.
1504 my( $self, $pass ) = ( shift, shift );
1506 warn "[$me] set_password (to $pass) called on $self: ". Dumper($self)
1509 my $failure = gettext('illegal_password'). " $passwordmin-$passwordmax ".
1510 FS::Msgcat::_gettext('illegal_password_characters').
1513 my( $encoding, $encryption ) = ('', '');
1515 if ( $self->_password_encoding ) {
1516 $encoding = $self->_password_encoding;
1517 # identify existing encryption method, try to use it.
1518 $encryption = $self->_password_encryption;
1520 # use the system default
1526 # set encoding to system default
1527 ($encoding, $encryption) =
1528 split(/-/, lc($conf->config('default-password-encoding')));
1529 $encoding ||= 'legacy';
1530 $self->_password_encoding($encoding);
1533 if ( $encoding eq 'legacy' ) {
1535 # The legacy behavior from check():
1536 # If the password is blank, randomize it and set encoding to 'plain'.
1537 if(!defined($pass) or (length($pass) == 0 and $passwordmin)) {
1538 $pass = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1539 $self->_password_encoding('plain');
1541 # Prefix + valid-length password
1542 if ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1544 $self->_password_encoding('plain');
1545 # Prefix + crypt string
1546 } elsif ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([\w\.\/\$\;\+]{13,64})$/ ) {
1548 $self->_password_encoding('crypt');
1549 # Various disabled crypt passwords
1550 } elsif ( $pass eq '*' || $pass eq '!' || $pass eq '!!' ) {
1551 $self->_password_encoding('crypt');
1557 $self->_password($pass);
1563 if $passwordmin && length($pass) < $passwordmin
1564 or $passwordmax && length($pass) > $passwordmax;
1566 if ( $encoding eq 'crypt' ) {
1567 if ($encryption eq 'md5') {
1568 $pass = unix_md5_crypt($pass);
1569 } elsif ($encryption eq 'des') {
1570 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1573 } elsif ( $encoding eq 'ldap' ) {
1574 if ($encryption eq 'md5') {
1575 $pass = md5_base64($pass);
1576 } elsif ($encryption eq 'sha1') {
1577 $pass = sha1_base64($pass);
1578 } elsif ($encryption eq 'crypt') {
1579 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1581 # else $encryption eq 'plain', do nothing
1582 $pass = '{'.uc($encryption).'}'.$pass;
1584 # else encoding eq 'plain'
1586 $self->_password($pass);
1592 Internal function to check the username against the list of system usernames
1593 from the I<system_usernames> configuration value. Returns true if the username
1594 is listed on the system username list.
1600 scalar( grep { $self->username eq $_ || $self->email eq $_ }
1601 $conf->config('system_usernames')
1605 =item _check_duplicate
1607 Internal method to check for duplicates usernames, username@domain pairs and
1610 If the I<global_unique-username> configuration value is set to B<username> or
1611 B<username@domain>, enforces global username or username@domain uniqueness.
1613 In all cases, check for duplicate uids and usernames or username@domain pairs
1614 per export and with identical I<svcpart> values.
1618 sub _check_duplicate {
1621 my $global_unique = $conf->config('global_unique-username') || 'none';
1622 return '' if $global_unique eq 'disabled';
1626 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
1627 unless ( $part_svc ) {
1628 return 'unknown svcpart '. $self->svcpart;
1631 my @dup_user = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1632 qsearch( 'svc_acct', { 'username' => $self->username } );
1633 return gettext('username_in_use')
1634 if $global_unique eq 'username' && @dup_user;
1636 my @dup_userdomain = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1637 qsearch( 'svc_acct', { 'username' => $self->username,
1638 'domsvc' => $self->domsvc } );
1639 return gettext('username_in_use')
1640 if $global_unique eq 'username@domain' && @dup_userdomain;
1643 if ( $part_svc->part_svc_column('uid')->columnflag ne 'F'
1644 && $self->username !~ /^(toor|(hyla)?fax)$/ ) {
1645 @dup_uid = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1646 qsearch( 'svc_acct', { 'uid' => $self->uid } );
1651 if ( @dup_user || @dup_userdomain || @dup_uid ) {
1652 my $exports = FS::part_export::export_info('svc_acct');
1653 my %conflict_user_svcpart;
1654 my %conflict_userdomain_svcpart = ( $self->svcpart => 'SELF', );
1656 foreach my $part_export ( $part_svc->part_export ) {
1658 #this will catch to the same exact export
1659 my @svcparts = map { $_->svcpart } $part_export->export_svc;
1661 #this will catch to exports w/same exporthost+type ???
1662 #my @other_part_export = qsearch('part_export', {
1663 # 'machine' => $part_export->machine,
1664 # 'exporttype' => $part_export->exporttype,
1666 #foreach my $other_part_export ( @other_part_export ) {
1667 # push @svcparts, map { $_->svcpart }
1668 # qsearch('export_svc', { 'exportnum' => $part_export->exportnum });
1671 #my $nodomain = $exports->{$part_export->exporttype}{'nodomain'};
1672 #silly kludge to avoid uninitialized value errors
1673 my $nodomain = exists( $exports->{$part_export->exporttype}{'nodomain'} )
1674 ? $exports->{$part_export->exporttype}{'nodomain'}
1676 if ( $nodomain =~ /^Y/i ) {
1677 $conflict_user_svcpart{$_} = $part_export->exportnum
1680 $conflict_userdomain_svcpart{$_} = $part_export->exportnum
1685 foreach my $dup_user ( @dup_user ) {
1686 my $dup_svcpart = $dup_user->cust_svc->svcpart;
1687 if ( exists($conflict_user_svcpart{$dup_svcpart}) ) {
1688 return "duplicate username ". $self->username.
1689 ": conflicts with svcnum ". $dup_user->svcnum.
1690 " via exportnum ". $conflict_user_svcpart{$dup_svcpart};
1694 foreach my $dup_userdomain ( @dup_userdomain ) {
1695 my $dup_svcpart = $dup_userdomain->cust_svc->svcpart;
1696 if ( exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1697 return "duplicate username\@domain ". $self->email.
1698 ": conflicts with svcnum ". $dup_userdomain->svcnum.
1699 " via exportnum ". $conflict_userdomain_svcpart{$dup_svcpart};
1703 foreach my $dup_uid ( @dup_uid ) {
1704 my $dup_svcpart = $dup_uid->cust_svc->svcpart;
1705 if ( exists($conflict_user_svcpart{$dup_svcpart})
1706 || exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1707 return "duplicate uid ". $self->uid.
1708 ": conflicts with svcnum ". $dup_uid->svcnum.
1710 ( $conflict_user_svcpart{$dup_svcpart}
1711 || $conflict_userdomain_svcpart{$dup_svcpart} );
1723 Depriciated, use radius_reply instead.
1728 carp "FS::svc_acct::radius depriciated, use radius_reply";
1729 $_[0]->radius_reply;
1734 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1735 reply attributes of this record.
1737 Note that this is now the preferred method for reading RADIUS attributes -
1738 accessing the columns directly is discouraged, as the column names are
1739 expected to change in the future.
1746 return %{ $self->{'radius_reply'} }
1747 if exists $self->{'radius_reply'};
1752 my($column, $attrib) = ($1, $2);
1753 #$attrib =~ s/_/\-/g;
1754 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1755 } grep { /^radius_/ && $self->getfield($_) } fields( $self->table );
1757 if ( $self->slipip && $self->slipip ne '0e0' ) {
1758 $reply{$radius_ip} = $self->slipip;
1761 if ( $self->seconds !~ /^$/ ) {
1762 $reply{'Session-Timeout'} = $self->seconds;
1765 if ( $conf->exists('radius-chillispot-max') ) {
1766 #http://dev.coova.org/svn/coova-chilli/doc/dictionary.chillispot
1768 #hmm. just because sqlradius.pm says so?
1775 foreach my $what (qw( input output total )) {
1776 my $is = $whatis{$what}.'bytes';
1777 if ( $self->$is() =~ /\d/ ) {
1778 my $big = new Math::BigInt $self->$is();
1779 $big = new Math::BigInt '0' if $big->is_neg();
1780 my $att = "Chillispot-Max-\u$what";
1781 $reply{"$att-Octets"} = $big->copy->band(0xffffffff)->bstr;
1782 $reply{"$att-Gigawords"} = $big->copy->brsft(32)->bstr;
1793 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1794 check attributes of this record.
1796 Note that this is now the preferred method for reading RADIUS attributes -
1797 accessing the columns directly is discouraged, as the column names are
1798 expected to change in the future.
1805 return %{ $self->{'radius_check'} }
1806 if exists $self->{'radius_check'};
1811 my($column, $attrib) = ($1, $2);
1812 #$attrib =~ s/_/\-/g;
1813 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1814 } grep { /^rc_/ && $self->getfield($_) } fields( $self->table );
1817 my($pw_attrib, $password) = $self->radius_password;
1818 $check{$pw_attrib} = $password;
1820 my $cust_svc = $self->cust_svc;
1822 my $cust_pkg = $cust_svc->cust_pkg;
1823 if ( $cust_pkg && $cust_pkg->part_pkg->is_prepaid && $cust_pkg->bill ) {
1824 $check{'Expiration'} = time2str('%B %e %Y %T', $cust_pkg->bill ); #http://lists.cistron.nl/pipermail/freeradius-users/2005-January/040184.html
1827 warn "WARNING: no cust_svc record for svc_acct.svcnum ". $self->svcnum.
1828 "; can't set Expiration\n"
1836 =item radius_password
1838 Returns a key/value pair containing the RADIUS attribute name and value
1843 sub radius_password {
1847 if ( $self->_password_encoding eq 'ldap' ) {
1848 $pw_attrib = 'Password-With-Header';
1849 } elsif ( $self->_password_encoding eq 'crypt' ) {
1850 $pw_attrib = 'Crypt-Password';
1851 } elsif ( $self->_password_encoding eq 'plain' ) {
1852 $pw_attrib = $radius_password;
1854 $pw_attrib = length($self->_password) <= 12
1859 ($pw_attrib, $self->_password);
1865 This method instructs the object to "snapshot" or freeze RADIUS check and
1866 reply attributes to the current values.
1870 #bah, my english is too broken this morning
1871 #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
1872 #the FS::cust_pkg's replace method to trigger the correct export updates when
1873 #package dates change)
1878 $self->{$_} = { $self->$_() }
1879 foreach qw( radius_reply radius_check );
1883 =item forget_snapshot
1885 This methos instructs the object to forget any previously snapshotted
1886 RADIUS check and reply attributes.
1890 sub forget_snapshot {
1894 foreach qw( radius_reply radius_check );
1898 =item domain [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1900 Returns the domain associated with this account.
1902 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1909 die "svc_acct.domsvc is null for svcnum ". $self->svcnum unless $self->domsvc;
1910 my $svc_domain = $self->svc_domain(@_)
1911 or die "no svc_domain.svcnum for svc_acct.domsvc ". $self->domsvc;
1912 $svc_domain->domain;
1917 Returns the FS::cust_svc record for this account (see L<FS::cust_svc>).
1921 #inherited from svc_Common
1923 =item email [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1925 Returns an email address associated with the account.
1927 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1934 $self->username. '@'. $self->domain(@_);
1939 Returns an array of FS::acct_snarf records associated with the account.
1946 'table' => 'acct_snarf',
1947 'hashref' => { 'svcnum' => $self->svcnum },
1948 #'order_by' => 'ORDER BY priority ASC',
1952 =item cgp_rpop_hashref
1954 Returns an arrayref of RPOP data suitable for Communigate Pro API commands.
1958 sub cgp_rpop_hashref {
1960 { map { $_->snarfname => $_->cgp_hashref } $self->acct_snarf };
1963 =item decrement_upbytes OCTETS
1965 Decrements the I<upbytes> field of this record by the given amount. If there
1966 is an error, returns the error, otherwise returns false.
1970 sub decrement_upbytes {
1971 shift->_op_usage('-', 'upbytes', @_);
1974 =item increment_upbytes OCTETS
1976 Increments 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 increment_upbytes {
1982 shift->_op_usage('+', 'upbytes', @_);
1985 =item decrement_downbytes OCTETS
1987 Decrements the I<downbytes> field of this record by the given amount. If there
1988 is an error, returns the error, otherwise returns false.
1992 sub decrement_downbytes {
1993 shift->_op_usage('-', 'downbytes', @_);
1996 =item increment_downbytes OCTETS
1998 Increments 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 increment_downbytes {
2004 shift->_op_usage('+', 'downbytes', @_);
2007 =item decrement_totalbytes OCTETS
2009 Decrements the I<totalbytes> field of this record by the given amount. If there
2010 is an error, returns the error, otherwise returns false.
2014 sub decrement_totalbytes {
2015 shift->_op_usage('-', 'totalbytes', @_);
2018 =item increment_totalbytes OCTETS
2020 Increments 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 increment_totalbytes {
2026 shift->_op_usage('+', 'totalbytes', @_);
2029 =item decrement_seconds SECONDS
2031 Decrements the I<seconds> field of this record by the given amount. If there
2032 is an error, returns the error, otherwise returns false.
2036 sub decrement_seconds {
2037 shift->_op_usage('-', 'seconds', @_);
2040 =item increment_seconds SECONDS
2042 Increments 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 increment_seconds {
2048 shift->_op_usage('+', 'seconds', @_);
2056 my %op2condition = (
2057 '-' => sub { my($self, $column, $amount) = @_;
2058 $self->$column - $amount <= 0;
2060 '+' => sub { my($self, $column, $amount) = @_;
2061 ($self->$column || 0) + $amount > 0;
2064 my %op2warncondition = (
2065 '-' => sub { my($self, $column, $amount) = @_;
2066 my $threshold = $column . '_threshold';
2067 $self->$column - $amount <= $self->$threshold + 0;
2069 '+' => sub { my($self, $column, $amount) = @_;
2070 ($self->$column || 0) + $amount > 0;
2075 my( $self, $op, $column, $amount ) = @_;
2077 warn "$me _op_usage called for $column on svcnum ". $self->svcnum.
2078 ' ('. $self->email. "): $op $amount\n"
2081 return '' unless $amount;
2083 local $SIG{HUP} = 'IGNORE';
2084 local $SIG{INT} = 'IGNORE';
2085 local $SIG{QUIT} = 'IGNORE';
2086 local $SIG{TERM} = 'IGNORE';
2087 local $SIG{TSTP} = 'IGNORE';
2088 local $SIG{PIPE} = 'IGNORE';
2090 my $oldAutoCommit = $FS::UID::AutoCommit;
2091 local $FS::UID::AutoCommit = 0;
2094 my $sql = "UPDATE svc_acct SET $column = ".
2095 " CASE WHEN $column IS NULL THEN 0 ELSE $column END ". #$column||0
2096 " $op ? WHERE svcnum = ?";
2100 my $sth = $dbh->prepare( $sql )
2101 or die "Error preparing $sql: ". $dbh->errstr;
2102 my $rv = $sth->execute($amount, $self->svcnum);
2103 die "Error executing $sql: ". $sth->errstr
2104 unless defined($rv);
2105 die "Can't update $column for svcnum". $self->svcnum
2108 #$self->snapshot; #not necessary, we retain the old values
2109 #create an object with the updated usage values
2110 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2112 my $error = $new->replace($self);
2114 $dbh->rollback if $oldAutoCommit;
2115 return "Error replacing: $error";
2118 #overlimit_action eq 'cancel' handling
2119 my $cust_pkg = $self->cust_svc->cust_pkg;
2121 && $cust_pkg->part_pkg->option('overlimit_action', 1) eq 'cancel'
2122 && $op eq '-' && &{$op2condition{$op}}($self, $column, $amount)
2126 my $error = $cust_pkg->cancel; #XXX should have a reason
2128 $dbh->rollback if $oldAutoCommit;
2129 return "Error cancelling: $error";
2132 #nothing else is relevant if we're cancelling, so commit & return success
2133 warn "$me update successful; committing\n"
2135 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2140 my $action = $op2action{$op};
2142 if ( &{$op2condition{$op}}($self, $column, $amount) &&
2143 ( $action eq 'suspend' && !$self->overlimit
2144 || $action eq 'unsuspend' && $self->overlimit )
2147 my $error = $self->_op_overlimit($action);
2149 $dbh->rollback if $oldAutoCommit;
2155 if ( $conf->exists("svc_acct-usage_$action")
2156 && &{$op2condition{$op}}($self, $column, $amount) ) {
2157 #my $error = $self->$action();
2158 my $error = $self->cust_svc->cust_pkg->$action();
2159 # $error ||= $self->overlimit($action);
2161 $dbh->rollback if $oldAutoCommit;
2162 return "Error ${action}ing: $error";
2166 if ($warning_template && &{$op2warncondition{$op}}($self, $column, $amount)) {
2167 my $wqueue = new FS::queue {
2168 'svcnum' => $self->svcnum,
2169 'job' => 'FS::svc_acct::reached_threshold',
2174 $to = $warning_cc if &{$op2condition{$op}}($self, $column, $amount);
2178 my $error = $wqueue->insert(
2179 'svcnum' => $self->svcnum,
2181 'column' => $column,
2185 $dbh->rollback if $oldAutoCommit;
2186 return "Error queuing threshold activity: $error";
2190 warn "$me update successful; committing\n"
2192 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2198 my( $self, $action ) = @_;
2200 local $SIG{HUP} = 'IGNORE';
2201 local $SIG{INT} = 'IGNORE';
2202 local $SIG{QUIT} = 'IGNORE';
2203 local $SIG{TERM} = 'IGNORE';
2204 local $SIG{TSTP} = 'IGNORE';
2205 local $SIG{PIPE} = 'IGNORE';
2207 my $oldAutoCommit = $FS::UID::AutoCommit;
2208 local $FS::UID::AutoCommit = 0;
2211 my $cust_pkg = $self->cust_svc->cust_pkg;
2213 my $conf_overlimit =
2215 ? $conf->config('overlimit_groups', $cust_pkg->cust_main->agentnum )
2216 : $conf->config('overlimit_groups');
2218 foreach my $part_export ( $self->cust_svc->part_svc->part_export ) {
2220 my $groups = $conf_overlimit || $part_export->option('overlimit_groups');
2221 next unless $groups;
2223 my $gref = &{ $self->_fieldhandlers->{'usergroup'} }( $self, $groups );
2225 my $other = new FS::svc_acct $self->hashref;
2226 $other->usergroup( $gref );
2229 if ($action eq 'suspend') {
2232 } else { # $action eq 'unsuspend'
2237 my $error = $part_export->export_replace($new, $old)
2238 || $self->overlimit($action);
2241 $dbh->rollback if $oldAutoCommit;
2242 return "Error replacing radius groups: $error";
2247 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2253 my( $self, $valueref, %options ) = @_;
2255 warn "$me set_usage called for svcnum ". $self->svcnum.
2256 ' ('. $self->email. "): ".
2257 join(', ', map { "$_ => " . $valueref->{$_}} keys %$valueref) . "\n"
2260 local $SIG{HUP} = 'IGNORE';
2261 local $SIG{INT} = 'IGNORE';
2262 local $SIG{QUIT} = 'IGNORE';
2263 local $SIG{TERM} = 'IGNORE';
2264 local $SIG{TSTP} = 'IGNORE';
2265 local $SIG{PIPE} = 'IGNORE';
2267 local $FS::svc_Common::noexport_hack = 1;
2268 my $oldAutoCommit = $FS::UID::AutoCommit;
2269 local $FS::UID::AutoCommit = 0;
2274 if ( $options{null} ) {
2275 %handyhash = ( map { ( $_ => undef, $_."_threshold" => undef ) }
2276 qw( seconds upbytes downbytes totalbytes )
2279 foreach my $field (keys %$valueref){
2280 $reset = 1 if $valueref->{$field};
2281 $self->setfield($field, $valueref->{$field});
2282 $self->setfield( $field.'_threshold',
2283 int($self->getfield($field)
2284 * ( $conf->exists('svc_acct-usage_threshold')
2285 ? 1 - $conf->config('svc_acct-usage_threshold')/100
2290 $handyhash{$field} = $self->getfield($field);
2291 $handyhash{$field.'_threshold'} = $self->getfield($field.'_threshold');
2293 #my $error = $self->replace; #NO! we avoid the call to ->check for
2294 #die $error if $error; #services not explicity changed via the UI
2296 my $sql = "UPDATE svc_acct SET " .
2297 join (',', map { "$_ = ?" } (keys %handyhash) ).
2298 " WHERE svcnum = ". $self->svcnum;
2303 if (scalar(keys %handyhash)) {
2304 my $sth = $dbh->prepare( $sql )
2305 or die "Error preparing $sql: ". $dbh->errstr;
2306 my $rv = $sth->execute(values %handyhash);
2307 die "Error executing $sql: ". $sth->errstr
2308 unless defined($rv);
2309 die "Can't update usage for svcnum ". $self->svcnum
2313 #$self->snapshot; #not necessary, we retain the old values
2314 #create an object with the updated usage values
2315 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2316 local($FS::Record::nowarn_identical) = 1;
2317 my $error = $new->replace($self); #call exports
2319 $dbh->rollback if $oldAutoCommit;
2320 return "Error replacing: $error";
2327 $error = $self->_op_overlimit('unsuspend')
2328 if $self->overlimit;;
2330 $error ||= $self->cust_svc->cust_pkg->unsuspend
2331 if $conf->exists("svc_acct-usage_unsuspend");
2334 $dbh->rollback if $oldAutoCommit;
2335 return "Error unsuspending: $error";
2340 warn "$me update successful; committing\n"
2342 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2348 =item recharge HASHREF
2350 Increments usage columns by the amount specified in HASHREF as
2351 column=>amount pairs.
2356 my ($self, $vhash) = @_;
2359 warn "[$me] recharge called on $self: ". Dumper($self).
2360 "\nwith vhash: ". Dumper($vhash);
2363 my $oldAutoCommit = $FS::UID::AutoCommit;
2364 local $FS::UID::AutoCommit = 0;
2368 foreach my $column (keys %$vhash){
2369 $error ||= $self->_op_usage('+', $column, $vhash->{$column});
2373 $dbh->rollback if $oldAutoCommit;
2375 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2380 =item is_rechargeable
2382 Returns true if this svc_account can be "recharged" and false otherwise.
2386 sub is_rechargable {
2388 $self->seconds ne ''
2389 || $self->upbytes ne ''
2390 || $self->downbytes ne ''
2391 || $self->totalbytes ne '';
2394 =item seconds_since TIMESTAMP
2396 Returns the number of seconds this account has been online since TIMESTAMP,
2397 according to the session monitor (see L<FS::Session>).
2399 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2400 L<Time::Local> and L<Date::Parse> for conversion functions.
2404 #note: POD here, implementation in FS::cust_svc
2407 $self->cust_svc->seconds_since(@_);
2410 =item seconds_since_sqlradacct TIMESTAMP_START TIMESTAMP_END
2412 Returns the numbers of seconds this account has been online between
2413 TIMESTAMP_START (inclusive) and TIMESTAMP_END (exclusive), according to an
2414 external SQL radacct table, specified via sqlradius export. Sessions which
2415 started in the specified range but are still open are counted from session
2416 start to the end of the range (unless they are over 1 day old, in which case
2417 they are presumed missing their stop record and not counted). Also, sessions
2418 which end in the range but started earlier are counted from the start of the
2419 range to session end. Finally, sessions which start before the range but end
2420 after are counted for the entire range.
2422 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2423 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2428 #note: POD here, implementation in FS::cust_svc
2429 sub seconds_since_sqlradacct {
2431 $self->cust_svc->seconds_since_sqlradacct(@_);
2434 =item attribute_since_sqlradacct TIMESTAMP_START TIMESTAMP_END ATTRIBUTE
2436 Returns the sum of the given attribute for all accounts (see L<FS::svc_acct>)
2437 in this package for sessions ending between TIMESTAMP_START (inclusive) and
2438 TIMESTAMP_END (exclusive).
2440 TIMESTAMP_START and TIMESTAMP_END are specified as UNIX timestamps; see
2441 L<perlfunc/"time">. Also see L<Time::Local> and L<Date::Parse> for conversion
2446 #note: POD here, implementation in FS::cust_svc
2447 sub attribute_since_sqlradacct {
2449 $self->cust_svc->attribute_since_sqlradacct(@_);
2452 =item get_session_history TIMESTAMP_START TIMESTAMP_END
2454 Returns an array of hash references of this customers login history for the
2455 given time range. (document this better)
2459 sub get_session_history {
2461 $self->cust_svc->get_session_history(@_);
2464 =item last_login_text
2466 Returns text describing the time of last login.
2470 sub last_login_text {
2472 $self->last_login ? ctime($self->last_login) : 'unknown';
2475 =item get_cdrs TIMESTAMP_START TIMESTAMP_END [ 'OPTION' => 'VALUE ... ]
2480 my($self, $start, $end, %opt ) = @_;
2482 my $did = $self->username; #yup
2484 my $prefix = $opt{'default_prefix'}; #convergent.au '+61'
2486 my $for_update = $opt{'for_update'} ? 'FOR UPDATE' : '';
2488 #SELECT $for_update * FROM cdr
2489 # WHERE calldate >= $start #need a conversion
2490 # AND calldate < $end #ditto
2491 # AND ( charged_party = "$did"
2492 # OR charged_party = "$prefix$did" #if length($prefix);
2493 # OR ( ( charged_party IS NULL OR charged_party = '' )
2495 # ( src = "$did" OR src = "$prefix$did" ) # if length($prefix)
2498 # AND ( freesidestatus IS NULL OR freesidestatus = '' )
2501 if ( length($prefix) ) {
2503 " AND ( charged_party = '$did'
2504 OR charged_party = '$prefix$did'
2505 OR ( ( charged_party IS NULL OR charged_party = '' )
2507 ( src = '$did' OR src = '$prefix$did' )
2513 " AND ( charged_party = '$did'
2514 OR ( ( charged_party IS NULL OR charged_party = '' )
2524 'select' => "$for_update *",
2527 #( freesidestatus IS NULL OR freesidestatus = '' )
2528 'freesidestatus' => '',
2530 'extra_sql' => $charged_or_src,
2538 Returns all RADIUS groups for this account (see L<FS::radius_usergroup>).
2544 if ( $self->usergroup ) {
2545 confess "explicitly specified usergroup not an arrayref: ". $self->usergroup
2546 unless ref($self->usergroup) eq 'ARRAY';
2547 #when provisioning records, export callback runs in svc_Common.pm before
2548 #radius_usergroup records can be inserted...
2549 @{$self->usergroup};
2551 map { $_->groupname }
2552 qsearch('radius_usergroup', { 'svcnum' => $self->svcnum } );
2556 =item clone_suspended
2558 Constructor used by FS::part_export::_export_suspend fallback. Document
2563 sub clone_suspended {
2565 my %hash = $self->hash;
2566 $hash{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
2567 new FS::svc_acct \%hash;
2570 =item clone_kludge_unsuspend
2572 Constructor used by FS::part_export::_export_unsuspend fallback. Document
2577 sub clone_kludge_unsuspend {
2579 my %hash = $self->hash;
2580 $hash{_password} = '';
2581 new FS::svc_acct \%hash;
2584 =item check_password
2586 Checks the supplied password against the (possibly encrypted) password in the
2587 database. Returns true for a successful authentication, false for no match.
2589 Currently supported encryptions are: classic DES crypt() and MD5
2593 sub check_password {
2594 my($self, $check_password) = @_;
2596 #remove old-style SUSPENDED kludge, they should be allowed to login to
2597 #self-service and pay up
2598 ( my $password = $self->_password ) =~ s/^\*SUSPENDED\* //;
2600 if ( $self->_password_encoding eq 'ldap' ) {
2602 my $auth = from_rfc2307 Authen::Passphrase $self->_password;
2603 return $auth->match($check_password);
2605 } elsif ( $self->_password_encoding eq 'crypt' ) {
2607 my $auth = from_crypt Authen::Passphrase $self->_password;
2608 return $auth->match($check_password);
2610 } elsif ( $self->_password_encoding eq 'plain' ) {
2612 return $check_password eq $password;
2616 #XXX this could be replaced with Authen::Passphrase stuff
2618 if ( $password =~ /^(\*|!!?)$/ ) { #no self-service login
2620 } elsif ( length($password) < 13 ) { #plaintext
2621 $check_password eq $password;
2622 } elsif ( length($password) == 13 ) { #traditional DES crypt
2623 crypt($check_password, $password) eq $password;
2624 } elsif ( $password =~ /^\$1\$/ ) { #MD5 crypt
2625 unix_md5_crypt($check_password, $password) eq $password;
2626 } elsif ( $password =~ /^\$2a?\$/ ) { #Blowfish
2627 warn "Can't check password: Blowfish encryption not yet supported, ".
2628 "svcnum ". $self->svcnum. "\n";
2631 warn "Can't check password: Unrecognized encryption for svcnum ".
2632 $self->svcnum. "\n";
2640 =item crypt_password [ DEFAULT_ENCRYPTION_TYPE ]
2642 Returns an encrypted password, either by passing through an encrypted password
2643 in the database or by encrypting a plaintext password from the database.
2645 The optional DEFAULT_ENCRYPTION_TYPE parameter can be set to I<crypt> (classic
2646 UNIX DES crypt), I<md5> (md5 crypt supported by most modern Linux and BSD
2647 distrubtions), or (eventually) I<blowfish> (blowfish hashing supported by
2648 OpenBSD, SuSE, other Linux distibutions with pam_unix2, etc.). The default
2649 encryption type is only used if the password is not already encrypted in the
2654 sub crypt_password {
2657 if ( $self->_password_encoding eq 'ldap' ) {
2659 if ( $self->_password =~ /^\{(PLAIN|CLEARTEXT)\}(.+)$/ ) {
2662 #XXX this could be replaced with Authen::Passphrase stuff
2664 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2665 if ( $encryption eq 'crypt' ) {
2668 $saltset[int(rand(64))].$saltset[int(rand(64))]
2670 } elsif ( $encryption eq 'md5' ) {
2671 unix_md5_crypt( $self->_password );
2672 } elsif ( $encryption eq 'blowfish' ) {
2673 croak "unknown encryption method $encryption";
2675 croak "unknown encryption method $encryption";
2678 } elsif ( $self->_password =~ /^\{CRYPT\}(.+)$/ ) {
2682 } elsif ( $self->_password_encoding eq 'crypt' ) {
2684 return $self->_password;
2686 } elsif ( $self->_password_encoding eq 'plain' ) {
2688 #XXX this could be replaced with Authen::Passphrase stuff
2690 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2691 if ( $encryption eq 'crypt' ) {
2694 $saltset[int(rand(64))].$saltset[int(rand(64))]
2696 } elsif ( $encryption eq 'md5' ) {
2697 unix_md5_crypt( $self->_password );
2698 } elsif ( $encryption eq 'blowfish' ) {
2699 croak "unknown encryption method $encryption";
2701 croak "unknown encryption method $encryption";
2706 if ( length($self->_password) == 13
2707 || $self->_password =~ /^\$(1|2a?)\$/
2708 || $self->_password =~ /^(\*|NP|\*LK\*|!!?)$/
2714 #XXX this could be replaced with Authen::Passphrase stuff
2716 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2717 if ( $encryption eq 'crypt' ) {
2720 $saltset[int(rand(64))].$saltset[int(rand(64))]
2722 } elsif ( $encryption eq 'md5' ) {
2723 unix_md5_crypt( $self->_password );
2724 } elsif ( $encryption eq 'blowfish' ) {
2725 croak "unknown encryption method $encryption";
2727 croak "unknown encryption method $encryption";
2736 =item ldap_password [ DEFAULT_ENCRYPTION_TYPE ]
2738 Returns an encrypted password in "LDAP" format, with a curly-bracked prefix
2739 describing the format, for example, "{PLAIN}himom", "{CRYPT}94pAVyK/4oIBk" or
2740 "{MD5}5426824942db4253f87a1009fd5d2d4".
2742 The optional DEFAULT_ENCRYPTION_TYPE is not yet used, but the idea is for it
2743 to work the same as the B</crypt_password> method.
2749 #eventually should check a "password-encoding" field
2751 if ( $self->_password_encoding eq 'ldap' ) {
2753 return $self->_password;
2755 } elsif ( $self->_password_encoding eq 'crypt' ) {
2757 if ( length($self->_password) == 13 ) { #crypt
2758 return '{CRYPT}'. $self->_password;
2759 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2761 #} elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2762 # die "Blowfish encryption not supported in this context, svcnum ".
2763 # $self->svcnum. "\n";
2765 warn "encryption method not (yet?) supported in LDAP context";
2766 return '{CRYPT}*'; #unsupported, should not auth
2769 } elsif ( $self->_password_encoding eq 'plain' ) {
2771 return '{PLAIN}'. $self->_password;
2773 #return '{CLEARTEXT}'. $self->_password; #?
2777 if ( length($self->_password) == 13 ) { #crypt
2778 return '{CRYPT}'. $self->_password;
2779 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2781 } elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2782 warn "Blowfish encryption not supported in this context, svcnum ".
2783 $self->svcnum. "\n";
2786 #are these two necessary anymore?
2787 } elsif ( $self->_password =~ /^(\w{48})$/ ) { #LDAP SSHA
2788 return '{SSHA}'. $1;
2789 } elsif ( $self->_password =~ /^(\w{64})$/ ) { #LDAP NS-MTA-MD5
2790 return '{NS-MTA-MD5}'. $1;
2793 return '{PLAIN}'. $self->_password;
2795 #return '{CLEARTEXT}'. $self->_password; #?
2797 #XXX this could be replaced with Authen::Passphrase stuff if it gets used
2798 #my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2799 #if ( $encryption eq 'crypt' ) {
2800 # return '{CRYPT}'. crypt(
2802 # $saltset[int(rand(64))].$saltset[int(rand(64))]
2804 #} elsif ( $encryption eq 'md5' ) {
2805 # unix_md5_crypt( $self->_password );
2806 #} elsif ( $encryption eq 'blowfish' ) {
2807 # croak "unknown encryption method $encryption";
2809 # croak "unknown encryption method $encryption";
2817 =item domain_slash_username
2819 Returns $domain/$username/
2823 sub domain_slash_username {
2825 $self->domain. '/'. $self->username. '/';
2828 =item virtual_maildir
2830 Returns $domain/maildirs/$username/
2834 sub virtual_maildir {
2836 $self->domain. '/maildirs/'. $self->username. '/';
2841 =head1 CLASS METHODS
2845 =item search HASHREF
2847 Class method which returns a qsearch hash expression to search for parameters
2848 specified in HASHREF. Valid parameters are
2862 Arrayref of pkgparts
2868 Arrayref of additional WHERE clauses, will be ANDed together.
2879 my ($class, $params) = @_;
2884 if ( $params->{'domain'} ) {
2885 my $svc_domain = qsearchs('svc_domain', { 'domain'=>$params->{'domain'} } );
2886 #preserve previous behavior & bubble up an error if $svc_domain not found?
2887 push @where, 'domsvc = '. $svc_domain->svcnum if $svc_domain;
2891 if ( $params->{'domsvc'} =~ /^(\d+)$/ ) {
2892 push @where, "domsvc = $1";
2896 push @where, 'pkgnum IS NULL' if $params->{'unlinked'};
2899 if ( $params->{'agentnum'} =~ /^(\d+)$/ and $1 ) {
2900 push @where, "agentnum = $1";
2904 if ( $params->{'custnum'} =~ /^(\d+)$/ and $1 ) {
2905 push @where, "custnum = $1";
2909 if ( $params->{'pkgpart'} && scalar(@{ $params->{'pkgpart'} }) ) {
2910 #XXX untaint or sql quote
2912 'cust_pkg.pkgpart IN ('. join(',', @{ $params->{'pkgpart'} } ). ')';
2916 if ( $params->{'popnum'} =~ /^(\d+)$/ ) {
2917 push @where, "popnum = $1";
2921 if ( $params->{'svcpart'} =~ /^(\d+)$/ ) {
2922 push @where, "svcpart = $1";
2926 # here is the agent virtualization
2927 #if ($params->{CurrentUser}) {
2929 # qsearchs('access_user', { username => $params->{CurrentUser} });
2931 # if ($access_user) {
2932 # push @where, $access_user->agentnums_sql('table'=>'cust_main');
2934 # push @where, "1=0";
2937 push @where, $FS::CurrentUser::CurrentUser->agentnums_sql(
2938 'table' => 'cust_main',
2939 'null_right' => 'View/link unlinked services',
2943 push @where, @{ $params->{'where'} } if $params->{'where'};
2945 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
2947 my $addl_from = ' LEFT JOIN cust_svc USING ( svcnum ) '.
2948 ' LEFT JOIN part_svc USING ( svcpart ) '.
2949 ' LEFT JOIN cust_pkg USING ( pkgnum ) '.
2950 ' LEFT JOIN cust_main USING ( custnum ) ';
2952 my $count_query = "SELECT COUNT(*) FROM svc_acct $addl_from $extra_sql";
2953 #if ( keys %svc_acct ) {
2954 # $count_query .= ' WHERE '.
2955 # join(' AND ', map "$_ = ". dbh->quote($svc_acct{$_}),
2961 'table' => 'svc_acct',
2962 'hashref' => {}, # \%svc_acct,
2963 'select' => join(', ',
2966 'cust_main.custnum',
2967 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
2969 'addl_from' => $addl_from,
2970 'extra_sql' => $extra_sql,
2971 'order_by' => $params->{'order_by'},
2972 'count_query' => $count_query,
2985 This is the FS::svc_acct job-queue-able version. It still uses
2986 FS::Misc::send_email under-the-hood.
2993 eval "use FS::Misc qw(send_email)";
2996 $opt{mimetype} ||= 'text/plain';
2997 $opt{mimetype} .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2999 my $error = send_email(
3000 'from' => $opt{from},
3002 'subject' => $opt{subject},
3003 'content-type' => $opt{mimetype},
3004 'body' => [ map "$_\n", split("\n", $opt{body}) ],
3006 die $error if $error;
3009 =item check_and_rebuild_fuzzyfiles
3013 sub check_and_rebuild_fuzzyfiles {
3014 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3015 -e "$dir/svc_acct.username"
3016 or &rebuild_fuzzyfiles;
3019 =item rebuild_fuzzyfiles
3023 sub rebuild_fuzzyfiles {
3025 use Fcntl qw(:flock);
3027 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3031 open(USERNAMELOCK,">>$dir/svc_acct.username")
3032 or die "can't open $dir/svc_acct.username: $!";
3033 flock(USERNAMELOCK,LOCK_EX)
3034 or die "can't lock $dir/svc_acct.username: $!";
3036 my @all_username = map $_->getfield('username'), qsearch('svc_acct', {});
3038 open (USERNAMECACHE,">$dir/svc_acct.username.tmp")
3039 or die "can't open $dir/svc_acct.username.tmp: $!";
3040 print USERNAMECACHE join("\n", @all_username), "\n";
3041 close USERNAMECACHE or die "can't close $dir/svc_acct.username.tmp: $!";
3043 rename "$dir/svc_acct.username.tmp", "$dir/svc_acct.username";
3053 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3054 open(USERNAMECACHE,"<$dir/svc_acct.username")
3055 or die "can't open $dir/svc_acct.username: $!";
3056 my @array = map { chomp; $_; } <USERNAMECACHE>;
3057 close USERNAMECACHE;
3061 =item append_fuzzyfiles USERNAME
3065 sub append_fuzzyfiles {
3066 my $username = shift;
3068 &check_and_rebuild_fuzzyfiles;
3070 use Fcntl qw(:flock);
3072 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
3074 open(USERNAME,">>$dir/svc_acct.username")
3075 or die "can't open $dir/svc_acct.username: $!";
3076 flock(USERNAME,LOCK_EX)
3077 or die "can't lock $dir/svc_acct.username: $!";
3079 print USERNAME "$username\n";
3081 flock(USERNAME,LOCK_UN)
3082 or die "can't unlock $dir/svc_acct.username: $!";
3090 =item radius_usergroup_selector GROUPS_ARRAYREF [ SELECTNAME ]
3094 sub radius_usergroup_selector {
3095 my $sel_groups = shift;
3096 my %sel_groups = map { $_=>1 } @$sel_groups;
3098 my $selectname = shift || 'radius_usergroup';
3101 my $sth = $dbh->prepare(
3102 'SELECT DISTINCT(groupname) FROM radius_usergroup ORDER BY groupname'
3103 ) or die $dbh->errstr;
3104 $sth->execute() or die $sth->errstr;
3105 my @all_groups = map { $_->[0] } @{$sth->fetchall_arrayref};
3109 function ${selectname}_doadd(object) {
3110 var myvalue = object.${selectname}_add.value;
3111 var optionName = new Option(myvalue,myvalue,false,true);
3112 var length = object.$selectname.length;
3113 object.$selectname.options[length] = optionName;
3114 object.${selectname}_add.value = "";
3117 <SELECT MULTIPLE NAME="$selectname">
3120 foreach my $group ( @all_groups ) {
3121 $html .= qq(<OPTION VALUE="$group");
3122 if ( $sel_groups{$group} ) {
3123 $html .= ' SELECTED';
3124 $sel_groups{$group} = 0;
3126 $html .= ">$group</OPTION>\n";
3128 foreach my $group ( grep { $sel_groups{$_} } keys %sel_groups ) {
3129 $html .= qq(<OPTION VALUE="$group" SELECTED>$group</OPTION>\n);
3131 $html .= '</SELECT>';
3133 $html .= qq!<BR><INPUT TYPE="text" NAME="${selectname}_add">!.
3134 qq!<INPUT TYPE="button" VALUE="Add new group" onClick="${selectname}_doadd(this.form)">!;
3139 =item reached_threshold
3141 Performs some activities when svc_acct thresholds (such as number of seconds
3142 remaining) are reached.
3146 sub reached_threshold {
3149 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } );
3150 die "Cannot find svc_acct with svcnum " . $opt{'svcnum'} unless $svc_acct;
3152 if ( $opt{'op'} eq '+' ){
3153 $svc_acct->setfield( $opt{'column'}.'_threshold',
3154 int($svc_acct->getfield($opt{'column'})
3155 * ( $conf->exists('svc_acct-usage_threshold')
3156 ? $conf->config('svc_acct-usage_threshold')/100
3161 my $error = $svc_acct->replace;
3162 die $error if $error;
3163 }elsif ( $opt{'op'} eq '-' ){
3165 my $threshold = $svc_acct->getfield( $opt{'column'}.'_threshold' );
3166 return '' if ($threshold eq '' );
3168 $svc_acct->setfield( $opt{'column'}.'_threshold', 0 );
3169 my $error = $svc_acct->replace;
3170 die $error if $error; # email next time, i guess
3172 if ( $warning_template ) {
3173 eval "use FS::Misc qw(send_email)";
3176 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
3177 my $cust_main = $cust_pkg->cust_main;
3179 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ }
3180 $cust_main->invoicing_list,
3181 ($opt{'to'} ? $opt{'to'} : ())
3184 my $mimetype = $warning_mimetype;
3185 $mimetype .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
3187 my $body = $warning_template->fill_in( HASH => {
3188 'custnum' => $cust_main->custnum,
3189 'username' => $svc_acct->username,
3190 'password' => $svc_acct->_password,
3191 'first' => $cust_main->first,
3192 'last' => $cust_main->getfield('last'),
3193 'pkg' => $cust_pkg->part_pkg->pkg,
3194 'column' => $opt{'column'},
3195 'amount' => $opt{'column'} =~/bytes/
3196 ? FS::UI::bytecount::display_bytecount($svc_acct->getfield($opt{'column'}))
3197 : $svc_acct->getfield($opt{'column'}),
3198 'threshold' => $opt{'column'} =~/bytes/
3199 ? FS::UI::bytecount::display_bytecount($threshold)
3204 my $error = send_email(
3205 'from' => $warning_from,
3207 'subject' => $warning_subject,
3208 'content-type' => $mimetype,
3209 'body' => [ map "$_\n", split("\n", $body) ],
3211 die $error if $error;
3214 die "unknown op: " . $opt{'op'};
3222 The $recref stuff in sub check should be cleaned up.
3224 The suspend, unsuspend and cancel methods update the database, but not the
3225 current object. This is probably a bug as it's unexpected and
3228 radius_usergroup_selector? putting web ui components in here? they should
3229 probably live somewhere else...
3231 insertion of RADIUS group stuff in insert could be done with child_objects now
3232 (would probably clean up export of them too)
3234 _op_usage and set_usage bypass the history... maybe they shouldn't
3238 L<FS::svc_Common>, edit/part_svc.cgi from an installed web interface,
3239 export.html from the base documentation, L<FS::Record>, L<FS::Conf>,
3240 L<FS::cust_svc>, L<FS::part_svc>, L<FS::cust_pkg>, L<FS::queue>,
3241 L<freeside-queued>), L<FS::svc_acct_pop>,
3242 schema.html from the base documentation.