Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / FS / FS / access_user.pm
1 package FS::access_user;
2 use base qw( FS::m2m_Common FS::option_Common ); 
3
4 use strict;
5 use vars qw( $DEBUG $me );
6 use FS::UID;
7 use FS::Auth;
8 use FS::Conf;
9 use FS::Record qw( qsearch qsearchs dbh );
10 use FS::agent;
11 use FS::cust_main;
12 use FS::sales;
13
14 $DEBUG = 0;
15 $me = '[FS::access_user]';
16
17 =head1 NAME
18
19 FS::access_user - Object methods for access_user records
20
21 =head1 SYNOPSIS
22
23   use FS::access_user;
24
25   $record = new FS::access_user \%hash;
26   $record = new FS::access_user { 'column' => 'value' };
27
28   $error = $record->insert;
29
30   $error = $new_record->replace($old_record);
31
32   $error = $record->delete;
33
34   $error = $record->check;
35
36 =head1 DESCRIPTION
37
38 An FS::access_user object represents an internal access user.  FS::access_user
39 inherits from FS::Record.  The following fields are currently supported:
40
41 =over 4
42
43 =item usernum - primary key
44
45 =item username - 
46
47 =item _password - 
48
49 =item last -
50
51 =item first -
52
53 =item disabled - empty or 'Y'
54
55 =back
56
57 =head1 METHODS
58
59 =over 4
60
61 =item new HASHREF
62
63 Creates a new internal access user.  To add the user to the database, see L<"insert">.
64
65 Note that this stores the hash reference, not a distinct copy of the hash it
66 points to.  You can ask the object for a copy with the I<hash> method.
67
68 =cut
69
70 # the new method can be inherited from FS::Record, if a table method is defined
71
72 sub table { 'access_user'; }
73
74 sub _option_table    { 'access_user_pref'; }
75 sub _option_namecol  { 'prefname'; }
76 sub _option_valuecol { 'prefvalue'; }
77
78 =item insert
79
80 Adds this record to the database.  If there is an error, returns the error,
81 otherwise returns false.
82
83 =cut
84
85 sub insert {
86   my $self = shift;
87
88   my $error = $self->check;
89   return $error if $error;
90
91   local $SIG{HUP} = 'IGNORE';
92   local $SIG{INT} = 'IGNORE';
93   local $SIG{QUIT} = 'IGNORE';
94   local $SIG{TERM} = 'IGNORE';
95   local $SIG{TSTP} = 'IGNORE';
96   local $SIG{PIPE} = 'IGNORE';
97
98   my $oldAutoCommit = $FS::UID::AutoCommit;
99   local $FS::UID::AutoCommit = 0;
100   my $dbh = dbh;
101
102   if ( $error ) {
103     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
104     return $error;
105   }
106
107   $error = $self->SUPER::insert(@_);
108
109   if ( $error ) {
110     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
111     return $error;
112   } else {
113     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
114     '';
115   }
116
117 }
118
119 =item delete
120
121 Delete this record from the database.
122
123 =cut
124
125 sub delete {
126   my $self = shift;
127
128   local $SIG{HUP} = 'IGNORE';
129   local $SIG{INT} = 'IGNORE';
130   local $SIG{QUIT} = 'IGNORE';
131   local $SIG{TERM} = 'IGNORE';
132   local $SIG{TSTP} = 'IGNORE';
133   local $SIG{PIPE} = 'IGNORE';
134
135   my $oldAutoCommit = $FS::UID::AutoCommit;
136   local $FS::UID::AutoCommit = 0;
137   my $dbh = dbh;
138
139   my $error = $self->SUPER::delete(@_);
140
141   if ( $error ) {
142     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
143     return $error;
144   } else {
145     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
146     '';
147   }
148
149 }
150
151 =item replace OLD_RECORD
152
153 Replaces the OLD_RECORD with this one in the database.  If there is an error,
154 returns the error, otherwise returns false.
155
156 =cut
157
158 sub replace {
159   my $new = shift;
160
161   my $old = ( ref($_[0]) eq ref($new) )
162               ? shift
163               : $new->replace_old;
164
165   local $SIG{HUP} = 'IGNORE';
166   local $SIG{INT} = 'IGNORE';
167   local $SIG{QUIT} = 'IGNORE';
168   local $SIG{TERM} = 'IGNORE';
169   local $SIG{TSTP} = 'IGNORE';
170   local $SIG{PIPE} = 'IGNORE';
171
172   my $oldAutoCommit = $FS::UID::AutoCommit;
173   local $FS::UID::AutoCommit = 0;
174   my $dbh = dbh;
175
176   return "Must change password when enabling this account"
177     if $old->disabled && !$new->disabled
178     && (      $new->_password =~ /changeme/i
179            || $new->_password eq 'notyet'
180        );
181
182   my $error = $new->SUPER::replace($old, @_);
183
184   if ( $error ) {
185     $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
186     return $error;
187   } else {
188     $dbh->commit or die $dbh->errstr if $oldAutoCommit;
189     '';
190   }
191
192 }
193
194 =item check
195
196 Checks all fields to make sure this is a valid internal access user.  If there is
197 an error, returns the error, otherwise returns false.  Called by the insert
198 and replace methods.
199
200 =cut
201
202 # the check method should currently be supplied - FS::Record contains some
203 # data checking routines
204
205 sub check {
206   my $self = shift;
207
208   my $error = 
209     $self->ut_numbern('usernum')
210     || $self->ut_alpha_lower('username')
211     || $self->ut_textn('_password')
212     || $self->ut_textn('last')
213     || $self->ut_textn('first')
214     || $self->ut_foreign_keyn('user_custnum', 'cust_main', 'custnum')
215     || $self->ut_foreign_keyn('report_salesnum', 'sales', 'salesnum')
216     || $self->ut_enum('disabled', [ '', 'Y' ] )
217   ;
218   return $error if $error;
219
220   $self->SUPER::check;
221 }
222
223 =item name
224
225 Returns a name string for this user: "Last, First".
226
227 =cut
228
229 sub name {
230   my $self = shift;
231   return $self->username
232     if $self->get('last') eq 'Lastname' && $self->first eq 'Firstname'
233     or $self->get('last') eq ''         && $self->first eq '';
234   return $self->get('last'). ', '. $self->first;
235 }
236
237 =item user_cust_main
238
239 Returns the FS::cust_main object (see L<FS::cust_main>), if any, for this
240 user.
241
242 =cut
243
244 sub user_cust_main {
245   my $self = shift;
246   qsearchs( 'cust_main', { 'custnum' => $self->user_custnum } );
247 }
248
249 =item report_sales
250
251 Returns the FS::sales object (see L<FS::sales>), if any, for this
252 user.
253
254 =cut
255
256 sub report_sales {
257   my $self = shift;
258   qsearchs( 'sales', { 'salesnum' => $self->report_salesnum } );
259 }
260
261 =item access_usergroup
262
263 Returns links to the the groups this user is a part of, as FS::access_usergroup
264 objects (see L<FS::access_usergroup>).
265
266 =item agentnums 
267
268 Returns a list of agentnums this user can view (via group membership).
269
270 =cut
271
272 sub agentnums {
273   my $self = shift;
274   my $sth = dbh->prepare(
275     "SELECT DISTINCT agentnum FROM access_usergroup
276                               JOIN access_groupagent USING ( groupnum )
277        WHERE usernum = ?"
278   ) or die dbh->errstr;
279   $sth->execute($self->usernum) or die $sth->errstr;
280   map { $_->[0] } @{ $sth->fetchall_arrayref };
281 }
282
283 =item agentnums_href
284
285 Returns a hashref of agentnums this user can view.
286
287 =cut
288
289 sub agentnums_href {
290   my $self = shift;
291   scalar( { map { $_ => 1 } $self->agentnums } );
292 }
293
294 =item agentnums_sql [ HASHREF | OPTION => VALUE ... ]
295
296 Returns an sql fragement to select only agentnums this user can view.
297
298 Options are passed as a hashref or a list.  Available options are:
299
300 =over 4
301
302 =item null
303
304 The frament will also allow the selection of null agentnums.
305
306 =item null_right
307
308 The fragment will also allow the selection of null agentnums if the current
309 user has the provided access right
310
311 =item table
312
313 Optional table name in which agentnum is being checked.  Sometimes required to
314 resolve 'column reference "agentnum" is ambiguous' errors.
315
316 =item viewall_right
317
318 All agents will be viewable if the current user has the provided access right.
319 Defaults to 'View customers of all agents'.
320
321 =back
322
323 =cut
324
325 sub agentnums_sql {
326   my( $self ) = shift;
327   my %opt = ref($_[0]) ? %{$_[0]} : @_;
328
329   my $agentnum = $opt{'table'} ? $opt{'table'}.'.agentnum' : 'agentnum';
330
331   my @or = ();
332
333   my $viewall_right = $opt{'viewall_right'} || 'View customers of all agents';
334   if ( $self->access_right($viewall_right) ) {
335     push @or, "$agentnum IS NOT NULL";
336   } else {
337     push @or, "$agentnum IN (". join(',', $self->agentnums). ')';
338   }
339
340   push @or, "$agentnum IS NULL"
341     if $opt{'null'}
342     || ( $opt{'null_right'} && $self->access_right($opt{'null_right'}) );
343
344   return ' 1 = 0 ' unless scalar(@or);
345   '( '. join( ' OR ', @or ). ' )';
346
347 }
348
349 =item agentnum
350
351 Returns true if the user can view the specified agent.
352
353 =cut
354
355 sub agentnum {
356   my( $self, $agentnum ) = @_;
357   my $sth = dbh->prepare(
358     "SELECT COUNT(*) FROM access_usergroup
359                      JOIN access_groupagent USING ( groupnum )
360        WHERE usernum = ? AND agentnum = ?"
361   ) or die dbh->errstr;
362   $sth->execute($self->usernum, $agentnum) or die $sth->errstr;
363   $sth->fetchrow_arrayref->[0];
364 }
365
366 =item agents [ HASHREF | OPTION => VALUE ... ]
367
368 Returns the list of agents this user can view (via group membership), as
369 FS::agent objects.  Accepts the same options as the agentnums_sql method.
370
371 =cut
372
373 sub agents {
374   my $self = shift;
375   qsearch({
376     'table'     => 'agent',
377     'hashref'   => { disabled=>'' },
378     'extra_sql' => ' AND '. $self->agentnums_sql(@_),
379     'order_by'  => 'ORDER BY agent',
380   });
381 }
382
383 =item access_right RIGHTNAME | LISTREF
384
385 Given a right name or a list reference of right names, returns true if this
386 user has this right, or, for a list, one of the rights (currently via group
387 membership, eventually also via user overrides).
388
389 =cut
390
391 sub access_right {
392   my( $self, $rightname ) = @_;
393
394   $rightname = [ $rightname ] unless ref($rightname);
395
396   warn "$me access_right called on ". join(', ', @$rightname). "\n"
397     if $DEBUG;
398
399   #some caching of ACL requests for low-hanging fruit perf improvement
400   #since we get a new $CurrentUser object each page view there shouldn't be any
401   #issues with stickiness
402   if ( $self->{_ACLcache} ) {
403
404     unless ( grep !exists($self->{_ACLcache}{$_}), @$rightname ) {
405       warn "$me ACL cache hit for ". join(', ', @$rightname). "\n"
406         if $DEBUG;
407       return scalar( grep $self->{_ACLcache}{$_}, @$rightname );
408     }
409
410     warn "$me ACL cache miss for ". join(', ', @$rightname). "\n"
411       if $DEBUG;
412
413   } else {
414
415     warn "initializing ACL cache\n"
416       if $DEBUG;
417     $self->{_ACLcache} = {};
418
419   }
420
421   my $has_right = ' rightname IN ('. join(',', map '?', @$rightname ). ') ';
422
423   my $sth = dbh->prepare("
424     SELECT groupnum FROM access_usergroup
425                     LEFT JOIN access_group USING ( groupnum )
426                     LEFT JOIN access_right
427                          ON ( access_group.groupnum = access_right.rightobjnum )
428       WHERE usernum = ?
429         AND righttype = 'FS::access_group'
430         AND $has_right
431       LIMIT 1
432   ") or die dbh->errstr;
433   $sth->execute($self->usernum, @$rightname) or die $sth->errstr;
434   my $row = $sth->fetchrow_arrayref;
435
436   my $return = $row ? $row->[0] : '';
437
438   #just caching the single-rightname hits should be enough of a win for now
439   if ( scalar(@$rightname) == 1 ) {
440     $self->{_ACLcache}{${$rightname}[0]} = $return;
441   }
442
443   $return;
444
445 }
446
447 =item default_customer_view
448
449 Returns the default customer view for this user, from the 
450 "default_customer_view" user preference, the "cust_main-default_view" config,
451 or the hardcoded default, "basics" (formerly "jumbo" prior to 3.0).
452
453 =cut
454
455 sub default_customer_view {
456   my $self = shift;
457
458   $self->option('default_customer_view')
459     || FS::Conf->new->config('cust_main-default_view')
460     || 'basics'; #s/jumbo/basics/ starting with 3.0
461
462 }
463
464 =item spreadsheet_format [ OVERRIDE ]
465
466 Returns a hashref of this user's Excel spreadsheet download settings:
467 'extension' (xls or xlsx), 'class' (Spreadsheet::WriteExcel or
468 Excel::Writer::XLSX), and 'mime_type'.  If OVERRIDE is 'XLS' or 'XLSX',
469 use that instead of the user's setting.
470
471 =cut
472
473 # is there a better place to put this?
474 my %formats = (
475   XLS => {
476     extension => '.xls',
477     class => 'Spreadsheet::WriteExcel',
478     mime_type => 'application/vnd.ms-excel',
479   },
480   XLSX => {
481     extension => '.xlsx',
482     class => 'Excel::Writer::XLSX',
483     mime_type => # it's on wikipedia, it must be true
484       'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
485   }
486 );
487
488 sub spreadsheet_format {
489   my $self = shift;
490   my $override = shift;
491
492   my $f =  $override
493         || $self->option('spreadsheet_format') 
494         || FS::Conf->new->config('spreadsheet_format')
495         || 'XLS';
496
497   $formats{$f};
498 }
499
500 =item is_system_user
501
502 Returns true if this user has the name of a known system account.  These 
503 users cannot log into the web interface and can't have passwords set.
504
505 =cut
506
507 sub is_system_user {
508   my $self = shift;
509   return grep { $_ eq $self->username } ( qw(
510     fs_queue
511     fs_daily
512     fs_selfservice
513     fs_signup
514     fs_bootstrap
515     fs_selfserv
516     fs_api
517   ) );
518 }
519
520 =item change_password NEW_PASSWORD
521
522 =cut
523
524 sub change_password {
525   #my( $self, $password ) = @_;
526   #FS::Auth->auth_class->change_password( $self, $password );
527   FS::Auth->auth_class->change_password( @_ );
528 }
529
530 =item change_password_fields NEW_PASSWORD
531
532 =cut
533
534 sub change_password_fields {
535   #my( $self, $password ) = @_;
536   #FS::Auth->auth_class->change_password_fields( $self, $password );
537   FS::Auth->auth_class->change_password_fields( @_ );
538 }
539
540 =back
541
542 =head1 BUGS
543
544 =head1 SEE ALSO
545
546 L<FS::Record>, schema.html from the base documentation.
547
548 =cut
549
550 1;
551