summaryrefslogtreecommitdiff
path: root/FS/FS/TicketSystem/RT_Internal.pm
blob: f47648e7f75c59f2a3d1b0793d218ccdfdce3448 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
package FS::TicketSystem::RT_Internal;

use strict;
use vars qw( @ISA $DEBUG $me );
use Data::Dumper;
use MIME::Entity;
use FS::UID qw(dbh);
use FS::CGI qw(popurl);
use FS::TicketSystem::RT_Libs;
use RT::CurrentUser;

@ISA = qw( FS::TicketSystem::RT_Libs );

$DEBUG = 0;
$me = '[FS::TicketSystem::RT_Internal]';

sub sql_num_customer_tickets {
  "( select count(*) from Tickets
                     join Links on ( Tickets.id = Links.LocalBase )
     where ( Status = 'new' or Status = 'open' or Status = 'stalled' )
       and Target = 'freeside://freeside/cust_main/' || custnum
   )";
}

sub baseurl {
  #my $self = shift;
  if ( $RT::URI::freeside::URL ) {
    $RT::URI::freeside::URL. '/rt/';
  } else {
    'http://you_need_to_set_RT_URI_freeside_URL_in_SiteConfig.pm/';
  }
}

#mapping/genericize??
#ShowConfigTab ModifySelf
sub access_right {
  my( $self, $session, $right ) = @_;

  #return '' unless $conf->config('ticket_system');
  return '' unless FS::Conf->new->config('ticket_system');

  $session = $self->session($session);

  #warn "$me access_right: CurrentUser ". $session->{'CurrentUser'}. ":\n".
  #     ( $DEBUG>1 ? Dumper($session->{'CurrentUser'}) : '' )
  #  if $DEBUG > 1;

  $session->{'CurrentUser'}->HasRight( Right  => $right,
                                       Object => $RT::System );
}

sub session {
  my( $self, $session ) = @_;

  if ( $session && $session->{'Current_User'} ) {
    warn "$me session: using existing session and CurrentUser: \n".
         Dumper($session->{'CurrentUser'})
      if $DEBUG;
 } else {
    warn "$me session: loading session and CurrentUser\n" if $DEBUG > 1;
    $session = $self->_web_external_auth($session);
  }

  $session;
}

sub init {
  my $self = shift;

  warn "$me init: loading RT libraries\n" if $DEBUG;
  eval '
    use lib ( "/opt/rt3/local/lib", "/opt/rt3/lib" );
    use RT;
    #it looks like the rest are taken care of these days in RT::InitClasses
    #use RT::Ticket;
    #use RT::Transactions;
    #use RT::Users;
    #use RT::CurrentUser;
    #use RT::Templates;
    #use RT::Queues;
    #use RT::ScripActions;
    #use RT::ScripConditions;
    #use RT::Scrips;
    #use RT::Groups;
    #use RT::GroupMembers;
    #use RT::CustomFields;
    #use RT::CustomFieldValues;
    #use RT::ObjectCustomFieldValues;

    #for web external auth...
    use RT::Interface::Web;
  ';
  die $@ if $@;

  warn "$me init: loading RT config\n" if $DEBUG;
  {
    local $SIG{__DIE__};
    eval 'RT::LoadConfig();';
  }
  die $@ if $@;

  warn "$me init: initializing RT\n" if $DEBUG;
  {
    local $SIG{__DIE__};
    eval 'RT::Init("NoSignalHandlers"=>1);';
  }
  die $@ if $@;

  warn "$me init: complete" if $DEBUG;
}

=item create_ticket SESSION_HASHREF, OPTION => VALUE ...

Class method.  Creates a ticket.  If there is an error, returns the scalar
error, otherwise returns the newly created RT::Ticket object.

Accepts the following options:

=over 4

=item queue

Queue name or Id

=item subject

Ticket subject

=item requestor

Requestor email address or arrayref of addresses

=item cc

Cc: email address or arrayref of addresses

=item message

Ticket message

=item mime_type

MIME type to use for message.  Defaults to text/plain.  Specifying text/html
can be useful to use HTML markup in message.

=item custnum

Customer number (see L<FS::cust_main>) to associate with ticket.

=item svcnum

Service number (see L<FS::cust_svc>) to associate with ticket.  Will also
associate the customer who has this service (unless the service is unlinked).

=back

=cut

