add sip_passwordmin/max, RT#25239
[freeside.git] / FS / FS / svc_phone.pm
1 package FS::svc_phone;
2
3 use strict;
4 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
7            );
8 use Data::Dumper;
9 use Scalar::Util qw( blessed );
10 use List::Util qw( min );
11 use FS::Conf;
12 use FS::Record qw( qsearch qsearchs dbh );
13 use FS::PagedSearch qw( psearch );
14 use FS::Msgcat qw(gettext);
15 use FS::part_svc;
16 use FS::phone_device;
17 use FS::svc_pbx;
18 use FS::svc_domain;
19 use FS::cust_location;
20 use FS::phone_avail;
21
22 $me = '[' . __PACKAGE__ . ']';
23 $DEBUG = 0;
24
25 #avoid l 1 and o O 0
26 @pw_set = ( 'a'..'k', 'm','n', 'p-z', 'A'..'N', 'P'..'Z' , '2'..'9' );
27
28 #ask FS::UID to run this stuff for us later
29 FS::UID->install_callback( sub { 
30   $conf = new FS::Conf;
31   $phone_name_max = $conf->config('svc_phone-phone_name-max_length');
32   $passwordmin = $conf->config('sip_passwordmin') || 0;
33   $passwordmax = $conf->config('sip_passwordmax') || 80;
34 }
35 );
36
37 =head1 NAME
38
39 FS::svc_phone - Object methods for svc_phone records
40
41 =head1 SYNOPSIS
42
43   use FS::svc_phone;
44
45   $record = new FS::svc_phone \%hash;
46   $record = new FS::svc_phone { 'column' => 'value' };
47
48   $error = $record->insert;
49
50   $error = $new_record->replace($old_record);
51
52   $error = $record->delete;
53
54   $error = $record->check;
55
56   $error = $record->suspend;
57
58   $error = $record->unsuspend;
59
60   $error = $record->cancel;
61
62 =head1 DESCRIPTION
63
64 An FS::svc_phone object represents a phone number.  FS::svc_phone inherits
65 from FS::Record.  The following fields are currently supported:
66
67 =over 4
68
69 =item svcnum
70
71 primary key
72
73 =item countrycode
74
75 =item phonenum
76
77 =item sim_imsi
78
79 SIM IMSI (http://en.wikipedia.org/wiki/International_mobile_subscriber_identity)
80
81 =item sip_password
82
83 =item pin
84
85 Voicemail PIN
86
87 =item phone_name
88
89 =item pbxsvc
90
91 Optional svcnum from svc_pbx
92
93 =item forwarddst
94
95 Forwarding destination
96
97 =item email
98
99 Email address for virtual fax (fax-to-email) services
100
101 =item lnp_status
102
103 LNP Status (can be null, native, portedin, portingin, portin-reject,
104 portingout, portout-reject)
105
106 =item portable
107
108 =item lrn
109
110 =item lnp_desired_due_date
111
112 =item lnp_due_date
113
114 =item lnp_other_provider
115
116 If porting the number in or out, name of the losing or winning provider, 
117 respectively.
118
119 =item lnp_other_provider_account
120
121 Account number of other provider. See lnp_other_provider.
122
123 =item lnp_reject_reason
124
125 See lnp_status. If lnp_status is portin-reject or portout-reject, this is an
126 optional reject reason.
127
128 =back
129
130 =head1 METHODS
131
132 =over 4
133
134 =item new HASHREF
135
136 Creates a new phone number.  To add the number to the database, see L<"insert">.
137
138 Note that this stores the hash reference, not a distinct copy of the hash it
139 points to.  You can ask the object for a copy with the I<hash> method.
140
141 =cut
142
143 # the new method can be inherited from FS::Record, if a table method is defined
144 #
145 sub table_info {
146  my %dis2 = ( disable_inventory=>1, disable_select=>1 );
147   {
148     'name' => 'Phone number',
149     'sorts' => 'phonenum',
150     'display_weight' => 60,
151     'cancel_weight'  => 80,
152     'fields' => {
153         'svcnum'       => 'Service',
154         'countrycode'  => { label => 'Country code',
155                             type  => 'text',
156                             disable_inventory => 1,
157                             disable_select => 1,
158                           },
159         'phonenum'     => 'Phone number',
160         'sim_imsi'     => 'IMSI', #http://en.wikipedia.org/wiki/International_mobile_subscriber_identity
161         'pin'          => { label => 'Voicemail PIN', #'Personal Identification Number',
162                             type  => 'text',
163                             disable_inventory => 1,
164                             disable_select => 1,
165                           },
166         'sip_password' => 'SIP password',
167         'phone_name'   => 'Name',
168         'pbxsvc'       => { label => 'PBX',
169                             type  => 'select-svc_pbx.html',
170                             disable_inventory => 1,
171                             disable_select => 1, #UI wonky, pry works otherwise
172                           },
173         'domsvc'    => {
174                          label     => 'Domain',
175                          type      => 'select',
176                          select_table => 'svc_domain',
177                          select_key   => 'svcnum',
178                          select_label => 'domain',
179                          disable_inventory => 1,
180                        },
181         'sms_carrierid'    => { label             => 'SMS Carrier',
182                                 type              => 'select',
183                                 select_table      => 'cdr_carrier',
184                                 select_key        => 'carrierid',
185                                 select_label      => 'carriername',
186                                 disable_inventory => 1,
187                               },
188         'sms_account'      => { label => 'SMS Carrier Account', },
189         'max_simultaneous' => { label=>'Maximum number of simultaneous users' },
190         'locationnum' => {
191                            label => 'E911 location',
192                            disable_inventory => 1,
193                            disable_select    => 1,
194                          },
195         'forwarddst' => {       label => 'Forward Destination', 
196                                 %dis2,
197                         },
198         'email' => {            label => 'Email',
199                                 %dis2,
200                     },
201         'lnp_status' => {       label => 'LNP Status',
202                                 type => 'select-lnp_status.html',
203                                 %dis2,
204                         },
205         'lnp_reject_reason' => { 
206                                 label => 'LNP Reject Reason',
207                                 %dis2,
208                         },
209         'portable' =>   {       label => 'Portable?', %dis2, },
210         'lrn'   =>      {       label => 'LRN', 
211                                 disable_inventory => 1, 
212                         },
213         'lnp_desired_due_date' =>
214                         { label => 'LNP Desired Due Date', %dis2 },
215         'lnp_due_date' =>
216                         { label => 'LNP Due Date', %dis2 },
217         'lnp_other_provider' =>
218                         {       label => 'LNP Other Provider', 
219                                 disable_inventory => 1, 
220                         },
221         'lnp_other_provider_account' =>
222                         {       label => 'LNP Other Provider Account #', 
223                                 %dis2 
224                         },
225     },
226   };
227 }
228
229 sub table { 'svc_phone'; }
230
231 sub table_dupcheck_fields { ( 'countrycode', 'phonenum' ); }
232
233 =item search_sql STRING
234
235 Class method which returns an SQL fragment to search for the given string.
236
237 =cut
238
239 sub search_sql {
240   my( $class, $string ) = @_;
241
242   my $conf = new FS::Conf;
243
244   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
245     $string =~ s/\W//g;
246   } else {
247     $string =~ s/\D//g;
248   }
249
250   my $ccode = (    $conf->exists('default_phone_countrycode')
251                 && $conf->config('default_phone_countrycode')
252               )
253                 ? $conf->config('default_phone_countrycode') 
254                 : '1';
255
256   $string =~ s/^$ccode//;
257
258   $class->search_sql_field('phonenum', $string );
259 }
260
261 =item label
262
263 Returns the phone number.
264
265 =cut
266
267 sub label {
268   my $self = shift;
269   my $phonenum = $self->phonenum; #XXX format it better
270   my $label = $phonenum;
271   $label .= '@'.$self->domain if $self->domsvc;
272   $label .= ' ('.$self->phone_name.')' if $self->phone_name;
273   $label;
274 }
275
276 =item insert
277
278 Adds this phone number to the database.  If there is an error, returns the
279 error, otherwise returns false.
280
281 =cut
282
283 sub insert {
284   my $self = shift;
285   my %options = @_;
286
287   if ( $DEBUG ) {
288     warn "[$me] insert called on $self: ". Dumper($self).
289          "\nwith options: ". Dumper(%options);
290   }
291
292   local $SIG{HUP} = 'IGNORE';
293   local $SIG{INT} = 'IGNORE';
294   local $SIG{QUIT} = 'IGNORE';
295   local $SIG{TERM} = 'IGNORE';
296   local $SIG{TSTP} = 'IGNORE';
297   local $SIG{PIPE} = 'IGNORE';
298
299   my $oldAutoCommit = $FS::UID::AutoCommit;
300   local $FS::UID::AutoCommit = 0;
301   my $dbh = dbh;
302
303   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
304   #make it more of a base class than a mixin... :)
305   if ( $options{'cust_location'} ) {
306     my $error = $options{'cust_location'}->find_or_insert;
307     if ( $error ) {
308       $dbh->rollback if $oldAutoCommit;
309       return "inserting cust_location (transaction rolled back): $error";
310     }
311     $self->locationnum( $options{'cust_location'}->locationnum );
312   }
313   #what about on-the-fly edits?  if the ui supports it?
314
315   my $error = $self->SUPER::insert(%options);
316   if ( $error ) {
317     $dbh->rollback if $oldAutoCommit;
318     return $error;
319   }
320
321   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
322   '';
323
324 }
325
326 =item delete
327
328 Delete this record from the database.
329
330 =cut
331
332 sub delete {
333   my $self = shift;
334
335   local $SIG{HUP} = 'IGNORE';
336   local $SIG{INT} = 'IGNORE';
337   local $SIG{QUIT} = 'IGNORE';
338   local $SIG{TERM} = 'IGNORE';
339   local $SIG{TSTP} = 'IGNORE';
340   local $SIG{PIPE} = 'IGNORE';
341
342   my $oldAutoCommit = $FS::UID::AutoCommit;
343   local $FS::UID::AutoCommit = 0;
344   my $dbh = dbh;
345
346   foreach my $phone_device ( $self->phone_device ) {
347     my $error = $phone_device->delete;
348     if ( $error ) {
349       $dbh->rollback if $oldAutoCommit;
350       return $error;
351     }
352   }
353
354   my @phone_avail = qsearch('phone_avail', { 'svcnum' => $self->svcnum } );
355   foreach my $phone_avail ( @phone_avail ) {
356     $phone_avail->svcnum('');
357     my $error = $phone_avail->replace;
358     if ( $error ) {
359       $dbh->rollback if $oldAutoCommit;
360       return $error;
361     }
362   }
363
364   my $error = $self->SUPER::delete;
365   if ( $error ) {
366     $dbh->rollback if $oldAutoCommit;
367     return $error;
368   }
369
370   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
371   '';
372
373 }
374
375 # the delete method can be inherited from FS::Record
376
377 =item replace OLD_RECORD
378
379 Replaces the OLD_RECORD with this one in the database.  If there is an error,
380 returns the error, otherwise returns false.
381
382 =cut
383
384 sub replace {
385   my $new = shift;
386
387   my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
388               ? shift
389               : $new->replace_old;
390
391   my %options = @_;
392
393   if ( $DEBUG ) {
394     warn "[$me] replacing $old with $new\n".
395          "\nwith options: ". Dumper(%options);
396   }
397
398   local $SIG{HUP} = 'IGNORE';
399   local $SIG{INT} = 'IGNORE';
400   local $SIG{QUIT} = 'IGNORE';
401   local $SIG{TERM} = 'IGNORE';
402   local $SIG{TSTP} = 'IGNORE';
403   local $SIG{PIPE} = 'IGNORE';
404
405   my $oldAutoCommit = $FS::UID::AutoCommit;
406   local $FS::UID::AutoCommit = 0;
407   my $dbh = dbh;
408
409   #false laziness w/cust_pkg.pm... move this to location_Mixin?  that would
410   #make it more of a base class than a mixin... :)
411   if ( $options{'cust_location'}
412          && ( ! $new->locationnum || $new->locationnum == -1 ) ) {
413     my $error = $options{'cust_location'}->insert;
414     if ( $error ) {
415       $dbh->rollback if $oldAutoCommit;
416       return "inserting cust_location (transaction rolled back): $error";
417     }
418     $new->locationnum( $options{'cust_location'}->locationnum );
419   }
420   #what about on-the-fly edits?  if the ui supports it?
421
422   # LNP data validation
423  return 'Invalid LNP status' # if someone does really stupid stuff
424     if (  ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portingin')
425         || ($old->lnp_status eq 'portout-reject' && $new->lnp_status eq 'portingin')
426         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'portingout')
427         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'native')
428         || ($old->lnp_status eq 'portin-reject' && $new->lnp_status eq 'native')
429         || ($old->lnp_status eq 'portingin' && $new->lnp_status eq 'portingout')
430         || ($old->lnp_status eq 'portingout' && $new->lnp_status eq 'portin-reject')
431         );
432
433   my $error = $new->SUPER::replace($old, %options);
434   if ( $error ) {
435     $dbh->rollback if $oldAutoCommit;
436     return $error if $error;
437   }
438
439   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
440   ''; #no error
441 }
442
443 =item suspend
444
445 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
446
447 =item unsuspend
448
449 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
450
451 =item cancel
452
453 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
454
455 =item check
456
457 Checks all fields to make sure this is a valid phone number.  If there is
458 an error, returns the error, otherwise returns false.  Called by the insert
459 and replace methods.
460
461 =cut
462
463 # the check method should currently be supplied - FS::Record contains some
464 # data checking routines
465
466 sub check {
467   my $self = shift;
468
469   my $conf = new FS::Conf;
470
471   my $phonenum = $self->phonenum;
472   my $phonenum_check_method;
473   if ( $conf->exists('svc_phone-allow_alpha_phonenum') ) {
474     $phonenum =~ s/\W//g;
475     $phonenum_check_method = 'ut_alpha';
476   } else {
477     $phonenum =~ s/\D//g;
478     $phonenum_check_method = 'ut_number';
479   }
480   $self->phonenum($phonenum);
481
482   $self->locationnum('') if !$self->locationnum || $self->locationnum == -1;
483
484   my $error = 
485     $self->ut_numbern('svcnum')
486     || $self->ut_numbern('countrycode')
487     || $self->$phonenum_check_method('phonenum')
488     || $self->ut_numbern('sim_imsi')
489     || $self->ut_anything('sip_password')
490     || $self->ut_numbern('pin')
491     || $self->ut_textn('phone_name')
492     || $self->ut_foreign_keyn('pbxsvc', 'svc_pbx',    'svcnum' )
493     || $self->ut_foreign_keyn('domsvc', 'svc_domain', 'svcnum' )
494     || $self->ut_foreign_keyn('sms_carrierid', 'cdr_carrier', 'carrierid' )
495     || $self->ut_alphan('sms_account')
496     || $self->ut_numbern('max_simultaneous')
497     || $self->ut_foreign_keyn('locationnum', 'cust_location', 'locationnum')
498     || $self->ut_numbern('forwarddst')
499     || $self->ut_textn('email')
500     || $self->ut_numbern('lrn')
501     || $self->ut_numbern('lnp_desired_due_date')
502     || $self->ut_numbern('lnp_due_date')
503     || $self->ut_textn('lnp_other_provider')
504     || $self->ut_textn('lnp_other_provider_account')
505     || $self->ut_enumn('lnp_status', ['','portingin','portingout','portedin',
506                                 'native', 'portin-reject', 'portout-reject'])
507     || $self->ut_enumn('portable', ['','Y'])
508     || $self->ut_textn('lnp_reject_reason')
509   ;
510   return $error if $error;
511
512   return 'Illegal IMSI (not 14-15 digits)' #shorter?
513     if length($self->sim_imsi)
514     && ( length($self->sim_imsi) < 14 || length($self->sim_imsi) > 15 );
515
516     # LNP data validation
517     return 'Cannot set LNP fields: no LNP in progress'
518         if ( ($self->lnp_desired_due_date || $self->lnp_due_date 
519             || $self->lnp_other_provider || $self->lnp_other_provider_account
520             || $self->lnp_reject_reason) 
521             && (!$self->lnp_status || $self->lnp_status eq 'native') );
522     return 'Cannot set LNP reject reason: no LNP in progress or status is not reject'
523         if ($self->lnp_reject_reason && (!$self->lnp_status 
524                             || $self->lnp_status !~ /^port(in|out)-reject$/) );
525     return 'Cannot port-out a non-portable number' 
526         if (!$self->portable && $self->lnp_status eq 'portingout');
527
528
529   return 'Name ('. $self->phone_name.
530          ") is longer than $phone_name_max characters"
531     if $phone_name_max && length($self->phone_name) > $phone_name_max;
532
533   $self->countrycode(1) unless $self->countrycode;
534
535   unless ( length($self->pin) ) {
536     my $random_pin = $conf->config('svc_phone-random_pin');
537     if ( defined($random_pin) && $random_pin =~ /^\d+$/ ) {
538       $self->pin(
539         join('', map int(rand(10)), 0..($random_pin-1))
540       );
541     }
542   }
543
544   if ( length($self->sip_password) ) {
545
546     return "SIP password must be longer than $passwordmin characters"
547       if length($self->sip_password) < $passwordmin;
548     return "SIP password must be shorter than $passwordmax characters"
549       if length($self->sip_password) > $passwordmax;
550
551   } else { # option for this?
552
553     $self->sip_password(
554       join('', map $pw_set[ int(rand $#pw_set) ], (1..min($passwordmax,16)) )
555     );
556
557   }
558
559   $self->SUPER::check;
560 }
561
562 =item _check duplicate
563
564 Internal method to check for duplicate phone numers.
565
566 =cut
567
568 #false laziness w/svc_acct.pm's _check_duplicate.
569 sub _check_duplicate {
570   my $self = shift;
571
572   my $global_unique = $conf->config('global_unique-phonenum') || 'none';
573   return '' if $global_unique eq 'disabled';
574
575   $self->lock_table;
576
577   my @dup_ccphonenum =
578     grep { !$self->svcnum || $_->svcnum != $self->svcnum }
579     qsearch( 'svc_phone', {
580       'countrycode' => $self->countrycode,
581       'phonenum'    => $self->phonenum,
582     });
583
584   return gettext('phonenum_in_use')
585     if $global_unique eq 'countrycode+phonenum' && @dup_ccphonenum;
586
587   my $part_svc = qsearchs('part_svc', { 'svcpart' => $self->svcpart } );
588   unless ( $part_svc ) {
589     return 'unknown svcpart '. $self->svcpart;
590   }
591
592   if ( @dup_ccphonenum ) {
593
594     my $exports = FS::part_export::export_info('svc_phone');
595     my %conflict_ccphonenum_svcpart = ( $self->svcpart => 'SELF', );
596
597     foreach my $part_export ( $part_svc->part_export ) {
598
599       #this will catch to the same exact export
600       my @svcparts = map { $_->svcpart } $part_export->export_svc;
601
602       $conflict_ccphonenum_svcpart{$_} = $part_export->exportnum
603         foreach @svcparts;
604
605     }
606
607     foreach my $dup_ccphonenum ( @dup_ccphonenum ) {
608       my $dup_svcpart = $dup_ccphonenum->cust_svc->svcpart;
609       if ( exists($conflict_ccphonenum_svcpart{$dup_svcpart}) ) {
610         return "duplicate phone number ".
611                $self->countrycode. ' '. $self->phonenum.
612                ": conflicts with svcnum ". $dup_ccphonenum->svcnum.
613                " via exportnum ". $conflict_ccphonenum_svcpart{$dup_svcpart};
614       }
615     }
616
617   }
618
619   return '';
620
621 }
622
623 =item check_pin
624
625 Checks the supplied PIN against the PIN in the database.  Returns true for a
626 sucessful authentication, false if no match.
627
628 =cut
629
630 sub check_pin {
631   my($self, $check_pin) = @_;
632   length($self->pin) && $check_pin eq $self->pin;
633 }
634
635 =item radius_reply
636
637 =cut
638
639 sub radius_reply {
640   my $self = shift;
641   #XXX Session-Timeout!  holy shit, need rlm_perl to ask for this in realtime
642   ();
643 }
644
645 =item radius_check
646
647 =cut
648
649 sub radius_check {
650   my $self = shift;
651   my %check = ();
652
653   my $conf = new FS::Conf;
654
655   $check{'User-Password'} = $conf->config('svc_phone-radius-default_password');
656
657   %check;
658 }
659
660 sub radius_groups {
661   ();
662 }
663
664 =item sms_cdr_carrier
665
666 =cut
667
668 sub sms_cdr_carrier {
669   my $self = shift;
670   return '' unless $self->sms_carrierid;
671   qsearchs('cdr_carrier',  { 'carrierid' => $self->sms_carrierid } );
672 }
673
674 =item sms_carriername
675
676 =cut
677
678 sub sms_carriername {
679   my $self = shift;
680   my $cdr_carrier = $self->sms_cdr_carrier or return '';
681   $cdr_carrier->carriername;
682 }
683
684 =item phone_device
685
686 Returns any FS::phone_device records associated with this service.
687
688 =cut
689
690 sub phone_device {
691   my $self = shift;
692   qsearch('phone_device', { 'svcnum' => $self->svcnum } );
693 }
694
695 #override location_Mixin version cause we want to try the cust_pkg location
696 #in between us and cust_main
697 # XXX what to do in the unlinked case???  return a pseudo-object that returns
698 # empty fields?
699 sub cust_location_or_main {
700   my $self = shift;
701   return $self->cust_location if $self->locationnum;
702   my $cust_pkg = $self->cust_svc->cust_pkg;
703   $cust_pkg ? $cust_pkg->cust_location_or_main : '';
704 }
705
706 =item psearch_cdrs OPTIONS
707
708 Returns a paged search (L<FS::PagedSearch>) for Call Detail Records 
709 associated with this service.  By default, "associated with" means that 
710 either the "src" or the "charged_party" field of the CDR matches the 
711 "phonenum" field of the service.  To access the CDRs themselves, call
712 "->fetch" on the resulting object.
713
714 =over 2
715
716 Accepts the following options:
717
718 =item for_update => 1: SELECT the CDRs "FOR UPDATE".
719
720 =item status => "" (or "processing-tiered", "done"): Return only CDRs with that processing status.
721
722 =item inbound => 1: Return CDRs for inbound calls.  With "status", will filter 
723 on inbound processing status.
724
725 =item default_prefix => "XXX": Also accept the phone number of the service prepended 
726 with the chosen prefix.
727
728 =item begin, end: Start and end of a date range, as unix timestamp.
729
730 =item cdrtypenum: Only return CDRs with this type.
731
732 =item calltypenum: Only return CDRs with this call type.
733
734 =item disable_src => 1: Only match on "charged_party", not "src".
735
736 =item nonzero: Only return CDRs where duration > 0.
737
738 =item by_svcnum: not supported for svc_phone
739
740 =item billsec_sum: Instead of returning all of the CDRs, return a single
741 record (as an L<FS::cdr> object) with the sum of the 'billsec' field over 
742 the entire result set.
743
744 =back
745
746 =cut
747
748 sub psearch_cdrs {
749
750   my($self, %options) = @_;
751   my @fields;
752   my %hash;
753   my @where;
754
755   if ( $options{'inbound'} ) {
756
757     @fields = ( 'dst' );
758     if ( exists($options{'status'}) ) {
759       my $status = $options{'status'};
760       if ( $status ) {
761         push @where, 'EXISTS ( SELECT 1 FROM cdr_termination '.
762           'WHERE cdr.acctid = cdr_termination.acctid '.
763           "AND cdr_termination.status = '$status' ". #quoting kludge
764           'AND cdr_termination.termpart = 1 )';
765       } else {
766         push @where, 'NOT EXISTS ( SELECT 1 FROM cdr_termination '.
767           'WHERE cdr.acctid = cdr_termination.acctid '.
768           'AND cdr_termination.termpart = 1 )';
769       }
770     }
771
772   } else {
773
774     @fields = ( 'charged_party' );
775     push @fields, 'src' if !$options{'disable_src'};
776     $hash{'freesidestatus'} = $options{'status'}
777       if exists($options{'status'});
778   }
779
780   if ($options{'cdrtypenum'}) {
781     $hash{'cdrtypenum'} = $options{'cdrtypenum'};
782   }
783   if ($options{'calltypenum'}) {
784     $hash{'calltypenum'} = $options{'calltypenum'};
785   }
786   
787   my $for_update = $options{'for_update'} ? 'FOR UPDATE' : '';
788
789   my $number = $self->phonenum;
790
791   my $prefix = $options{'default_prefix'};
792
793   my @orwhere =  map " $_ = '$number'        ", @fields;
794   push @orwhere, map " $_ = '$prefix$number' ", @fields
795     if defined($prefix) && length($prefix);
796   if ( $prefix && $prefix =~ /^\+(\d+)$/ ) {
797     push @orwhere, map " $_ = '$1$number' ", @fields
798   }
799
800   push @where, ' ( '. join(' OR ', @orwhere ). ' ) ';
801
802   if ( $options{'begin'} ) {
803     push @where, 'startdate >= '. $options{'begin'};
804   }
805   if ( $options{'end'} ) {
806     push @where, 'startdate < '.  $options{'end'};
807   }
808   if ( $options{'nonzero'} ) {
809     push @where, 'duration > 0';
810   }
811
812   my $extra_sql = ( keys(%hash) ? ' AND ' : ' WHERE ' ). join(' AND ', @where );
813
814   psearch( {
815       'table'      => 'cdr',
816       'hashref'    => \%hash,
817       'extra_sql'  => $extra_sql,
818       'order_by'   => $options{'billsec_sum'} ? '' : "ORDER BY startdate $for_update",
819       'select'     => $options{'billsec_sum'} ? 'sum(billsec) as billsec_sum' : '*',
820   } );
821 }
822
823 =item get_cdrs (DEPRECATED)
824
825 Like psearch_cdrs, but returns all the L<FS::cdr> objects at once, in a 
826 single list.  Arguments are the same as for psearch_cdrs.  This can take 
827 an unreasonably large amount of memory and is best avoided.
828
829 =cut
830
831 sub get_cdrs {
832   my $self = shift;
833   my $psearch = $self->psearch_cdrs(@_);
834   qsearch ( $psearch->{query} )
835 }
836
837 =item sum_cdrs
838
839 Takes the same options as psearch_cdrs, but returns a single row containing
840 "count" (the number of CDRs) and the sums of the following fields: duration,
841 billsec, rated_price, rated_seconds, rated_minutes.
842
843 Note that if any calls are not rated, their rated_* fields will be null.
844 If you want to use those fields, pass the 'status' option to limit to 
845 calls that have been rated.  This is intentional; please don't "fix" it.
846
847 =cut
848
849 sub sum_cdrs {
850   my $self = shift;
851   my $psearch = $self->psearch_cdrs(@_);
852   $psearch->{query}->{'select'} = join(',',
853     'COUNT(*) AS count',
854     map { "SUM($_) AS $_" }
855       qw(duration billsec rated_price rated_seconds rated_minutes)
856   );
857   # hack
858   $psearch->{query}->{'extra_sql'} =~ s/ ORDER BY.*$//;
859   qsearchs ( $psearch->{query} );
860 }
861
862 =back
863
864 =head1 BUGS
865
866 =head1 SEE ALSO
867
868 L<FS::svc_Common>, L<FS::Record>, L<FS::cust_svc>, L<FS::part_svc>,
869 L<FS::cust_pkg>, schema.html from the base documentation.
870
871 =cut
872
873 1;
874