2 use base qw( FS::svc_Domain_Mixin FS::location_Mixin FS::svc_Common );
5 use vars qw( $DEBUG $me @pw_set $conf $phone_name_max
6 $passwordmin $passwordmax
9 use Scalar::Util qw( blessed );
10 use List::Util qw( min );
12 use FS::Record qw( qsearch qsearchs dbh );
13 use FS::PagedSearch qw( psearch );
14 use FS::Msgcat qw(gettext);
18 use FS::cust_location;
21 $me = '[' . __PACKAGE__ . ']';
25 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
27 #ask FS::UID to run this stuff for us later
28 FS::UID->install_callback( sub {
30 $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
31 $passwordmin = $conf->config('sip_passwordmin') || 0;
32 $passwordmax = $conf->config('sip_passwordmax') || 80;
38 FS::svc_phone - Object methods for svc_phone records
44 $record = new FS::svc_phone \%hash;
45 $record = new FS::svc_phone { 'column' => 'value' };
47 $error = $record->insert;
49 $error = $new_record->replace($old_record);
51 $error = $record->delete;
53 $error = $record->check;
55 $error = $record->suspend;
57 $error = $record->unsuspend;
59 $error = $record->cancel;
63 An FS::svc_phone object represents a phone number. FS::svc_phone inherits
64 from FS::Record. The following fields are currently supported:
78 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
90 Optional svcnum from svc_pbx
94 Forwarding destination
98 Email address for virtual fax (fax-to-email) services
102 LNP Status (can be null, native, portedin, portingin, portin-reject,
103 portingout, portout-reject)
109 =item lnp_desired_due_date
113 =item lnp_other_provider
115 If porting the number in or out, name of the losing or winning provider,
118 =item lnp_other_provider_account
120 Account number of other provider. See lnp_other_provider.
122 =item lnp_reject_reason
124 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
125 optional reject reason.
135 Creates a new phone number. To add the number to the database, see L<"insert">.
137 Note that this stores the hash reference, not a distinct copy of the hash it
138 points to. You can ask the object for a copy with the I<hash> method.
142 # the new method can be inherited from FS::Record, if a table method is defined
145 my %dis2 = ( disable_inventory=>1, disable_select=>1 );
147 'name' => 'Phone number',
148 'sorts' => 'phonenum',
149 'display_weight' => 60,
150 'cancel_weight' => 80,
152 'svcnum' => 'Service',
153 'countrycode' => { label => 'Country code',
155 disable_inventory => 1,
158 'phonenum' => 'Phone number',
159 'sim_imsi' => 'IMSI', #http://en.wikipedia.org/wiki/International_mobile_subscriber_identity
160 'pin' => { label => 'Voicemail PIN', #'Personal Identification Number',
162 disable_inventory => 1,
165 'sip_password' => 'SIP password',
166 'phone_name' => 'Name',
167 'pbxsvc' => { label => 'PBX',
168 type => 'select-svc_pbx.html',
169 disable_inventory => 1,
170 disable_select => 1, #UI wonky, pry works otherwise
175 select_table => 'svc_domain',
176 select_key => 'svcnum',
177 select_label => 'domain',
178 disable_inventory => 1,
180 'sms_carrierid' => { label => 'SMS Carrier',
182 select_table => 'cdr_carrier',
183 select_key => 'carrierid',
184 select_label => 'carriername',
185 disable_inventory => 1,
187 'sms_account' => { label => 'SMS Carrier Account', },
188 'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
190 label => 'E911 location',
191 disable_inventory => 1,
194 'forwarddst' => { label => 'Forward Destination',
197 'email' => { label => 'Email',
200 'lnp_status' => { label => 'LNP Status',
201 type => 'select-lnp_status.html',
204 'lnp_reject_reason' => {
205 label => 'LNP Reject Reason',
208 'portable' => { label => 'Portable?', %dis2, },
209 'lrn' => { label => 'LRN',
210 disable_inventory => 1,
212 'lnp_desired_due_date' =>
213 { label => 'LNP Desired Due Date', %dis2 },
215 { label => 'LNP Due Date', %dis2 },
216 'lnp_other_provider' =>
217 { label => 'LNP Other Provider',
218 disable_inventory => 1,
220 'lnp_other_provider_account' =>
221 { label => 'LNP Other Provider Account #',
228 sub table { 'svc_phone'; }
230 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
232 =item search_sql STRING
234 Class method which returns an SQL fragment to search for the given string.
239 my( $class, $string ) = @_;
241 #my $conf = new FS::Conf;
243 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
249 my $ccode = ( $conf->exists('default_phone_countrycode')
250 && $conf->config('default_phone_countrycode')
252 ? $conf->config('default_phone_countrycode')
255 $string =~ s/^$ccode//;
257 $class->search_sql_field('phonenum', $string );
262 Returns the phone number.
268 my $phonenum = $self->phonenum; #XXX format it better
269 my $label = $phonenum;
270 $label .= '@'.$self->domain if $self->domsvc;
271 $label .= ' ('.$self->phone_name.')' if $self->phone_name;
277 Adds this phone number to the database. If there is an error, returns the
278 error, otherwise returns false.
287 warn "[$me] insert called on $self: ". Dumper($self).
288 "\nwith options: ". Dumper(%options);
291 local $SIG{HUP} = 'IGNORE';
292 local $SIG{INT} = 'IGNORE';
293 local $SIG{QUIT} = 'IGNORE';
294 local $SIG{TERM} = 'IGNORE';
295 local $SIG{TSTP} = 'IGNORE';
296 local $SIG{PIPE} = 'IGNORE';
298 my $oldAutoCommit = $FS::UID::AutoCommit;
299 local $FS::UID::AutoCommit = 0;
302 #false laziness w/cust_pkg.pm... move this to location_Mixin? that would
303 #make it more of a base class than a mixin... :)
304 if ( $options{'cust_location'} ) {
305 my $error = $options{'cust_location'}->find_or_insert;
307 $dbh->rollback if $oldAutoCommit;
308 return "inserting cust_location (transaction rolled back): $error";
310 $self->locationnum( $options{'cust_location'}->locationnum );
312 #what about on-the-fly edits? if the ui supports it?
314 my $error = $self->SUPER::insert(%options);
316 $dbh->rollback if $oldAutoCommit;
320 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
327 Delete this record from the database.
334 local $SIG{HUP} = 'IGNORE';
335 local $SIG{INT} = 'IGNORE';
336 local $SIG{QUIT} = 'IGNORE';
337 local $SIG{TERM} = 'IGNORE';
338 local $SIG{TSTP} = 'IGNORE';
339 local $SIG{PIPE} = 'IGNORE';
341 my $oldAutoCommit = $FS::UID::AutoCommit;
342 local $FS::UID::AutoCommit = 0;
345 foreach my $phone_device ( $self->phone_device ) {
346 my $error = $phone_device->delete;
348 $dbh->rollback if $oldAutoCommit;
353 my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
354 foreach my $phone_avail ( @phone_avail ) {
355 $phone_avail->svcnum('');
356 my $error = $phone_avail->replace;
358 $dbh->rollback if $oldAutoCommit;
363 my $error = $self->SUPER::delete;
365 $dbh->rollback if $oldAutoCommit;
369 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
374 =item replace OLD_RECORD
376 Replaces the OLD_RECORD with this one in the database. If there is an error,
377 returns the error, otherwise returns false.
384 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
391 warn "[$me] replacing $old with $new\n".
392 "\nwith options: ". Dumper(%options);
395 local $SIG{HUP} = 'IGNORE';
396 local $SIG{INT} = 'IGNORE';
397 local $SIG{QUIT} = 'IGNORE';
398 local $SIG{TERM} = 'IGNORE';
399 local $SIG{TSTP} = 'IGNORE';
400 local $SIG{PIPE} = 'IGNORE';
402 my $oldAutoCommit = $FS::UID::AutoCommit;
403 local $FS::UID::AutoCommit = 0;
406 #false laziness w/cust_pkg.pm... move this to location_Mixin? that would
407 #make it more of a base class than a mixin... :)
408 if ( $options{'cust_location'}
409 && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
410 my $error = $options{'cust_location'}->insert;
412 $dbh->rollback if $oldAutoCommit;
413 return "inserting cust_location (transaction rolled back): $error";
415 $new->locationnum( $options{'cust_location'}->locationnum );
417 #what about on-the-fly edits? if the ui supports it?
419 # LNP data validation
420 return 'Invalid LNP status' # if someone does really stupid stuff
421 if ( ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portingin')
422 || ($old->lnp_status eq 'portout-reject' && $new->lnp_status eq 'portingin')
423 || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'portingout')
424 || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'native')
425 || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'native')
426 || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'portingout')
427 || ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portin-reject')
430 my $error = $new->SUPER::replace($old, %options);
432 $dbh->rollback if $oldAutoCommit;
433 return $error if $error;
436 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
442 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
446 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
450 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
454 Checks all fields to make sure this is a valid phone number. If there is
455 an error, returns the error, otherwise returns false. Called by the insert
460 # the check method should currently be supplied - FS::Record contains some
461 # data checking routines
466 #my $conf = new FS::Conf;
468 my $x = $self->setfixed;
469 return $x unless ref($x);
472 my $phonenum = $self->phonenum;
473 my $phonenum_check_method;
474 if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
475 $phonenum =~ s/\W//g;
476 $phonenum_check_method = 'ut_alpha';
478 $phonenum =~ s/\D//g;
479 $phonenum_check_method = 'ut_number';
481 $self->phonenum($phonenum);
483 $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
486 $self->ut_numbern('svcnum')
487 || $self->ut_numbern('countrycode')
488 || $self->$phonenum_check_method('phonenum')
489 || $self->ut_numbern('sim_imsi')
490 || $self->ut_anything('sip_password')
491 || $self->ut_numbern('pin')
492 || $self->ut_textn('phone_name')
493 || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx', 'svcnum' )
494 || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
495 || $self->ut_foreign_keyn('sms_carrierid', 'cdr_carrier', 'carrierid' )
496 || $self->ut_alphan('sms_account')
497 || $self->ut_numbern('max_simultaneous')
498 || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
499 || $self->ut_numbern('forwarddst')
500 || $self->ut_textn('email')
501 || $self->ut_numbern('lrn')
502 || $self->ut_numbern('lnp_desired_due_date')
503 || $self->ut_numbern('lnp_due_date')
504 || $self->ut_textn('lnp_other_provider')
505 || $self->ut_textn('lnp_other_provider_account')
506 || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin',
507 'native', 'portin-reject', 'portout-reject'])
508 || $self->ut_enumn('portable', ['','Y'])
509 || $self->ut_textn('lnp_reject_reason')
511 return $error if $error;
513 return 'Illegal IMSI (not 14-15 digits)' #shorter?
514 if length($self->sim_imsi)
515 && ( length($self->sim_imsi) < 14 || length($self->sim_imsi) > 15 );
517 # LNP data validation
518 return 'Cannot set LNP fields: no LNP in progress'
519 if ( ($self->lnp_desired_due_date || $self->lnp_due_date
520 || $self->lnp_other_provider || $self->lnp_other_provider_account
521 || $self->lnp_reject_reason)
522 && (!$self->lnp_status || $self->lnp_status eq 'native') );
523 return 'Cannot set LNP reject reason: no LNP in progress or status is not reject'
524 if ($self->lnp_reject_reason && (!$self->lnp_status
525 || $self->lnp_status !~ /^port(in|out)-reject$/) );
526 return 'Cannot port-out a non-portable number'
527 if (!$self->portable && $self->lnp_status eq 'portingout');
530 return 'Name ('. $self->phone_name.
531 ") is longer than $phone_name_max characters"
532 if $phone_name_max && length($self->phone_name) > $phone_name_max;
534 $self->countrycode(1) unless $self->countrycode;
536 unless ( length($self->pin) ) {
537 my $random_pin = $conf->config('svc_phone-random_pin');
538 if ( defined($random_pin) && $random_pin =~ /^\d+$/ ) {
540 join('', map int(rand(10)), 0..($random_pin-1))
545 if ( length($self->sip_password) ) {
547 return "SIP password must be longer than $passwordmin characters"
548 if length($self->sip_password) < $passwordmin;
549 return "SIP password must be shorter than $passwordmax characters"
550 if length($self->sip_password) > $passwordmax;
552 } elsif ( $part_svc->part_svc_column('sip_password')->columnflag ne 'F' ) {
556 join('', map $pw_set[ int(rand $#pw_set) ], (1..min($passwordmax,16)) )
564 =item _check duplicate
566 Internal method to check for duplicate phone numers.
570 #false laziness w/svc_acct.pm's _check_duplicate.
571 sub _check_duplicate {
574 my $global_unique = $conf->config('global_unique-phonenum') || 'none';
575 return '' if $global_unique eq 'disabled';
580 grep { !$self->svcnum || $_->svcnum != $self->svcnum }
581 qsearch( 'svc_phone', {
582 'countrycode' => $self->countrycode,
583 'phonenum' => $self->phonenum,
586 return gettext('phonenum_in_use')
587 if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
589 my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
590 unless ( $part_svc ) {
591 return 'unknown svcpart '. $self->svcpart;
594 if ( @dup_ccphonenum ) {
596 my $exports = FS::part_export::export_info('svc_phone');
597 my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
599 foreach my $part_export ( $part_svc->part_export ) {
601 #this will catch to the same exact export
602 my @svcparts = map { $_->svcpart } $part_export->export_svc;
604 $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
609 foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
610 my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
611 if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
612 return "duplicate phone number ".
613 $self->countrycode. ' '. $self->phonenum.
614 ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
615 " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
627 Checks the supplied PIN against the PIN in the database. Returns true for a
628 sucessful authentication, false if no match.
633 my($self, $check_pin) = @_;
634 length($self->pin) && $check_pin eq $self->pin;
643 #XXX Session-Timeout! holy shit, need rlm_perl to ask for this in realtime
655 #my $conf = new FS::Conf;
658 if ( $conf->config('svc_phone-radius-password') eq 'countrycode_phonenum' ) {
659 $password = $self->countrycode. $self->phonenum;
661 $password = $conf->config('svc_phone-radius-default_password');
663 $check{'User-Password'} = $password;
672 =item sms_cdr_carrier
676 sub sms_cdr_carrier {
678 return '' unless $self->sms_carrierid;
679 qsearchs('cdr_carrier', { 'carrierid' => $self->sms_carrierid } );
682 =item sms_carriername
686 sub sms_carriername {
688 my $cdr_carrier = $self->sms_cdr_carrier or return '';
689 $cdr_carrier->carriername;
694 Returns any FS::phone_device records associated with this service.
698 #override location_Mixin version cause we want to try the cust_pkg location
699 #in between us and cust_main
700 # XXX what to do in the unlinked case??? return a pseudo-object that returns
702 sub cust_location_or_main {
704 return $self->cust_location if $self->locationnum;
705 my $cust_pkg = $self->cust_svc->cust_pkg;
706 $cust_pkg ? $cust_pkg->cust_location_or_main : '';
709 =item psearch_cdrs OPTIONS
711 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records
712 associated with this service. By default, "associated with" means that
713 either the "src" or the "charged_party" field of the CDR matches the
714 "phonenum" field of the service. To access the CDRs themselves, call
715 "->fetch" on the resulting object.
719 Accepts the following options:
721 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
723 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
725 =item inbound => 1: Return CDRs for inbound calls. With "status", will filter
726 on inbound processing status.
728 =item default_prefix => "XXX": Also accept the phone number of the service prepended
729 with the chosen prefix.
731 =item begin, end: Start and end of a date range, as unix timestamp.
733 =item cdrtypenum: Only return CDRs with this type.
735 =item calltypenum: Only return CDRs with this call type.
737 =item disable_src => 1: Only match on "charged_party", not "src".
739 =item nonzero: Only return CDRs where duration > 0.
741 =item by_svcnum: not supported for svc_phone
743 =item billsec_sum: Instead of returning all of the CDRs, return a single
744 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over
745 the entire result set.
753 my($self, %options) = @_;
758 if ( $options{'inbound'} ) {
761 if ( exists($options{'status'}) ) {
762 my $status = $options{'status'};
764 push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
765 'WHERE cdr.acctid = cdr_termination.acctid '.
766 "AND cdr_termination.status = '$status' ". #quoting kludge
767 'AND cdr_termination.termpart = 1 )';
769 push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
770 'WHERE cdr.acctid = cdr_termination.acctid '.
771 'AND cdr_termination.termpart = 1 )';
777 @fields = ( 'charged_party' );
778 push @fields, 'src' if !$options{'disable_src'};
779 $hash{'freesidestatus'} = $options{'status'}
780 if exists($options{'status'});
783 if ($options{'cdrtypenum'}) {
784 $hash{'cdrtypenum'} = $options{'cdrtypenum'};
786 if ($options{'calltypenum'}) {
787 $hash{'calltypenum'} = $options{'calltypenum'};
790 my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
792 my $number = $self->phonenum;
794 my $prefix = $options{'default_prefix'};
796 my @orwhere = map " $_ = '$number' ", @fields;
797 push @orwhere, map " $_ = '$prefix$number' ", @fields
798 if defined($prefix) && length($prefix);
799 if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
800 push @orwhere, map " $_ = '$1$number' ", @fields
803 push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
805 if ( $options{'begin'} ) {
806 push @where, 'startdate >= '. $options{'begin'};
808 if ( $options{'end'} ) {
809 push @where, 'startdate < '. $options{'end'};
811 if ( $options{'nonzero'} ) {
812 push @where, 'duration > 0';
815 my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
820 'extra_sql' => $extra_sql,
821 'order_by' => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
822 'select' => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
826 =item get_cdrs (DEPRECATED)
828 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a
829 single list. Arguments are the same as for psearch_cdrs. This can take
830 an unreasonably large amount of memory and is best avoided.
836 my $psearch = $self->psearch_cdrs(@_);
837 qsearch ( $psearch->{query} )
842 Takes the same options as psearch_cdrs, but returns a single row containing
843 "count" (the number of CDRs) and the sums of the following fields: duration,
844 billsec, rated_price, rated_seconds, rated_minutes.
846 Note that if any calls are not rated, their rated_* fields will be null.
847 If you want to use those fields, pass the 'status' option to limit to
848 calls that have been rated. This is intentional; please don't "fix" it.
854 my $psearch = $self->psearch_cdrs(@_);
855 $psearch->{query}->{'select'} = join(',',
857 map { "SUM($_) AS $_" }
858 qw(duration billsec rated_price rated_seconds rated_minutes)
861 $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
862 qsearchs ( $psearch->{query} );
871 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
872 L<FS::cust_pkg>, schema.html from the base documentation.