sub create_ticket {
  my($self, $session, %param) = @_;

  $session = $self->session($session);

  my $Queue = RT::Queue->new($session->{'CurrentUser'});
  $Queue->Load( $param{'queue'} );

  my $req = ref($param{'requestor'})
              ? $param{'requestor'}
              : ( $param{'requestor'} ? [ $param{'requestor'} ] : [] );

  my $cc = ref($param{'cc'})
             ? $param{'cc'}
             : ( $param{'cc'} ? [ $param{'cc'} ] : [] );

  my $mimeobj = MIME::Entity->build(
    'Data' => $param{'message'},
    'Type' => ( $param{'mime_type'} || 'text/plain' ),
  );

  my %ticket = (
    'Queue'     => $Queue->Id,
    'Subject'   => $param{'subject'},
    'Requestor' => $req,
    'Cc'        => $cc,
    'MIMEObj'   => $mimeobj,
  );
  warn Dumper(\%ticket) if $DEBUG > 1;

  my $Ticket = RT::Ticket->new($session->{'CurrentUser'});
  my( $id, $Transaction, $ErrStr );
  {
    local $SIG{__DIE__};
    ( $id, $Transaction, $ErrStr ) = $Ticket->Create( %ticket );
  }
  return $ErrStr if $id == 0;

  warn "ticket got id $id\n" if $DEBUG;

  #XXX check errors adding custnum/svcnum links (put it in a transaction)...
  # but we do already know they're good

  if ( $param{'custnum'} ) {
    my( $val, $msg ) = $Ticket->_AddLink(
     'Type'   => 'MemberOf',
     'Target' => 'freeside://freeside/cust_main/'. $param{'custnum'},
    );
  }

  if ( $param{'svcnum'} ) {
    my( $val, $msg ) = $Ticket->_AddLink(
     'Type'   => 'MemberOf',
     'Target' => 'freeside://freeside/cust_svc/'. $param{'svcnum'},
    );
  }

  $Ticket;
}

#shameless false laziness w/RT::Interface::Web::AttemptExternalAuth
# to get logged into RT from afar
sub _web_external_auth {
  my( $self, $session ) = @_;

  my $user = $FS::CurrentUser::CurrentUser->username;

  $session ||= {};
  $session->{'CurrentUser'} = RT::CurrentUser->new();

  warn "$me _web_external_auth loading RT user for $user\n"
    if $DEBUG > 1;

  $session->{'CurrentUser'}->Load($user);

  if ( ! $session->{'CurrentUser'}->Id() ) {

      # Create users on-the-fly

      warn "can't load RT user for $user; auto-creating\n"
        if $DEBUG;

      my $UserObj = RT::User->new( RT::CurrentUser->new('RT_System') );

      my ( $val, $msg ) = $UserObj->Create(
          %{ ref($RT::AutoCreate) ? $RT::AutoCreate : {} },
          Name  => $user,
          Gecos => $user,
      );

      if ($val) {

          # now get user specific information, to better create our user.
          my $new_user_info
              = RT::Interface::Web::WebExternalAutoInfo($user);

          # set the attributes that have been defined.
          # FIXME: this is a horrible kludge. I'm sure there's something cleaner
          foreach my $attribute (
              'Name',                  'Comments',
              'Signature',             'EmailAddress',
              'PagerEmailAddress',     'FreeformContactInfo',
              'Organization',          'Disabled',
              'Privileged',            'RealName',
              'NickName',              'Lang',
              'EmailEncoding',         'WebEncoding',
              'ExternalContactInfoId', 'ContactInfoSystem',
              'ExternalAuthId',        'Gecos',
              'HomePhone',             'WorkPhone',
              'MobilePhone',           'PagerPhone',
              'Address1',              'Address2',
              'City',                  'State',
              'Zip',                   'Country'
              )
          {
              #uhh, wrong root
              #$m->comp( '/Elements/Callback', %ARGS,
              #    _CallbackName => 'NewUser' );

              my $method = "Set$attribute";
              $UserObj->$method( $new_user_info->{$attribute} )
                  if ( defined $new_user_info->{$attribute} );
          }
          $session->{'CurrentUser'}->Load($user);
      }
      else {

         # we failed to successfully create the user. abort abort abort.
          delete $session->{'CurrentUser'};

          die "can't auto-create RT user"; #an error message would be nice :/
          #$m->abort() unless $RT::WebFallbackToInternalAuth;
          #$m->comp( '/Elements/Login', %ARGS,
          #    Error => loc( 'Cannot create user: [_1]', $msg ) );
      }
  }

  unless ( $session->{'CurrentUser'}->Id() ) {
      delete $session->{'CurrentUser'};

      die "can't auto-create RT user";
      #$user = $orig_user;
      # 
      #if ($RT::WebExternalOnly) {
      #    $m->comp( '/Elements/Login', %ARGS,
      #        Error => loc('You are not an authorized user') );
      #    $m->abort();
      #}
  }

  $session;

}

1;