2 use base qw( FS::svc_Domain_Mixin FS::svc_PBX_Mixin
3 FS::svc_CGP_Mixin FS::svc_CGPRule_Mixin
11 use vars qw( $DEBUG $me $conf $skip_fuzzyfiles
12 $dir_prefix @shells $usernamemin
13 $usernamemax $passwordmin $passwordmax
14 $username_ampersand $username_letter $username_letterfirst
15 $username_noperiod $username_nounderscore $username_nodash
16 $username_uppercase $username_percent $username_colon
17 $username_slash $username_equals $username_pound
19 $password_noampersand $password_noexclamation
20 $warning_template $warning_from $warning_subject $warning_mimetype
23 $radius_password $radius_ip
26 use Scalar::Util qw( blessed );
31 use Crypt::PasswdMD5 1.2;
32 use Digest::SHA 'sha1_base64';
33 use Digest::MD5 'md5_base64';
36 use Authen::Passphrase;
37 use FS::UID qw( datasrc driver_name );
39 use FS::Record qw( qsearch qsearchs fields dbh dbdef );
40 use FS::Msgcat qw(gettext);
41 use FS::UI::bytecount;
43 use FS::PagedSearch qw( psearch ); # XXX in v4, replace with FS::Cursor
47 use FS::cust_main_invoice;
52 use FS::radius_usergroup;
62 $me = '[FS::svc_acct]';
64 #ask FS::UID to run this stuff for us later
65 FS::UID->install_callback( sub {
67 $dir_prefix = $conf->config('home');
68 @shells = $conf->config('shells');
69 $usernamemin = $conf->config('usernamemin') || 2;
70 $usernamemax = $conf->config('usernamemax');
71 $passwordmin = $conf->config('passwordmin'); # || 6;
73 $passwordmin = ( defined($passwordmin) && $passwordmin =~ /\d+/ )
76 $passwordmax = $conf->config('passwordmax') || 8;
77 $username_letter = $conf->exists('username-letter');
78 $username_letterfirst = $conf->exists('username-letterfirst');
79 $username_noperiod = $conf->exists('username-noperiod');
80 $username_nounderscore = $conf->exists('username-nounderscore');
81 $username_nodash = $conf->exists('username-nodash');
82 $username_uppercase = $conf->exists('username-uppercase');
83 $username_ampersand = $conf->exists('username-ampersand');
84 $username_percent = $conf->exists('username-percent');
85 $username_colon = $conf->exists('username-colon');
86 $username_slash = $conf->exists('username-slash');
87 $username_equals = $conf->exists('username-equals');
88 $username_pound = $conf->exists('username-pound');
89 $username_exclamation = $conf->exists('username-exclamation');
90 $password_noampersand = $conf->exists('password-noexclamation');
91 $password_noexclamation = $conf->exists('password-noexclamation');
92 $dirhash = $conf->config('dirhash') || 0;
93 if ( $conf->exists('warning_email') ) {
94 $warning_template = new Text::Template (
96 SOURCE => [ map "$_\n", $conf->config('warning_email') ]
97 ) or warn "can't create warning email template: $Text::Template::ERROR";
98 $warning_from = $conf->config('warning_email-from'); # || 'your-isp-is-dum'
99 $warning_subject = $conf->config('warning_email-subject') || 'Warning';
100 $warning_mimetype = $conf->config('warning_email-mimetype') || 'text/plain';
101 $warning_cc = $conf->config('warning_email-cc');
103 $warning_template = '';
105 $warning_subject = '';
106 $warning_mimetype = '';
109 $smtpmachine = $conf->config('smtpmachine');
110 $radius_password = $conf->config('radius-password') || 'Password';
111 $radius_ip = $conf->config('radius-ip') || 'Framed-IP-Address';
112 @pw_set = ( 'A'..'Z' ) if $conf->exists('password-generated-allcaps');
116 @saltset = ( 'a'..'z' , 'A'..'Z' , '0'..'9' , '.' , '/' );
117 @pw_set = ( 'a'..'z', 'A'..'Z', '0'..'9', '(', ')', '#', '.', ',' );
121 my ( $hashref, $cache ) = @_;
122 if ( $hashref->{'svc_acct_svcnum'} ) {
123 $self->{'_domsvc'} = FS::svc_domain->new( {
124 'svcnum' => $hashref->{'domsvc'},
125 'domain' => $hashref->{'svc_acct_domain'},
126 'catchall' => $hashref->{'svc_acct_catchall'},
133 FS::svc_acct - Object methods for svc_acct records
139 $record = new FS::svc_acct \%hash;
140 $record = new FS::svc_acct { 'column' => 'value' };
142 $error = $record->insert;
144 $error = $new_record->replace($old_record);
146 $error = $record->delete;
148 $error = $record->check;
150 $error = $record->suspend;
152 $error = $record->unsuspend;
154 $error = $record->cancel;
156 %hash = $record->radius;
158 %hash = $record->radius_reply;
160 %hash = $record->radius_check;
162 $domain = $record->domain;
164 $svc_domain = $record->svc_domain;
166 $email = $record->email;
168 $seconds_since = $record->seconds_since($timestamp);
172 An FS::svc_acct object represents an account. FS::svc_acct inherits from
173 FS::svc_Common. The following fields are currently supported:
179 Primary key (assigned automatcially for new accounts)
187 =item _password_encoding
189 plain, crypt, ldap (or empty for autodetection)
197 Point of presence (see L<FS::svc_acct_pop>)
209 set automatically if blank (and uid is not)
229 svcnum from svc_domain
233 Optional svcnum from svc_pbx
235 =item radius_I<Radius_Attribute>
237 I<Radius-Attribute> (reply)
239 =item rc_I<Radius_Attribute>
241 I<Radius-Attribute> (check)
251 Creates a new account. To add the account to the database, see L<"insert">.
258 'longname_plural' => 'Access accounts and mailboxes',
259 'sorts' => [ 'username', 'uid', 'seconds', 'last_login' ],
260 'display_weight' => 10,
261 'cancel_weight' => 50,
262 'ip_field' => 'slipip',
263 'manual_require' => 1,
265 'dir' => 'Home directory',
268 def_info => 'set to fixed and blank for no UIDs',
271 'slipip' => 'IP address',
272 # 'popnum' => qq!<A HREF="$p/browse/svc_acct_pop.cgi/">POP number</A>!,
274 label => 'Access number',
276 select_table => 'svc_acct_pop',
277 select_key => 'popnum',
278 select_label => 'city',
284 disable_default => 1,
289 'password_selfchange' => { label => 'Password modification',
292 'password_recover' => { label => 'Password recovery',
296 label => 'Quota', #Mail storage limit
298 disable_inventory => 1,
301 label => 'File storage limit',
303 disable_inventory => 1,
306 label => 'Number of files limit',
308 disable_inventory => 1,
311 label => 'File size limit',
313 disable_inventory => 1,
315 '_password' => { label => 'Password',
320 def_info => 'when blank, defaults to UID',
325 def_info => 'set to blank for no shell tracking',
327 #select_list => [ $conf->config('shells') ],
328 select_list => [ $conf ? $conf->config('shells') : () ],
329 disable_inventory => 1,
332 'finger' => 'Real name', # (GECOS)',
336 select_table => 'svc_domain',
337 select_key => 'svcnum',
338 select_label => 'domain',
339 disable_inventory => 1,
342 'pbxsvc' => { label => 'PBX',
343 type => 'select-svc_pbx.html',
344 disable_inventory => 1,
345 disable_select => 1, #UI wonky, pry works otherwise
347 'sectornum' => 'Tower sector',
349 label => 'RADIUS groups',
350 type => 'select-radius_group.html',
351 disable_inventory => 1,
355 'seconds' => { label => 'Seconds',
356 label_sort => 'with Time Remaining',
358 disable_inventory => 1,
360 disable_part_svc_column => 1,
362 'upbytes' => { label => 'Upload',
364 disable_inventory => 1,
366 'format' => \&FS::UI::bytecount::display_bytecount,
367 'parse' => \&FS::UI::bytecount::parse_bytecount,
368 disable_part_svc_column => 1,
370 'downbytes' => { label => 'Download',
372 disable_inventory => 1,
374 'format' => \&FS::UI::bytecount::display_bytecount,
375 'parse' => \&FS::UI::bytecount::parse_bytecount,
376 disable_part_svc_column => 1,
378 'totalbytes'=> { label => 'Total up and download',
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 'seconds_threshold' => { label => 'Seconds threshold',
388 disable_inventory => 1,
390 disable_part_svc_column => 1,
392 'upbytes_threshold' => { label => 'Upload threshold',
394 disable_inventory => 1,
396 'format' => \&FS::UI::bytecount::display_bytecount,
397 'parse' => \&FS::UI::bytecount::parse_bytecount,
398 disable_part_svc_column => 1,
400 'downbytes_threshold' => { label => 'Download threshold',
402 disable_inventory => 1,
404 'format' => \&FS::UI::bytecount::display_bytecount,
405 'parse' => \&FS::UI::bytecount::parse_bytecount,
406 disable_part_svc_column => 1,
408 'totalbytes_threshold'=> { label => 'Total up and download threshold',
410 disable_inventory => 1,
412 'format' => \&FS::UI::bytecount::display_bytecount,
413 'parse' => \&FS::UI::bytecount::parse_bytecount,
414 disable_part_svc_column => 1,
417 label => 'Last login',
421 label => 'Last logout',
426 label => 'Communigate aliases',
428 disable_inventory => 1,
433 label => 'Communigate account type',
435 select_list => [qw( MultiMailbox TextMailbox MailDirMailbox AGrade BGrade CGrade )],
436 disable_inventory => 1,
439 'cgp_accessmodes' => {
440 label => 'Communigate enabled services',
441 type => 'communigate_pro-accessmodes',
442 disable_inventory => 1,
445 'cgp_rulesallowed' => {
446 label => 'Allowed mail rules',
448 select_list => [ '', 'No', 'Filter Only', 'All But Exec', 'Any' ],
449 disable_inventory => 1,
452 'cgp_rpopallowed' => { label => 'RPOP modifications',
455 'cgp_mailtoall' => { label => 'Accepts mail to "all"',
458 'cgp_addmailtrailer' => { label => 'Add trailer to sent mail',
461 'cgp_archiveafter' => {
462 label => 'Archive messages after',
465 -2 => 'default(730 days)',
472 1209600 => '2 weeks',
473 2592000 => '30 days',
474 7776000 => '90 days',
475 15552000 => '180 days',
476 31536000 => '365 days',
477 63072000 => '730 days',
479 disable_inventory => 1,
485 'cgp_deletemode' => {
486 label => 'Communigate message delete method',
488 select_list => [ 'Move To Trash', 'Immediately', 'Mark' ],
489 disable_inventory => 1,
492 'cgp_emptytrash' => {
493 label => 'Communigate on logout remove trash',
495 select_list => __PACKAGE__->cgp_emptytrash_values,
496 disable_inventory => 1,
500 label => 'Communigate language',
502 select_list => [ '', qw( English Arabic Chinese Dutch French German Hebrew Italian Japanese Portuguese Russian Slovak Spanish Thai ) ],
503 disable_inventory => 1,
507 label => 'Communigate time zone',
509 select_list => __PACKAGE__->cgp_timezone_values,
510 disable_inventory => 1,
514 label => 'Communigate layout',
516 select_list => [ '', '***', 'GoldFleece', 'Skin2' ],
517 disable_inventory => 1,
520 'cgp_prontoskinname' => {
521 label => 'Communigate Pronto style',
523 select_list => [ '', 'Pronto', 'Pronto-darkflame', 'Pronto-steel', 'Pronto-twilight', ],
524 disable_inventory => 1,
527 'cgp_sendmdnmode' => {
528 label => 'Communigate send read receipts',
530 select_list => [ '', 'Never', 'Manually', 'Automatically' ],
531 disable_inventory => 1,
542 sub table { 'svc_acct'; }
544 sub table_dupcheck_fields { ( 'username', 'domsvc' ); }
547 shift->_lastlog('in', @_);
551 shift->_lastlog('out', @_);
555 my( $self, $op, $time ) = @_;
557 if ( defined($time) ) {
558 warn "$me last_log$op called on svcnum ". $self->svcnum.
559 ' ('. $self->email. "): $time\n"
564 my $sql = "UPDATE svc_acct SET last_log$op = ? WHERE svcnum = ?";
568 my $sth = $dbh->prepare( $sql )
569 or die "Error preparing $sql: ". $dbh->errstr;
570 my $rv = $sth->execute($time, $self->svcnum);
571 die "Error executing $sql: ". $sth->errstr
573 die "Can't update last_log$op for svcnum". $self->svcnum
576 $self->{'Hash'}->{"last_log$op"} = $time;
578 $self->getfield("last_log$op");
582 =item search_sql STRING
584 Class method which returns an SQL fragment to search for the given string.
589 my( $class, $string ) = @_;
590 if ( $string =~ /^([^@]+)@([^@]+)$/ ) {
591 my( $username, $domain ) = ( $1, $2 );
592 my $q_username = dbh->quote($username);
593 my @svc_domain = qsearch('svc_domain', { 'domain' => $domain } );
595 "svc_acct.username = $q_username AND ( ".
596 join( ' OR ', map { "svc_acct.domsvc = ". $_->svcnum; } @svc_domain ).
601 } elsif ( $string =~ /^(\d{1,3}\.){3}\d{1,3}$/ ) {
603 $class->search_sql_field('slipip', $string ).
605 $class->search_sql_field('username', $string ).
608 $class->search_sql_field('username', $string);
612 =item label [ END_TIMESTAMP [ START_TIMESTAMP ] ]
614 Returns the "username@domain" string for this account.
616 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
626 =item label_long [ END_TIMESTAMP [ START_TIMESTAMP ] ]
628 Returns a longer string label for this acccount ("Real Name <username@domain>"
629 if available, or "username@domain").
631 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
638 my $label = $self->label(@_);
639 my $finger = $self->finger;
640 return $label unless $finger =~ /\S/;
641 my $maxlen = 40 - length($label) - length($self->cust_svc->part_svc->svc);
642 $finger = substr($finger, 0, $maxlen-3).'...' if length($finger) > $maxlen;
646 =item insert [ , OPTION => VALUE ... ]
648 Adds this account to the database. If there is an error, returns the error,
649 otherwise returns false.
651 The additional fields pkgnum and svcpart (see L<FS::cust_svc>) should be
652 defined. An FS::cust_svc record will be created and inserted.
654 The additional field I<usergroup> can optionally be defined; if so it should
655 contain an arrayref of group names. See L<FS::radius_usergroup>.
657 The additional field I<child_objects> can optionally be defined; if so it
658 should contain an arrayref of FS::tablename objects. They will have their
659 svcnum fields set and will be inserted after this record, but before any
660 exports are run. Each element of the array can also optionally be a
661 two-element array reference containing the child object and the name of an
662 alternate field to be filled in with the newly-inserted svcnum, for example
663 C<[ $svc_forward, 'srcsvc' ]>
665 Currently available options are: I<depend_jobnum>
667 If I<depend_jobnum> is set (to a scalar jobnum or an array reference of
668 jobnums), all provisioning jobs will have a dependancy on the supplied
669 jobnum(s) (they will not run until the specific job(s) complete(s)).
671 (TODOC: L<FS::queue> and L<freeside-queued>)
673 (TODOC: new exports!)
682 warn "[$me] insert called on $self: ". Dumper($self).
683 "\nwith options: ". Dumper(%options);
686 local $SIG{HUP} = 'IGNORE';
687 local $SIG{INT} = 'IGNORE';
688 local $SIG{QUIT} = 'IGNORE';
689 local $SIG{TERM} = 'IGNORE';
690 local $SIG{TSTP} = 'IGNORE';
691 local $SIG{PIPE} = 'IGNORE';
693 my $oldAutoCommit = $FS::UID::AutoCommit;
694 local $FS::UID::AutoCommit = 0;
698 my $error = $self->SUPER::insert( # usergroup is here
699 'jobnums' => \@jobnums,
700 'child_objects' => $self->child_objects,
704 $dbh->rollback if $oldAutoCommit;
708 unless ( $skip_fuzzyfiles ) {
709 $error = $self->queue_fuzzyfiles_update;
711 $dbh->rollback if $oldAutoCommit;
712 return "updating fuzzy search cache: $error";
716 my $cust_pkg = $self->cust_svc->cust_pkg;
719 my $cust_main = $cust_pkg->cust_main;
720 my $agentnum = $cust_main->agentnum;
722 if ( $conf->exists('emailinvoiceautoalways')
723 || $conf->exists('emailinvoiceauto')
724 && ! $cust_main->invoicing_list_emailonly
726 my @invoicing_list = $cust_main->invoicing_list;
727 push @invoicing_list, $self->email;
728 $cust_main->invoicing_list(\@invoicing_list);
732 my @welcome_exclude_svcparts = $conf->config('svc_acct_welcome_exclude');
733 unless ( grep { $_ eq $self->svcpart } @welcome_exclude_svcparts ) {
735 my $msgnum = $conf->config('welcome_msgnum', $agentnum);
737 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
738 $error = $msg_template->send('cust_main' => $cust_main,
742 my ($to,$welcome_template,$welcome_from,$welcome_subject,$welcome_subject_template,$welcome_mimetype)
743 = ('','','','','','');
745 if ( $conf->exists('welcome_email', $agentnum) ) {
746 $welcome_template = new Text::Template (
748 SOURCE => [ map "$_\n", $conf->config('welcome_email', $agentnum) ]
749 ) or warn "can't create welcome email template: $Text::Template::ERROR";
750 $welcome_from = $conf->config('welcome_email-from', $agentnum);
751 # || 'your-isp-is-dum'
752 $welcome_subject = $conf->config('welcome_email-subject', $agentnum)
754 $welcome_subject_template = new Text::Template (
756 SOURCE => $welcome_subject,
757 ) or warn "can't create welcome email subject template: $Text::Template::ERROR";
758 $welcome_mimetype = $conf->config('welcome_email-mimetype', $agentnum)
761 if ( $welcome_template ) {
762 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ } $cust_main->invoicing_list );
766 'custnum' => $self->custnum,
767 'username' => $self->username,
768 'password' => $self->_password,
769 'first' => $cust_main->first,
770 'last' => $cust_main->getfield('last'),
771 'pkg' => $cust_pkg->part_pkg->pkg,
773 my $wqueue = new FS::queue {
774 'svcnum' => $self->svcnum,
775 'job' => 'FS::svc_acct::send_email'
777 my $error = $wqueue->insert(
779 'from' => $welcome_from,
780 'subject' => $welcome_subject_template->fill_in( HASH => \%hash, ),
781 'mimetype' => $welcome_mimetype,
782 'body' => $welcome_template->fill_in( HASH => \%hash, ),
785 $dbh->rollback if $oldAutoCommit;
786 return "error queuing welcome email: $error";
789 if ( $options{'depend_jobnum'} ) {
790 warn "$me depend_jobnum found; adding to welcome email dependancies"
792 if ( ref($options{'depend_jobnum'}) ) {
793 warn "$me adding jobs ". join(', ', @{$options{'depend_jobnum'}} ).
794 "to welcome email dependancies"
796 push @jobnums, @{ $options{'depend_jobnum'} };
798 warn "$me adding job $options{'depend_jobnum'} ".
799 "to welcome email dependancies"
801 push @jobnums, $options{'depend_jobnum'};
805 foreach my $jobnum ( @jobnums ) {
806 my $error = $wqueue->depend_insert($jobnum);
808 $dbh->rollback if $oldAutoCommit;
809 return "error queuing welcome email job dependancy: $error";
815 } # if $welcome_template
820 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
824 # set usage fields and thresholds if unset but set in a package def
825 # AND the package already has a last bill date (otherwise they get double added)
826 sub preinsert_hook_first {
829 return '' unless $self->pkgnum;
831 my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
832 return '' unless $cust_pkg && $cust_pkg->last_bill;
834 my $part_pkg = $cust_pkg->part_pkg;
835 return '' unless $part_pkg && $part_pkg->can('usage_valuehash');
837 my %values = $part_pkg->usage_valuehash;
838 my $multiplier = $conf->exists('svc_acct-usage_threshold')
839 ? 1 - $conf->config('svc_acct-usage_threshold')/100
840 : 0.20; #doesn't matter
842 foreach ( keys %values ) {
843 next if $self->getfield($_);
844 $self->setfield( $_, $values{$_} );
845 $self->setfield( $_. '_threshold', int( $values{$_} * $multiplier ) )
846 if $conf->exists('svc_acct-usage_threshold');
854 Deletes this account from the database. If there is an error, returns the
855 error, otherwise returns false.
857 The corresponding FS::cust_svc record will be deleted as well.
859 (TODOC: new exports!)
866 return "can't delete system account" if $self->_check_system;
868 return "Can't delete an account which is a (svc_forward) source!"
869 if qsearch( 'svc_forward', { 'srcsvc' => $self->svcnum } );
871 return "Can't delete an account which is a (svc_forward) destination!"
872 if qsearch( 'svc_forward', { 'dstsvc' => $self->svcnum } );
874 return "Can't delete an account with (svc_www) web service!"
875 if qsearch( 'svc_www', { 'usersvc' => $self->svcnum } );
877 # what about records in session ? (they should refer to history table)
879 local $SIG{HUP} = 'IGNORE';
880 local $SIG{INT} = 'IGNORE';
881 local $SIG{QUIT} = 'IGNORE';
882 local $SIG{TERM} = 'IGNORE';
883 local $SIG{TSTP} = 'IGNORE';
884 local $SIG{PIPE} = 'IGNORE';
886 my $oldAutoCommit = $FS::UID::AutoCommit;
887 local $FS::UID::AutoCommit = 0;
890 foreach my $cust_main_invoice (
891 qsearch( 'cust_main_invoice', { 'dest' => $self->svcnum } )
893 unless ( defined($cust_main_invoice) ) {
894 warn "WARNING: something's wrong with qsearch";
897 my %hash = $cust_main_invoice->hash;
898 $hash{'dest'} = $self->email;
899 my $new = new FS::cust_main_invoice \%hash;
900 my $error = $new->replace($cust_main_invoice);
902 $dbh->rollback if $oldAutoCommit;
907 foreach my $svc_domain (
908 qsearch( 'svc_domain', { 'catchall' => $self->svcnum } )
910 my %hash = new FS::svc_domain->hash;
911 $hash{'catchall'} = '';
912 my $new = new FS::svc_domain \%hash;
913 my $error = $new->replace($svc_domain);
915 $dbh->rollback if $oldAutoCommit;
920 my $error = $self->SUPER::delete; # usergroup here
922 $dbh->rollback if $oldAutoCommit;
926 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
930 =item replace OLD_RECORD
932 Replaces OLD_RECORD with this one in the database. If there is an error,
933 returns the error, otherwise returns false.
935 The additional field I<usergroup> can optionally be defined; if so it should
936 contain an arrayref of group names. See L<FS::radius_usergroup>.
944 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
948 warn "$me replacing $old with $new\n" if $DEBUG;
952 return "can't modify system account" if $old->_check_system;
955 #no warnings 'numeric'; #alas, a 5.006-ism
958 foreach my $xid (qw( uid gid )) {
960 return "Can't change $xid!"
961 if ! $conf->exists("svc_acct-edit_$xid")
962 && $old->$xid() != $new->$xid()
963 && $new->cust_svc->part_svc->part_svc_column($xid)->columnflag ne 'F'
968 return "can't change username"
969 if $old->username ne $new->username
970 && $conf->exists('svc_acct-no_edit_username');
972 #change homdir when we change username
973 $new->setfield('dir', '') if $old->username ne $new->username;
975 local $SIG{HUP} = 'IGNORE';
976 local $SIG{INT} = 'IGNORE';
977 local $SIG{QUIT} = 'IGNORE';
978 local $SIG{TERM} = 'IGNORE';
979 local $SIG{TSTP} = 'IGNORE';
980 local $SIG{PIPE} = 'IGNORE';
982 my $oldAutoCommit = $FS::UID::AutoCommit;
983 local $FS::UID::AutoCommit = 0;
986 $error = $new->SUPER::replace($old, @_); # usergroup here
988 $dbh->rollback if $oldAutoCommit;
989 return $error if $error;
992 if ( $new->username ne $old->username && ! $skip_fuzzyfiles ) {
993 $error = $new->queue_fuzzyfiles_update;
995 $dbh->rollback if $oldAutoCommit;
996 return "updating fuzzy search cache: $error";
1000 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1004 =item queue_fuzzyfiles_update
1006 Used by insert & replace to update the fuzzy search cache
1010 sub queue_fuzzyfiles_update {
1013 local $SIG{HUP} = 'IGNORE';
1014 local $SIG{INT} = 'IGNORE';
1015 local $SIG{QUIT} = 'IGNORE';
1016 local $SIG{TERM} = 'IGNORE';
1017 local $SIG{TSTP} = 'IGNORE';
1018 local $SIG{PIPE} = 'IGNORE';
1020 my $oldAutoCommit = $FS::UID::AutoCommit;
1021 local $FS::UID::AutoCommit = 0;
1024 my $queue = new FS::queue {
1025 'svcnum' => $self->svcnum,
1026 'job' => 'FS::svc_acct::append_fuzzyfiles'
1028 my $error = $queue->insert($self->username);
1030 $dbh->rollback if $oldAutoCommit;
1031 return "queueing job (transaction rolled back): $error";
1034 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1042 Suspends this account by calling export-specific suspend hooks. If there is
1043 an error, returns the error, otherwise returns false.
1045 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1051 return "can't suspend system account" if $self->_check_system;
1052 $self->SUPER::suspend(@_);
1057 Unsuspends this account by by calling export-specific suspend hooks. If there
1058 is an error, returns the error, otherwise returns false.
1060 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
1066 my %hash = $self->hash;
1067 if ( $hash{_password} =~ /^\*SUSPENDED\* (.*)$/ ) {
1068 $hash{_password} = $1;
1069 my $new = new FS::svc_acct ( \%hash );
1070 my $error = $new->replace($self);
1071 return $error if $error;
1074 $self->SUPER::unsuspend(@_);
1079 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
1081 If the B<auto_unset_catchall> configuration option is set, this method will
1082 automatically remove any references to the canceled service in the catchall
1083 field of svc_domain. This allows packages that contain both a svc_domain and
1084 its catchall svc_acct to be canceled in one step.
1089 # Only one thing to do at this level
1091 foreach my $svc_domain (
1092 qsearch( 'svc_domain', { catchall => $self->svcnum } ) ) {
1093 if($conf->exists('auto_unset_catchall')) {
1094 my %hash = $svc_domain->hash;
1095 $hash{catchall} = '';
1096 my $new = new FS::svc_domain ( \%hash );
1097 my $error = $new->replace($svc_domain);
1098 return $error if $error;
1100 return "cannot unprovision svc_acct #".$self->svcnum.
1101 " while assigned as catchall for svc_domain #".$svc_domain->svcnum;
1105 $self->SUPER::cancel(@_);
1111 Checks all fields to make sure this is a valid service. If there is an error,
1112 returns the error, otherwise returns false. Called by the insert and replace
1115 Sets any fixed values; see L<FS::part_svc>.
1122 my($recref) = $self->hashref;
1124 my $x = $self->setfixed;
1125 return $x unless ref($x);
1128 my $error = $self->ut_numbern('svcnum')
1129 #|| $self->ut_number('domsvc')
1130 || $self->ut_foreign_key( 'domsvc', 'svc_domain', 'svcnum' )
1131 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
1132 || $self->ut_foreign_keyn('sectornum','tower_sector','sectornum')
1133 || $self->ut_foreign_keyn('routernum','router','routernum')
1134 || $self->ut_foreign_keyn('blocknum','addr_block','blocknum')
1135 || $self->ut_textn('sec_phrase')
1136 || $self->ut_snumbern('seconds')
1137 || $self->ut_snumbern('upbytes')
1138 || $self->ut_snumbern('downbytes')
1139 || $self->ut_snumbern('totalbytes')
1140 || $self->ut_snumbern('seconds_threshold')
1141 || $self->ut_snumbern('upbytes_threshold')
1142 || $self->ut_snumbern('downbytes_threshold')
1143 || $self->ut_snumbern('totalbytes_threshold')
1144 || $self->ut_enum('_password_encoding', ['',qw(plain crypt ldap)])
1145 || $self->ut_enum('password_selfchange', [ '', 'Y' ])
1146 || $self->ut_enum('password_recover', [ '', 'Y' ])
1148 || $self->ut_anything('cf_privatekey')
1150 || $self->ut_textn('cgp_accessmodes')
1151 || $self->ut_alphan('cgp_type')
1152 || $self->ut_textn('cgp_aliases' ) #well
1154 || $self->ut_alphasn('cgp_rulesallowed')
1155 || $self->ut_enum('cgp_rpopallowed', [ '', 'Y' ])
1156 || $self->ut_enum('cgp_mailtoall', [ '', 'Y' ])
1157 || $self->ut_enum('cgp_addmailtrailer', [ '', 'Y' ])
1158 || $self->ut_snumbern('cgp_archiveafter')
1160 || $self->ut_alphasn('cgp_deletemode')
1161 || $self->ut_enum('cgp_emptytrash', $self->cgp_emptytrash_values)
1162 || $self->ut_alphan('cgp_language')
1163 || $self->ut_textn('cgp_timezone')
1164 || $self->ut_textn('cgp_skinname')
1165 || $self->ut_textn('cgp_prontoskinname')
1166 || $self->ut_alphan('cgp_sendmdnmode')
1168 return $error if $error;
1170 # assign IP address, etc.
1171 if ( $conf->exists('svc_acct-ip_addr') ) {
1172 my $error = $self->svc_ip_check;
1173 return $error if $error;
1174 } else { # I think this is correct
1175 $self->routernum('');
1176 $self->blocknum('');
1180 local $username_letter = $username_letter;
1181 local $username_uppercase = $username_uppercase;
1182 if ($self->svcnum) {
1183 my $cust_svc = $self->cust_svc
1184 or return "no cust_svc record found for svcnum ". $self->svcnum;
1185 my $cust_pkg = $cust_svc->cust_pkg;
1187 if ($self->pkgnum) {
1188 $cust_pkg = qsearchs('cust_pkg', { 'pkgnum' => $self->pkgnum } );#complain?
1192 $conf->exists('username-letter', $cust_pkg->cust_main->agentnum);
1193 $username_uppercase =
1194 $conf->exists('username-uppercase', $cust_pkg->cust_main->agentnum);
1197 my $ulen = $usernamemax || $self->dbdef_table->column('username')->length;
1199 $recref->{username} =~ /^([a-z0-9_\-\.\&\%\:\/\=\#\!]{$usernamemin,$ulen})$/i
1200 or return gettext('illegal_username'). " ($usernamemin-$ulen): ". $recref->{username};
1201 $recref->{username} = $1;
1203 my $uerror = gettext('illegal_username'). ': '. $recref->{username};
1205 unless ( $username_uppercase ) {
1206 $recref->{username} =~ /[A-Z]/ and return $uerror;
1208 if ( $username_letterfirst ) {
1209 $recref->{username} =~ /^[a-z]/ or return $uerror;
1210 } elsif ( $username_letter ) {
1211 $recref->{username} =~ /[a-z]/ or return $uerror;
1213 if ( $username_noperiod ) {
1214 $recref->{username} =~ /\./ and return $uerror;
1216 if ( $username_nounderscore ) {
1217 $recref->{username} =~ /_/ and return $uerror;
1219 if ( $username_nodash ) {
1220 $recref->{username} =~ /\-/ and return $uerror;
1222 unless ( $username_ampersand ) {
1223 $recref->{username} =~ /\&/ and return $uerror;
1225 unless ( $username_percent ) {
1226 $recref->{username} =~ /\%/ and return $uerror;
1228 unless ( $username_colon ) {
1229 $recref->{username} =~ /\:/ and return $uerror;
1231 unless ( $username_slash ) {
1232 $recref->{username} =~ /\// and return $uerror;
1234 unless ( $username_equals ) {
1235 $recref->{username} =~ /\=/ and return $uerror;
1237 unless ( $username_pound ) {
1238 $recref->{username} =~ /\#/ and return $uerror;
1240 unless ( $username_exclamation ) {
1241 $recref->{username} =~ /\!/ and return $uerror;
1245 $recref->{popnum} =~ /^(\d*)$/ or return "Illegal popnum: ".$recref->{popnum};
1246 $recref->{popnum} = $1;
1247 return "Unknown popnum" unless
1248 ! $recref->{popnum} ||
1249 qsearchs('svc_acct_pop',{'popnum'=> $recref->{popnum} } );
1251 unless ( $part_svc->part_svc_column('uid')->columnflag eq 'F' ) {
1253 $recref->{uid} =~ /^(\d*)$/ or return "Illegal uid";
1254 $recref->{uid} = $1 eq '' ? $self->unique('uid') : $1;
1256 $recref->{gid} =~ /^(\d*)$/ or return "Illegal gid";
1257 $recref->{gid} = $1 eq '' ? $recref->{uid} : $1;
1258 #not all systems use gid=uid
1259 #you can set a fixed gid in part_svc
1261 return "Only root can have uid 0"
1262 if $recref->{uid} == 0
1263 && $recref->{username} !~ /^(root|toor|smtp)$/;
1265 unless ( $recref->{username} eq 'sync' ) {
1266 if ( grep $_ eq $recref->{shell}, @shells ) {
1267 $recref->{shell} = (grep $_ eq $recref->{shell}, @shells)[0];
1269 return "Illegal shell \`". $self->shell. "\'; ".
1270 "shells configuration value contains: @shells";
1273 $recref->{shell} = '/bin/sync';
1277 $recref->{gid} ne '' ?
1278 return "Can't have gid without uid" : ( $recref->{gid}='' );
1279 #$recref->{dir} ne '' ?
1280 # return "Can't have directory without uid" : ( $recref->{dir}='' );
1281 $recref->{shell} ne '' ?
1282 return "Can't have shell without uid" : ( $recref->{shell}='' );
1285 unless ( $part_svc->part_svc_column('dir')->columnflag eq 'F' ) {
1287 $recref->{dir} =~ /^([\/\w\-\.\&\:\#]*)$/
1288 or return "Illegal directory: ". $recref->{dir};
1289 $recref->{dir} = $1;
1290 return "Illegal directory"
1291 if $recref->{dir} =~ /(^|\/)\.+(\/|$)/; #no .. component
1292 return "Illegal directory"
1293 if $recref->{dir} =~ /\&/ && ! $username_ampersand;
1294 unless ( $recref->{dir} ) {
1295 $recref->{dir} = $dir_prefix . '/';
1296 if ( $dirhash > 0 ) {
1297 for my $h ( 1 .. $dirhash ) {
1298 $recref->{dir} .= substr($recref->{username}, $h-1, 1). '/';
1300 } elsif ( $dirhash < 0 ) {
1301 for my $h ( reverse $dirhash .. -1 ) {
1302 $recref->{dir} .= substr($recref->{username}, $h, 1). '/';
1305 $recref->{dir} .= $recref->{username};
1311 if ( $self->getfield('finger') eq '' ) {
1312 my $cust_pkg = $self->svcnum
1313 ? $self->cust_svc->cust_pkg
1314 : qsearchs('cust_pkg', { 'pkgnum' => $self->getfield('pkgnum') } );
1316 my $cust_main = $cust_pkg->cust_main;
1317 $self->setfield('finger', $cust_main->first.' '.$cust_main->get('last') );
1320 # $error = $self->ut_textn('finger');
1321 # return $error if $error;
1322 $self->getfield('finger') =~ /^([\w \,\.\-\'\&\t\!\@\#\$\%\(\)\+\;\"\?\/\*\<\>]*)$/
1323 or return "Illegal finger: ". $self->getfield('finger');
1324 $self->setfield('finger', $1);
1326 for (qw( quota file_quota file_maxsize )) {
1327 $recref->{$_} =~ /^(\w*)$/ or return "Illegal $_";
1330 $recref->{file_maxnum} =~ /^\s*(\d*)\s*$/ or return "Illegal file_maxnum";
1331 $recref->{file_maxnum} = $1;
1333 unless ( $part_svc->part_svc_column('slipip')->columnflag eq 'F' ) {
1334 if ( $recref->{slipip} eq '' ) {
1335 $recref->{slipip} = ''; # eh?
1336 } elsif ( $recref->{slipip} eq '0e0' ) {
1337 $recref->{slipip} = '0e0';
1339 $recref->{slipip} =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/
1340 or return "Illegal slipip: ". $self->slipip;
1341 $recref->{slipip} = $1;
1345 #arbitrary RADIUS stuff; allow ut_textn for now
1346 foreach ( grep /^radius_/, fields('svc_acct') ) {
1347 $self->ut_textn($_);
1350 # First, if _password is blank, generate one and set default encoding.
1351 if ( ! $recref->{_password} ) {
1352 $error = $self->set_password('');
1354 # But if there's a _password but no encoding, assume it's plaintext and
1355 # set it to default encoding.
1356 elsif ( ! $recref->{_password_encoding} ) {
1357 $error = $self->set_password($recref->{_password});
1359 return $error if $error;
1361 # Next, check _password to ensure compliance with the encoding.
1362 if ( $recref->{_password_encoding} eq 'ldap' ) {
1364 if ( $recref->{_password} =~ /^(\{[\w\-]+\})(!?.{0,64})$/ ) {
1365 $recref->{_password} = uc($1).$2;
1367 return 'Illegal (ldap-encoded) password: '. $recref->{_password};
1370 } elsif ( $recref->{_password_encoding} eq 'crypt' ) {
1372 if ( $recref->{_password} =~
1373 #/^(\$\w+\$.*|[\w\+\/]{13}|_[\w\+\/]{19}|\*)$/
1374 /^(!!?)?(\$\w+\$.*|[\w\+\/\.]{13}|_[\w\+\/\.]{19}|\*)$/
1377 $recref->{_password} = ( defined($1) ? $1 : '' ). $2;
1380 return 'Illegal (crypt-encoded) password: '. $recref->{_password};
1383 } elsif ( $recref->{_password_encoding} eq 'plain' ) {
1384 # Password randomization is now in set_password.
1385 # Strip whitespace characters, check length requirements, etc.
1386 if ( $recref->{_password} =~ /^([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1387 $recref->{_password} = $1;
1389 return gettext('illegal_password'). " $passwordmin-$passwordmax ".
1390 FS::Msgcat::_gettext('illegal_password_characters').
1391 ": ". $recref->{_password};
1394 if ( $password_noampersand ) {
1395 $recref->{_password} =~ /\&/ and return gettext('illegal_password');
1397 if ( $password_noexclamation ) {
1398 $recref->{_password} =~ /\!/ and return gettext('illegal_password');
1402 return "invalid password encoding ('".$recref->{_password_encoding}."'";
1405 $self->SUPER::check;
1410 sub _password_encryption {
1412 my $encoding = lc($self->_password_encoding);
1413 return if !$encoding;
1414 return 'plain' if $encoding eq 'plain';
1415 if($encoding eq 'crypt') {
1416 my $pass = $self->_password;
1417 $pass =~ s/^\*SUSPENDED\* //;
1419 return 'md5' if $pass =~ /^\$1\$/;
1420 #return 'blowfish' if $self->_password =~ /^\$2\$/;
1421 return 'des' if length($pass) == 13;
1424 if($encoding eq 'ldap') {
1425 uc($self->_password) =~ /^\{([\w-]+)\}/;
1426 return 'crypt' if $1 eq 'CRYPT' or $1 eq 'DES';
1427 return 'plain' if $1 eq 'PLAIN' or $1 eq 'CLEARTEXT';
1428 return 'md5' if $1 eq 'MD5';
1429 return 'sha1' if $1 eq 'SHA' or $1 eq 'SHA-1';
1436 sub get_cleartext_password {
1438 if($self->_password_encryption eq 'plain') {
1439 if($self->_password_encoding eq 'ldap') {
1440 $self->_password =~ /\{\w+\}(.*)$/;
1444 return $self->_password;
1453 Set the cleartext password for the account. If _password_encoding is set, the
1454 new password will be encoded according to the existing method (including
1455 encryption mode, if it can be determined). Otherwise,
1456 config('default-password-encoding') is used.
1458 If no password is supplied (or a zero-length password when minimum password length
1459 is >0), one will be generated randomly.
1464 my( $self, $pass ) = ( shift, shift );
1466 warn "[$me] set_password (to $pass) called on $self: ". Dumper($self)
1469 my $failure = gettext('illegal_password'). " $passwordmin-$passwordmax ".
1470 FS::Msgcat::_gettext('illegal_password_characters').
1473 my( $encoding, $encryption ) = ('', '');
1475 if ( $self->_password_encoding ) {
1476 $encoding = $self->_password_encoding;
1477 # identify existing encryption method, try to use it.
1478 $encryption = $self->_password_encryption;
1480 # use the system default
1486 # set encoding to system default
1487 ($encoding, $encryption) =
1488 split(/-/, lc($conf->config('default-password-encoding') || ''));
1489 $encoding ||= 'legacy';
1490 $self->_password_encoding($encoding);
1493 if ( $encoding eq 'legacy' ) {
1495 # The legacy behavior from check():
1496 # If the password is blank, randomize it and set encoding to 'plain'.
1497 if(!defined($pass) or (length($pass) == 0 and $passwordmin)) {
1498 $pass = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
1499 $self->_password_encoding('plain');
1501 # Prefix + valid-length password
1502 if ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([^\t\n]{$passwordmin,$passwordmax})$/ ) {
1504 $self->_password_encoding('plain');
1505 # Prefix + crypt string
1506 } elsif ( $pass =~ /^((\*SUSPENDED\* |!!?)?)([\w\.\/\$\;\+]{13,64})$/ ) {
1508 $self->_password_encoding('crypt');
1509 # Various disabled crypt passwords
1510 } elsif ( $pass eq '*' || $pass eq '!' || $pass eq '!!' ) {
1511 $self->_password_encoding('crypt');
1517 $self->_password($pass);
1523 if $passwordmin && length($pass) < $passwordmin
1524 or $passwordmax && length($pass) > $passwordmax;
1526 if ( $encoding eq 'crypt' ) {
1527 if ($encryption eq 'md5') {
1528 $pass = unix_md5_crypt($pass);
1529 } elsif ($encryption eq 'des') {
1530 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1533 } elsif ( $encoding eq 'ldap' ) {
1534 if ($encryption eq 'md5') {
1535 $pass = md5_base64($pass);
1536 } elsif ($encryption eq 'sha1') {
1537 $pass = sha1_base64($pass);
1538 } elsif ($encryption eq 'crypt') {
1539 $pass = crypt($pass, $saltset[int(rand(64))].$saltset[int(rand(64))]);
1541 # else $encryption eq 'plain', do nothing
1542 $pass .= '=' x (4 - length($pass) % 4) #properly padded base64
1543 if $encryption eq 'md5' || $encryption eq 'sha1';
1544 $pass = '{'.uc($encryption).'}'.$pass;
1546 # else encoding eq 'plain'
1548 $self->_password($pass);
1554 Internal function to check the username against the list of system usernames
1555 from the I<system_usernames> configuration value. Returns true if the username
1556 is listed on the system username list.
1562 scalar( grep { $self->username eq $_ || $self->email eq $_ }
1563 $conf->config('system_usernames')
1567 =item _check_duplicate
1569 Internal method to check for duplicates usernames, username@domain pairs and
1572 If the I<global_unique-username> configuration value is set to B<username> or
1573 B<username@domain>, enforces global username or username@domain uniqueness.
1575 In all cases, check for duplicate uids and usernames or username@domain pairs
1576 per export and with identical I<svcpart> values.
1580 sub _check_duplicate {
1583 my $global_unique = $conf->config('global_unique-username') || 'none';
1584 return '' if $global_unique eq 'disabled';
1588 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
1589 unless ( $part_svc ) {
1590 return 'unknown svcpart '. $self->svcpart;
1593 my @dup_user = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1594 qsearch( 'svc_acct', { 'username' => $self->username } );
1595 return gettext('username_in_use')
1596 if $global_unique eq 'username' && @dup_user;
1598 my @dup_userdomain = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1599 qsearch( 'svc_acct', { 'username' => $self->username,
1600 'domsvc' => $self->domsvc } );
1601 return gettext('username_in_use')
1602 if $global_unique eq 'username@domain' && @dup_userdomain;
1605 if ( $part_svc->part_svc_column('uid')->columnflag ne 'F'
1606 && $self->username !~ /^(toor|(hyla)?fax)$/ ) {
1607 @dup_uid = grep { !$self->svcnum || $_->svcnum != $self->svcnum }
1608 qsearch( 'svc_acct', { 'uid' => $self->uid } );
1613 if ( @dup_user || @dup_userdomain || @dup_uid ) {
1614 my $exports = FS::part_export::export_info('svc_acct');
1615 my %conflict_user_svcpart;
1616 my %conflict_userdomain_svcpart = ( $self->svcpart => 'SELF', );
1618 foreach my $part_export ( $part_svc->part_export ) {
1620 #this will catch to the same exact export
1621 my @svcparts = map { $_->svcpart } $part_export->export_svc;
1623 #this will catch to exports w/same exporthost+type ???
1624 #my @other_part_export = qsearch('part_export', {
1625 # 'machine' => $part_export->machine,
1626 # 'exporttype' => $part_export->exporttype,
1628 #foreach my $other_part_export ( @other_part_export ) {
1629 # push @svcparts, map { $_->svcpart }
1630 # qsearch('export_svc', { 'exportnum' => $part_export->exportnum });
1633 #my $nodomain = $exports->{$part_export->exporttype}{'nodomain'};
1634 #silly kludge to avoid uninitialized value errors
1635 my $nodomain = exists( $exports->{$part_export->exporttype}{'nodomain'} )
1636 ? $exports->{$part_export->exporttype}{'nodomain'}
1638 if ( $nodomain =~ /^Y/i ) {
1639 $conflict_user_svcpart{$_} = $part_export->exportnum
1642 $conflict_userdomain_svcpart{$_} = $part_export->exportnum
1647 foreach my $dup_user ( @dup_user ) {
1648 my $dup_svcpart = $dup_user->cust_svc->svcpart;
1649 if ( exists($conflict_user_svcpart{$dup_svcpart}) ) {
1650 return "duplicate username ". $self->username.
1651 ": conflicts with svcnum ". $dup_user->svcnum.
1652 " via exportnum ". $conflict_user_svcpart{$dup_svcpart};
1656 foreach my $dup_userdomain ( @dup_userdomain ) {
1657 my $dup_svcpart = $dup_userdomain->cust_svc->svcpart;
1658 if ( exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1659 return "duplicate username\@domain ". $self->email.
1660 ": conflicts with svcnum ". $dup_userdomain->svcnum.
1661 " via exportnum ". $conflict_userdomain_svcpart{$dup_svcpart};
1665 foreach my $dup_uid ( @dup_uid ) {
1666 my $dup_svcpart = $dup_uid->cust_svc->svcpart;
1667 if ( exists($conflict_user_svcpart{$dup_svcpart})
1668 || exists($conflict_userdomain_svcpart{$dup_svcpart}) ) {
1669 return "duplicate uid ". $self->uid.
1670 ": conflicts with svcnum ". $dup_uid->svcnum.
1672 ( $conflict_user_svcpart{$dup_svcpart}
1673 || $conflict_userdomain_svcpart{$dup_svcpart} );
1685 Depriciated, use radius_reply instead.
1690 carp "FS::svc_acct::radius depriciated, use radius_reply";
1691 $_[0]->radius_reply;
1696 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1697 reply attributes of this record.
1699 Note that this is now the preferred method for reading RADIUS attributes -
1700 accessing the columns directly is discouraged, as the column names are
1701 expected to change in the future.
1708 return %{ $self->{'radius_reply'} }
1709 if exists $self->{'radius_reply'};
1714 my($column, $attrib) = ($1, $2);
1715 #$attrib =~ s/_/\-/g;
1716 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1717 } grep { /^radius_/ && $self->getfield($_) } fields( $self->table );
1719 if ( $self->slipip && $self->slipip ne '0e0' ) {
1720 $reply{$radius_ip} = $self->slipip;
1723 if ( $self->seconds !~ /^$/ ) {
1724 $reply{'Session-Timeout'} = $self->seconds;
1727 if ( $conf->exists('radius-chillispot-max') ) {
1728 #http://dev.coova.org/svn/coova-chilli/doc/dictionary.chillispot
1730 #hmm. just because sqlradius.pm says so?
1737 foreach my $what (qw( input output total )) {
1738 my $is = $whatis{$what}.'bytes';
1739 if ( $self->$is() =~ /\d/ ) {
1740 my $big = new Math::BigInt $self->$is();
1741 $big = new Math::BigInt '0' if $big->is_neg();
1742 my $att = "Chillispot-Max-\u$what";
1743 $reply{"$att-Octets"} = $big->copy->band(0xffffffff)->bstr;
1744 $reply{"$att-Gigawords"} = $big->copy->brsft(32)->bstr;
1755 Returns key/value pairs, suitable for assigning to a hash, for any RADIUS
1756 check attributes of this record.
1758 Note that this is now the preferred method for reading RADIUS attributes -
1759 accessing the columns directly is discouraged, as the column names are
1760 expected to change in the future.
1767 return %{ $self->{'radius_check'} }
1768 if exists $self->{'radius_check'};
1773 my($column, $attrib) = ($1, $2);
1774 #$attrib =~ s/_/\-/g;
1775 ( $FS::raddb::attrib{lc($attrib)}, $self->getfield($column) );
1776 } grep { /^rc_/ && $self->getfield($_) } fields( $self->table );
1779 my($pw_attrib, $password) = $self->radius_password;
1780 $check{$pw_attrib} = $password;
1782 my $cust_svc = $self->cust_svc;
1784 my $cust_pkg = $cust_svc->cust_pkg;
1785 if ( $cust_pkg && $cust_pkg->part_pkg->is_prepaid && $cust_pkg->bill ) {
1786 $check{'Expiration'} = time2str('%B %e %Y %T', $cust_pkg->bill ); #http://lists.cistron.nl/pipermail/freeradius-users/2005-January/040184.html
1789 warn "WARNING: no cust_svc record for svc_acct.svcnum ". $self->svcnum.
1790 "; can't set Expiration\n"
1798 =item radius_password
1800 Returns a key/value pair containing the RADIUS attribute name and value
1805 sub radius_password {
1809 if ( $self->_password_encoding eq 'ldap' ) {
1810 $pw_attrib = 'Password-With-Header';
1811 } elsif ( $self->_password_encoding eq 'crypt' ) {
1812 $pw_attrib = 'Crypt-Password';
1813 } elsif ( $self->_password_encoding eq 'plain' ) {
1814 $pw_attrib = $radius_password;
1816 $pw_attrib = length($self->_password) <= 12
1821 ($pw_attrib, $self->_password);
1827 This method instructs the object to "snapshot" or freeze RADIUS check and
1828 reply attributes to the current values.
1832 #bah, my english is too broken this morning
1833 #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
1834 #the FS::cust_pkg's replace method to trigger the correct export updates when
1835 #package dates change)
1840 $self->{$_} = { $self->$_() }
1841 foreach qw( radius_reply radius_check );
1845 =item forget_snapshot
1847 This methos instructs the object to forget any previously snapshotted
1848 RADIUS check and reply attributes.
1852 sub forget_snapshot {
1856 foreach qw( radius_reply radius_check );
1860 =item domain [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1862 Returns the domain associated with this account.
1864 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1871 die "svc_acct.domsvc is null for svcnum ". $self->svcnum unless $self->domsvc;
1872 my $svc_domain = $self->svc_domain(@_)
1873 or die "no svc_domain.svcnum for svc_acct.domsvc ". $self->domsvc;
1874 $svc_domain->domain;
1879 Returns the FS::cust_svc record for this account (see L<FS::cust_svc>).
1883 #inherited from svc_Common
1885 =item email [ END_TIMESTAMP [ START_TIMESTAMP ] ]
1887 Returns an email address associated with the account.
1889 END_TIMESTAMP and START_TIMESTAMP can optionally be passed when dealing with
1896 $self->username. '@'. $self->domain(@_);
1902 Returns an array of FS::acct_snarf records associated with the account.
1906 # unused as originally intended, but now by Communigate Pro "RPOP"
1908 =item cgp_rpop_hashref
1910 Returns an arrayref of RPOP data suitable for Communigate Pro API commands.
1914 sub cgp_rpop_hashref {
1916 { map { $_->snarfname => $_->cgp_hashref } $self->acct_snarf };
1919 =item decrement_upbytes OCTETS
1921 Decrements the I<upbytes> field of this record by the given amount. If there
1922 is an error, returns the error, otherwise returns false.
1926 sub decrement_upbytes {
1927 shift->_op_usage('-', 'upbytes', @_);
1930 =item increment_upbytes OCTETS
1932 Increments the I<upbytes> field of this record by the given amount. If there
1933 is an error, returns the error, otherwise returns false.
1937 sub increment_upbytes {
1938 shift->_op_usage('+', 'upbytes', @_);
1941 =item decrement_downbytes OCTETS
1943 Decrements the I<downbytes> field of this record by the given amount. If there
1944 is an error, returns the error, otherwise returns false.
1948 sub decrement_downbytes {
1949 shift->_op_usage('-', 'downbytes', @_);
1952 =item increment_downbytes OCTETS
1954 Increments the I<downbytes> field of this record by the given amount. If there
1955 is an error, returns the error, otherwise returns false.
1959 sub increment_downbytes {
1960 shift->_op_usage('+', 'downbytes', @_);
1963 =item decrement_totalbytes OCTETS
1965 Decrements the I<totalbytes> field of this record by the given amount. If there
1966 is an error, returns the error, otherwise returns false.
1970 sub decrement_totalbytes {
1971 shift->_op_usage('-', 'totalbytes', @_);
1974 =item increment_totalbytes OCTETS
1976 Increments the I<totalbytes> field of this record by the given amount. If there
1977 is an error, returns the error, otherwise returns false.
1981 sub increment_totalbytes {
1982 shift->_op_usage('+', 'totalbytes', @_);
1985 =item decrement_seconds SECONDS
1987 Decrements the I<seconds> field of this record by the given amount. If there
1988 is an error, returns the error, otherwise returns false.
1992 sub decrement_seconds {
1993 shift->_op_usage('-', 'seconds', @_);
1996 =item increment_seconds SECONDS
1998 Increments the I<seconds> field of this record by the given amount. If there
1999 is an error, returns the error, otherwise returns false.
2003 sub increment_seconds {
2004 shift->_op_usage('+', 'seconds', @_);
2012 my %op2condition = (
2013 '-' => sub { my($self, $column, $amount) = @_;
2014 $self->$column - $amount <= 0;
2016 '+' => sub { my($self, $column, $amount) = @_;
2017 ($self->$column || 0) + $amount > 0;
2020 my %op2warncondition = (
2021 '-' => sub { my($self, $column, $amount) = @_;
2022 my $threshold = $column . '_threshold';
2023 $self->$column - $amount <= $self->$threshold + 0;
2025 '+' => sub { my($self, $column, $amount) = @_;
2026 ($self->$column || 0) + $amount > 0;
2031 my( $self, $op, $column, $amount ) = @_;
2033 warn "$me _op_usage called for $column on svcnum ". $self->svcnum.
2034 ' ('. $self->email. "): $op $amount\n"
2037 return '' unless $amount;
2039 local $SIG{HUP} = 'IGNORE';
2040 local $SIG{INT} = 'IGNORE';
2041 local $SIG{QUIT} = 'IGNORE';
2042 local $SIG{TERM} = 'IGNORE';
2043 local $SIG{TSTP} = 'IGNORE';
2044 local $SIG{PIPE} = 'IGNORE';
2046 my $oldAutoCommit = $FS::UID::AutoCommit;
2047 local $FS::UID::AutoCommit = 0;
2050 my $sql = "UPDATE svc_acct SET $column = ".
2051 " CASE WHEN $column IS NULL THEN 0 ELSE $column END ". #$column||0
2052 " $op ? WHERE svcnum = ?";
2056 my $sth = $dbh->prepare( $sql )
2057 or die "Error preparing $sql: ". $dbh->errstr;
2058 my $rv = $sth->execute($amount, $self->svcnum);
2059 die "Error executing $sql: ". $sth->errstr
2060 unless defined($rv);
2061 die "Can't update $column for svcnum". $self->svcnum
2064 #$self->snapshot; #not necessary, we retain the old values
2065 #create an object with the updated usage values
2066 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2068 my $error = $new->replace($self);
2070 $dbh->rollback if $oldAutoCommit;
2071 return "Error replacing: $error";
2074 #overlimit_action eq 'cancel' handling
2075 my $cust_pkg = $self->cust_svc->cust_pkg;
2077 && $cust_pkg->part_pkg->option('overlimit_action', 1) eq 'cancel'
2078 && $op eq '-' && &{$op2condition{$op}}($self, $column, $amount)
2082 my $error = $cust_pkg->cancel; #XXX should have a reason
2084 $dbh->rollback if $oldAutoCommit;
2085 return "Error cancelling: $error";
2088 #nothing else is relevant if we're cancelling, so commit & return success
2089 warn "$me update successful; committing\n"
2091 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2096 my $action = $op2action{$op};
2098 if ( &{$op2condition{$op}}($self, $column, $amount) &&
2099 ( $action eq 'suspend' && !$self->overlimit
2100 || $action eq 'unsuspend' && $self->overlimit )
2103 my $error = $self->_op_overlimit($action);
2105 $dbh->rollback if $oldAutoCommit;
2111 if ( $conf->exists("svc_acct-usage_$action")
2112 && &{$op2condition{$op}}($self, $column, $amount) ) {
2113 #my $error = $self->$action();
2114 my $error = $self->cust_svc->cust_pkg->$action();
2115 # $error ||= $self->overlimit($action);
2117 $dbh->rollback if $oldAutoCommit;
2118 return "Error ${action}ing: $error";
2122 if ($warning_template && &{$op2warncondition{$op}}($self, $column, $amount)) {
2123 my $wqueue = new FS::queue {
2124 'svcnum' => $self->svcnum,
2125 'job' => 'FS::svc_acct::reached_threshold',
2130 $to = $warning_cc if &{$op2condition{$op}}($self, $column, $amount);
2134 my $error = $wqueue->insert(
2135 'svcnum' => $self->svcnum,
2137 'column' => $column,
2141 $dbh->rollback if $oldAutoCommit;
2142 return "Error queuing threshold activity: $error";
2146 warn "$me update successful; committing\n"
2148 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2154 my( $self, $action ) = @_;
2156 local $SIG{HUP} = 'IGNORE';
2157 local $SIG{INT} = 'IGNORE';
2158 local $SIG{QUIT} = 'IGNORE';
2159 local $SIG{TERM} = 'IGNORE';
2160 local $SIG{TSTP} = 'IGNORE';
2161 local $SIG{PIPE} = 'IGNORE';
2163 my $oldAutoCommit = $FS::UID::AutoCommit;
2164 local $FS::UID::AutoCommit = 0;
2167 my $cust_pkg = $self->cust_svc->cust_pkg;
2169 my @conf_overlimit =
2171 ? $conf->config('overlimit_groups', $cust_pkg->cust_main->agentnum )
2172 : $conf->config('overlimit_groups');
2174 foreach my $part_export ( $self->cust_svc->part_svc->part_export ) {
2176 my @groups = scalar(@conf_overlimit) ? @conf_overlimit
2177 : split(' ',$part_export->option('overlimit_groups'));
2178 next unless scalar(@groups);
2180 my $other = new FS::svc_acct $self->hashref;
2181 $other->usergroup(\@groups);
2184 if ($action eq 'suspend') {
2187 } else { # $action eq 'unsuspend'
2192 my $error = $part_export->export_replace($new, $old)
2193 || $self->overlimit($action);
2196 $dbh->rollback if $oldAutoCommit;
2197 return "Error replacing radius groups: $error";
2202 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2208 my( $self, $valueref, %options ) = @_;
2210 warn "$me set_usage called for svcnum ". $self->svcnum.
2211 ' ('. $self->email. "): ".
2212 join(', ', map { "$_ => " . $valueref->{$_}} keys %$valueref) . "\n"
2215 local $SIG{HUP} = 'IGNORE';
2216 local $SIG{INT} = 'IGNORE';
2217 local $SIG{QUIT} = 'IGNORE';
2218 local $SIG{TERM} = 'IGNORE';
2219 local $SIG{TSTP} = 'IGNORE';
2220 local $SIG{PIPE} = 'IGNORE';
2222 local $FS::svc_Common::noexport_hack = 1;
2223 my $oldAutoCommit = $FS::UID::AutoCommit;
2224 local $FS::UID::AutoCommit = 0;
2229 if ( $options{null} ) {
2230 %handyhash = ( map { ( $_ => undef, $_."_threshold" => undef ) }
2231 qw( seconds upbytes downbytes totalbytes )
2234 foreach my $field (keys %$valueref){
2235 $reset = 1 if $valueref->{$field};
2236 $self->setfield($field, $valueref->{$field});
2237 $self->setfield( $field.'_threshold',
2238 int($self->getfield($field)
2239 * ( $conf->exists('svc_acct-usage_threshold')
2240 ? 1 - $conf->config('svc_acct-usage_threshold')/100
2245 $handyhash{$field} = $self->getfield($field);
2246 $handyhash{$field.'_threshold'} = $self->getfield($field.'_threshold');
2248 #my $error = $self->replace; #NO! we avoid the call to ->check for
2249 #die $error if $error; #services not explicity changed via the UI
2251 my $sql = "UPDATE svc_acct SET " .
2252 join (',', map { "$_ = ?" } (keys %handyhash) ).
2253 " WHERE svcnum = ". $self->svcnum;
2258 if (scalar(keys %handyhash)) {
2259 my $sth = $dbh->prepare( $sql )
2260 or die "Error preparing $sql: ". $dbh->errstr;
2261 my $rv = $sth->execute(values %handyhash);
2262 die "Error executing $sql: ". $sth->errstr
2263 unless defined($rv);
2264 die "Can't update usage for svcnum ". $self->svcnum
2268 #$self->snapshot; #not necessary, we retain the old values
2269 #create an object with the updated usage values
2270 my $new = qsearchs('svc_acct', { 'svcnum' => $self->svcnum });
2271 local($FS::Record::nowarn_identical) = 1;
2272 my $error = $new->replace($self); #call exports
2274 $dbh->rollback if $oldAutoCommit;
2275 return "Error replacing: $error";
2282 $error = $self->_op_overlimit('unsuspend')
2283 if $self->overlimit;;
2285 $error ||= $self->cust_svc->cust_pkg->unsuspend
2286 if $conf->exists("svc_acct-usage_unsuspend");
2289 $dbh->rollback if $oldAutoCommit;
2290 return "Error unsuspending: $error";
2295 warn "$me update successful; committing\n"
2297 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2303 =item recharge HASHREF
2305 Increments usage columns by the amount specified in HASHREF as
2306 column=>amount pairs.
2311 my ($self, $vhash) = @_;
2314 warn "[$me] recharge called on $self: ". Dumper($self).
2315 "\nwith vhash: ". Dumper($vhash);
2318 my $oldAutoCommit = $FS::UID::AutoCommit;
2319 local $FS::UID::AutoCommit = 0;
2323 foreach my $column (keys %$vhash){
2324 $error ||= $self->_op_usage('+', $column, $vhash->{$column});
2328 $dbh->rollback if $oldAutoCommit;
2330 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2335 =item is_rechargeable
2337 Returns true if this svc_account can be "recharged" and false otherwise.
2341 sub is_rechargable {
2343 $self->seconds ne ''
2344 || $self->upbytes ne ''
2345 || $self->downbytes ne ''
2346 || $self->totalbytes ne '';
2349 =item seconds_since TIMESTAMP
2351 Returns the number of seconds this account has been online since TIMESTAMP,
2352 according to the session monitor (see L<FS::Session>).
2354 TIMESTAMP is specified as a UNIX timestamp; see L<perlfunc/"time">. Also see
2355 L<Time::Local> and L<Date::Parse> for conversion functions.
2359 #note: POD here, implementation in FS::cust_svc
2362 $self->cust_svc->seconds_since(@_);
2365 =item last_login_text
2367 Returns text describing the time of last login.
2371 sub last_login_text {
2373 $self->last_login ? ctime($self->last_login) : 'unknown';
2376 =item psearch_cdrs OPTIONS
2378 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records
2379 associated with this service. For svc_acct, "associated with" means that
2380 either the "src" or the "charged_party" field of the CDR matches the
2381 "username" field of the service.
2386 my($self, %options) = @_;
2391 my $did = dbh->quote($self->username);
2393 my $prefix = $options{'default_prefix'} || ''; #convergent.au '+61'
2394 my $prefixdid = dbh->quote($prefix . $self->username);
2396 my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
2398 if ( $options{inbound} ) {
2399 # these will be selected under their DIDs
2400 push @where, "FALSE";
2404 if (!$options{'disable_charged_party'}) {
2406 "charged_party = $did",
2407 "charged_party = $prefixdid";
2409 if (!$options{'disable_src'}) {
2411 "src = $did AND charged_party IS NULL",
2412 "src = $prefixdid AND charged_party IS NULL";
2414 push @where, '(' . join(' OR ', @orwhere) . ')';
2416 # $options{'status'} = '' is meaningful; for the rest of them it's not
2417 if ( exists $options{'status'} ) {
2418 $hash{'freesidestatus'} = $options{'status'};
2420 if ( $options{'cdrtypenum'} ) {
2421 $hash{'cdrtypenum'} = $options{'cdrtypenum'};
2423 if ( $options{'calltypenum'} ) {
2424 $hash{'calltypenum'} = $options{'calltypenum'};
2426 if ( $options{'begin'} ) {
2427 push @where, 'startdate >= '. $options{'begin'};
2429 if ( $options{'end'} ) {
2430 push @where, 'startdate < '. $options{'end'};
2432 if ( $options{'nonzero'} ) {
2433 push @where, 'duration > 0';
2436 my $extra_sql = join(' AND ', @where);
2439 $extra_sql = " AND ".$extra_sql;
2441 $extra_sql = " WHERE ".$extra_sql;
2447 'hashref' => \%hash,
2448 'extra_sql' => $extra_sql,
2449 'order_by' => "ORDER BY startdate $for_update",
2453 =item get_cdrs (DEPRECATED)
2455 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a
2456 single list. Arguments are the same as for psearch_cdrs.
2462 my $psearch = $self->psearch_cdrs(@_);
2463 qsearch ( $psearch->{query} )
2466 # sub radius_groups has moved to svc_Radius_Mixin
2468 =item clone_suspended
2470 Constructor used by FS::part_export::_export_suspend fallback. Document
2475 sub clone_suspended {
2477 my %hash = $self->hash;
2478 $hash{_password} = join('',map($pw_set[ int(rand $#pw_set) ], (0..7) ) );
2479 new FS::svc_acct \%hash;
2482 =item clone_kludge_unsuspend
2484 Constructor used by FS::part_export::_export_unsuspend fallback. Document
2489 sub clone_kludge_unsuspend {
2491 my %hash = $self->hash;
2492 $hash{_password} = '';
2493 new FS::svc_acct \%hash;
2496 =item check_password
2498 Checks the supplied password against the (possibly encrypted) password in the
2499 database. Returns true for a successful authentication, false for no match.
2501 Currently supported encryptions are: classic DES crypt() and MD5
2505 sub check_password {
2506 my($self, $check_password) = @_;
2508 #remove old-style SUSPENDED kludge, they should be allowed to login to
2509 #self-service and pay up
2510 ( my $password = $self->_password ) =~ s/^\*SUSPENDED\* //;
2512 if ( $self->_password_encoding eq 'ldap' ) {
2514 $password =~ s/^{PLAIN}/{CLEARTEXT}/;
2515 my $auth = from_rfc2307 Authen::Passphrase $password;
2516 return $auth->match($check_password);
2518 } elsif ( $self->_password_encoding eq 'crypt' ) {
2520 my $auth = from_crypt Authen::Passphrase $self->_password;
2521 return $auth->match($check_password);
2523 } elsif ( $self->_password_encoding eq 'plain' ) {
2525 return $check_password eq $password;
2529 #XXX this could be replaced with Authen::Passphrase stuff
2531 if ( $password =~ /^(\*|!!?)$/ ) { #no self-service login
2533 } elsif ( length($password) < 13 ) { #plaintext
2534 $check_password eq $password;
2535 } elsif ( length($password) == 13 ) { #traditional DES crypt
2536 crypt($check_password, $password) eq $password;
2537 } elsif ( $password =~ /^\$1\$/ ) { #MD5 crypt
2538 unix_md5_crypt($check_password, $password) eq $password;
2539 } elsif ( $password =~ /^\$2a?\$/ ) { #Blowfish
2540 warn "Can't check password: Blowfish encryption not yet supported, ".
2541 "svcnum ". $self->svcnum. "\n";
2544 warn "Can't check password: Unrecognized encryption for svcnum ".
2545 $self->svcnum. "\n";
2553 =item crypt_password [ DEFAULT_ENCRYPTION_TYPE ]
2555 Returns an encrypted password, either by passing through an encrypted password
2556 in the database or by encrypting a plaintext password from the database.
2558 The optional DEFAULT_ENCRYPTION_TYPE parameter can be set to I<crypt> (classic
2559 UNIX DES crypt), I<md5> (md5 crypt supported by most modern Linux and BSD
2560 distrubtions), or (eventually) I<blowfish> (blowfish hashing supported by
2561 OpenBSD, SuSE, other Linux distibutions with pam_unix2, etc.). The default
2562 encryption type is only used if the password is not already encrypted in the
2567 sub crypt_password {
2570 if ( $self->_password_encoding eq 'ldap' ) {
2572 if ( $self->_password =~ /^\{(PLAIN|CLEARTEXT)\}(.+)$/ ) {
2575 #XXX this could be replaced with Authen::Passphrase stuff
2577 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2578 if ( $encryption eq 'crypt' ) {
2581 $saltset[int(rand(64))].$saltset[int(rand(64))]
2583 } elsif ( $encryption eq 'md5' ) {
2584 return unix_md5_crypt( $self->_password );
2585 } elsif ( $encryption eq 'blowfish' ) {
2586 croak "unknown encryption method $encryption";
2588 croak "unknown encryption method $encryption";
2591 } elsif ( $self->_password =~ /^\{CRYPT\}(.+)$/ ) {
2595 } elsif ( $self->_password_encoding eq 'crypt' ) {
2597 return $self->_password;
2599 } elsif ( $self->_password_encoding eq 'plain' ) {
2601 #XXX this could be replaced with Authen::Passphrase stuff
2603 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2604 if ( $encryption eq 'crypt' ) {
2607 $saltset[int(rand(64))].$saltset[int(rand(64))]
2609 } elsif ( $encryption eq 'md5' ) {
2610 return unix_md5_crypt( $self->_password );
2611 } elsif ( $encryption eq 'sha1_base64' ) { #for acct_sql
2612 my $pass = sha1_base64( $self->_password );
2613 $pass .= '=' x (4 - length($pass) % 4); #properly padded base64
2615 } elsif ( $encryption eq 'blowfish' ) {
2616 croak "unknown encryption method $encryption";
2618 croak "unknown encryption method $encryption";
2623 if ( length($self->_password) == 13
2624 || $self->_password =~ /^\$(1|2a?)\$/
2625 || $self->_password =~ /^(\*|NP|\*LK\*|!!?)$/
2631 #XXX this could be replaced with Authen::Passphrase stuff
2633 my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2634 if ( $encryption eq 'crypt' ) {
2637 $saltset[int(rand(64))].$saltset[int(rand(64))]
2639 } elsif ( $encryption eq 'md5' ) {
2640 return unix_md5_crypt( $self->_password );
2641 } elsif ( $encryption eq 'blowfish' ) {
2642 croak "unknown encryption method $encryption";
2644 croak "unknown encryption method $encryption";
2653 =item ldap_password [ DEFAULT_ENCRYPTION_TYPE ]
2655 Returns an encrypted password in "LDAP" format, with a curly-bracked prefix
2656 describing the format, for example, "{PLAIN}himom", "{CRYPT}94pAVyK/4oIBk" or
2657 "{MD5}5426824942db4253f87a1009fd5d2d4".
2659 The optional DEFAULT_ENCRYPTION_TYPE is not yet used, but the idea is for it
2660 to work the same as the B</crypt_password> method.
2666 #eventually should check a "password-encoding" field
2668 if ( $self->_password_encoding eq 'ldap' ) {
2670 return $self->_password;
2672 } elsif ( $self->_password_encoding eq 'crypt' ) {
2674 if ( length($self->_password) == 13 ) { #crypt
2675 return '{CRYPT}'. $self->_password;
2676 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2678 #} elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2679 # die "Blowfish encryption not supported in this context, svcnum ".
2680 # $self->svcnum. "\n";
2682 warn "encryption method not (yet?) supported in LDAP context";
2683 return '{CRYPT}*'; #unsupported, should not auth
2686 } elsif ( $self->_password_encoding eq 'plain' ) {
2688 return '{PLAIN}'. $self->_password;
2690 #return '{CLEARTEXT}'. $self->_password; #?
2694 if ( length($self->_password) == 13 ) { #crypt
2695 return '{CRYPT}'. $self->_password;
2696 } elsif ( $self->_password =~ /^\$1\$(.*)$/ && length($1) == 31 ) { #passwdMD5
2698 } elsif ( $self->_password =~ /^\$2a?\$(.*)$/ ) { #Blowfish
2699 warn "Blowfish encryption not supported in this context, svcnum ".
2700 $self->svcnum. "\n";
2703 #are these two necessary anymore?
2704 } elsif ( $self->_password =~ /^(\w{48})$/ ) { #LDAP SSHA
2705 return '{SSHA}'. $1;
2706 } elsif ( $self->_password =~ /^(\w{64})$/ ) { #LDAP NS-MTA-MD5
2707 return '{NS-MTA-MD5}'. $1;
2710 return '{PLAIN}'. $self->_password;
2712 #return '{CLEARTEXT}'. $self->_password; #?
2714 #XXX this could be replaced with Authen::Passphrase stuff if it gets used
2715 #my $encryption = ( scalar(@_) && $_[0] ) ? shift : 'crypt';
2716 #if ( $encryption eq 'crypt' ) {
2717 # return '{CRYPT}'. crypt(
2719 # $saltset[int(rand(64))].$saltset[int(rand(64))]
2721 #} elsif ( $encryption eq 'md5' ) {
2722 # unix_md5_crypt( $self->_password );
2723 #} elsif ( $encryption eq 'blowfish' ) {
2724 # croak "unknown encryption method $encryption";
2726 # croak "unknown encryption method $encryption";
2734 =item domain_slash_username
2736 Returns $domain/$username/
2740 sub domain_slash_username {
2742 $self->domain. '/'. $self->username. '/';
2745 =item virtual_maildir
2747 Returns $domain/maildirs/$username/
2751 sub virtual_maildir {
2753 $self->domain. '/maildirs/'. $self->username. '/';
2758 =head1 CLASS METHODS
2762 =item search HASHREF
2764 Class method which returns a qsearch hash expression to search for parameters
2765 specified in HASHREF. Valid parameters are
2779 Arrayref of pkgparts
2785 Arrayref of additional WHERE clauses, will be ANDed together.
2796 my( $class, $params, $from, $where ) = @_;
2798 #these two should probably move to svc_Domain_Mixin ?
2801 if ( $params->{'domain'} ) {
2802 my $svc_domain = qsearchs('svc_domain', { 'domain'=>$params->{'domain'} } );
2803 #preserve previous behavior & bubble up an error if $svc_domain not found?
2804 push @$where, 'domsvc = '. $svc_domain->svcnum if $svc_domain;
2808 if ( $params->{'domsvc'} =~ /^(\d+)$/ ) {
2809 push @$where, "domsvc = $1";
2814 if ( $params->{'popnum'} =~ /^(\d+)$/ ) {
2815 push @$where, "popnum = $1";
2819 #and these in svc_Tower_Mixin, or maybe we never should have done svc_acct
2820 # towers (or, as mark thought, never should have done svc_broadband)
2823 my @where_sector = $class->tower_sector_sql($params);
2824 if ( @where_sector ) {
2825 push @$where, @where_sector;
2826 push @$from, ' LEFT JOIN tower_sector USING ( sectornum )';
2839 This is the FS::svc_acct job-queue-able version. It still uses
2840 FS::Misc::send_email under-the-hood.
2847 eval "use FS::Misc qw(send_email)";
2850 $opt{mimetype} ||= 'text/plain';
2851 $opt{mimetype} .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2853 my $error = send_email(
2854 'from' => $opt{from},
2856 'subject' => $opt{subject},
2857 'content-type' => $opt{mimetype},
2858 'body' => [ map "$_\n", split("\n", $opt{body}) ],
2860 die $error if $error;
2863 =item check_and_rebuild_fuzzyfiles
2867 sub check_and_rebuild_fuzzyfiles {
2868 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2869 -e "$dir/svc_acct.username"
2870 or &rebuild_fuzzyfiles;
2873 =item rebuild_fuzzyfiles
2877 sub rebuild_fuzzyfiles {
2879 use Fcntl qw(:flock);
2881 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2885 open(USERNAMELOCK,">>$dir/svc_acct.username")
2886 or die "can't open $dir/svc_acct.username: $!";
2887 flock(USERNAMELOCK,LOCK_EX)
2888 or die "can't lock $dir/svc_acct.username: $!";
2890 my @all_username = map $_->getfield('username'), qsearch('svc_acct', {});
2892 open (USERNAMECACHE,">$dir/svc_acct.username.tmp")
2893 or die "can't open $dir/svc_acct.username.tmp: $!";
2894 print USERNAMECACHE join("\n", @all_username), "\n";
2895 close USERNAMECACHE or die "can't close $dir/svc_acct.username.tmp: $!";
2897 rename "$dir/svc_acct.username.tmp", "$dir/svc_acct.username";
2907 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2908 open(USERNAMECACHE,"<$dir/svc_acct.username")
2909 or die "can't open $dir/svc_acct.username: $!";
2910 my @array = map { chomp; $_; } <USERNAMECACHE>;
2911 close USERNAMECACHE;
2915 =item append_fuzzyfiles USERNAME
2919 sub append_fuzzyfiles {
2920 my $username = shift;
2922 &check_and_rebuild_fuzzyfiles;
2924 use Fcntl qw(:flock);
2926 my $dir = $FS::UID::conf_dir. "/cache.". $FS::UID::datasrc;
2928 open(USERNAME,">>$dir/svc_acct.username")
2929 or die "can't open $dir/svc_acct.username: $!";
2930 flock(USERNAME,LOCK_EX)
2931 or die "can't lock $dir/svc_acct.username: $!";
2933 print USERNAME "$username\n";
2935 flock(USERNAME,LOCK_UN)
2936 or die "can't unlock $dir/svc_acct.username: $!";
2943 =item reached_threshold
2945 Performs some activities when svc_acct thresholds (such as number of seconds
2946 remaining) are reached.
2950 sub reached_threshold {
2953 my $svc_acct = qsearchs('svc_acct', { 'svcnum' => $opt{'svcnum'} } );
2954 die "Cannot find svc_acct with svcnum " . $opt{'svcnum'} unless $svc_acct;
2956 if ( $opt{'op'} eq '+' ){
2957 $svc_acct->setfield( $opt{'column'}.'_threshold',
2958 int($svc_acct->getfield($opt{'column'})
2959 * ( $conf->exists('svc_acct-usage_threshold')
2960 ? $conf->config('svc_acct-usage_threshold')/100
2965 my $error = $svc_acct->replace;
2966 die $error if $error;
2967 }elsif ( $opt{'op'} eq '-' ){
2969 my $threshold = $svc_acct->getfield( $opt{'column'}.'_threshold' );
2970 return '' if ($threshold eq '' );
2972 $svc_acct->setfield( $opt{'column'}.'_threshold', 0 );
2973 my $error = $svc_acct->replace;
2974 die $error if $error; # email next time, i guess
2976 if ( $warning_template ) {
2977 eval "use FS::Misc qw(send_email)";
2980 my $cust_pkg = $svc_acct->cust_svc->cust_pkg;
2981 my $cust_main = $cust_pkg->cust_main;
2983 my $to = join(', ', grep { $_ !~ /^(POST|FAX)$/ }
2984 $cust_main->invoicing_list,
2985 ($opt{'to'} ? $opt{'to'} : ())
2988 my $mimetype = $warning_mimetype;
2989 $mimetype .= '; charset="iso-8859-1"' unless $opt{mimetype} =~ /charset/;
2991 my $body = $warning_template->fill_in( HASH => {
2992 'custnum' => $cust_main->custnum,
2993 'username' => $svc_acct->username,
2994 'password' => $svc_acct->_password,
2995 'first' => $cust_main->first,
2996 'last' => $cust_main->getfield('last'),
2997 'pkg' => $cust_pkg->part_pkg->pkg,
2998 'column' => $opt{'column'},
2999 'amount' => $opt{'column'} =~/bytes/
3000 ? FS::UI::bytecount::display_bytecount($svc_acct->getfield($opt{'column'}))
3001 : $svc_acct->getfield($opt{'column'}),
3002 'threshold' => $opt{'column'} =~/bytes/
3003 ? FS::UI::bytecount::display_bytecount($threshold)
3008 my $error = send_email(
3009 'from' => $warning_from,
3011 'subject' => $warning_subject,
3012 'content-type' => $mimetype,
3013 'body' => [ map "$_\n", split("\n", $body) ],
3015 die $error if $error;
3018 die "unknown op: " . $opt{'op'};
3026 The $recref stuff in sub check should be cleaned up.
3028 The suspend, unsuspend and cancel methods update the database, but not the
3029 current object. This is probably a bug as it's unexpected and
3032 insertion of RADIUS group stuff in insert could be done with child_objects now
3033 (would probably clean up export of them too)
3035 _op_usage and set_usage bypass the history... maybe they shouldn't
3039 L<FS::svc_Common>, edit/part_svc.cgi from an installed web interface,
3040 export.html from the base documentation, L<FS::Record>, L<FS::Conf>,
3041 L<FS::cust_svc>, L<FS::part_svc>, L<FS::cust_pkg>, L<FS::queue>,
3042 L<freeside-queued>), L<FS::svc_acct_pop>,
3043 schema.html from the base documentation.