AOPInboundEmail::handleCreateCase()   F
last analyzed

Complexity

Conditions 33
Paths > 20000

Size

Total Lines 170
Code Lines 128

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 1122
Metric Value
cc 33
eloc 128
nc 429496.7295
nop 2
dl 0
loc 170
ccs 0
cts 148
cp 0
crap 1122
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
 /**
3
 * 
4
 * 
5
 * @package 
6
 * @copyright SalesAgility Ltd http://www.salesagility.com
7
 * 
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
19
 * along with this program; if not, see http://www.gnu.org/licenses
20
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
21
 * Fifth Floor, Boston, MA 02110-1301  USA
22
 *
23
 * @author Salesagility Ltd <[email protected]>
24
 */
25
require_once 'modules/InboundEmail/InboundEmail.php';
26
require_once 'include/clean.php';
27
class AOPInboundEmail extends InboundEmail {
28
29
    /**
30
     * Replaces embedded image links with links to the appropriate note in the CRM.
31
     * @param $string
32
     * @param $noteIds A whitelist of note ids to replace
33
     * @return mixed
34
     */
35
    function processImageLinks($string, $noteIds){
36
        global $sugar_config;
37
        if(!$noteIds){
38
            return $string;
39
        }
40
        $matches = array();
41
        preg_match('/cid:([[:alnum:]-]*)/',$string,$matches);
42
        if(!$matches){
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
43
            return $string;
44
        }
45
        array_shift($matches);
46
        $matches = array_unique($matches);
47
        foreach($matches as $match){
48
            if(in_array($match,$noteIds)){
49
                $string = str_replace('cid:'.$match,$sugar_config['site_url']."/index.php?entryPoint=download&id={$match}&type=Notes&",$string);
50
            }
51
        }
52
        return $string;
53
    }
54
55
56
    function handleCreateCase($email, $userId) {
57
        global $current_user, $mod_strings, $current_language;
58
        $mod_strings = return_module_language($current_language, "Emails");
59
        $GLOBALS['log']->debug('In handleCreateCase in AOPInboundEmail');
60
        $c = new aCase();
61
        $this->getCaseIdFromCaseNumber($email->name, $c);
62
63
        if (!$this->handleCaseAssignment($email) && $this->isMailBoxTypeCreateCase()) {
64
            // create a case
65
            $GLOBALS['log']->debug('retrieveing email');
66
            $email->retrieve($email->id);
67
            $c = new aCase();
68
69
            $notes = $email->get_linked_beans('notes','Notes');
70
            $noteIds = array();
71
            foreach($notes as $note){
72
                $noteIds[] = $note->id;
73
            }
74
            if($email->description_html) {
75
                $c->description = $this->processImageLinks(SugarCleaner::cleanHtml($email->description_html),$noteIds);
76
            }else{
77
                $c->description = $email->description;
78
            }
79
            $c->assigned_user_id = $userId;
80
            $c->name = $email->name;
81
            $c->status = 'New';
82
            $c->priority = 'P1';
83
84
            if(!empty($email->reply_to_email)) {
85
                $contactAddr = $email->reply_to_email;
86
            } else {
87
                $contactAddr = $email->from_addr;
88
            }
89
90
            $GLOBALS['log']->debug('finding related accounts with address ' . $contactAddr);
91
            if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
92
                if (sizeof($accountIds) == 1) {
93
                    $c->account_id = $accountIds[0];
94
95
                    $acct = new Account();
96
                    $acct->retrieve($c->account_id);
97
                    $c->account_name = $acct->name;
98
                } // if
99
            } // if
100
            $contactIds = $this->getRelatedId($contactAddr, 'contacts');
101
            if(!empty($contactIds)) {
102
                $c->contact_created_by_id = $contactIds[0];
103
            }
104
105
            $c->save(true);
106
            $caseId = $c->id;
107
            $c = new aCase();
108
            $c->retrieve($caseId);
109
            if($c->load_relationship('emails')) {
110
                $c->emails->add($email->id);
111
            } // if
112
                if(!empty($contactIds) && $c->load_relationship('contacts')) {
113
                    if (!$accountIds && count($contactIds) == 1) {
114
                        $contact = BeanFactory::getBean('Contacts', $contactIds[0]);
115
                        if ($contact->load_relationship('accounts')) {
116
                            $acct = $contact->accounts->get();
117
                            if ($c->load_relationship('accounts') && !empty($acct[0])) {
118
                                $c->accounts->add($acct[0]);
119
                            }
120
                        }
121
                    }
122
                    $c->contacts->add($contactIds);
123
                } // if
124
            foreach($notes as $note){
125
                //Link notes to case also
126
                $newNote = BeanFactory::newBean('Notes');
127
                $newNote->name = $note->name;
128
                $newNote->file_mime_type = $note->file_mime_type;
129
                $newNote->filename = $note->filename;
130
                $newNote->parent_type = 'Cases';
131
                $newNote->parent_id = $c->id;
132
                $newNote->save();
133
                $srcFile = "upload://{$note->id}";
134
                $destFile = "upload://{$newNote->id}";
135
                copy($srcFile,$destFile);
136
137
            }
138
139
            $c->email_id = $email->id;
140
            $email->parent_type = "Cases";
141
            $email->parent_id = $caseId;
142
            // assign the email to the case owner
143
            $email->assigned_user_id = $c->assigned_user_id;
144
            $email->name = str_replace('%1', $c->case_number, $c->getEmailSubjectMacro()) . " ". $email->name;
145
            $email->save();
146
            $GLOBALS['log']->debug('InboundEmail created one case with number: '.$c->case_number);
147
            $createCaseTemplateId = $this->get_stored_options('create_case_email_template', "");
148
            if(!empty($this->stored_options)) {
149
                $storedOptions = unserialize(base64_decode($this->stored_options));
150
            }
151
            if(!empty($createCaseTemplateId)) {
152
                $fromName = "";
153
                $fromAddress = "";
154
                if (!empty($this->stored_options)) {
155
                    $fromAddress = $storedOptions['from_addr'];
156
                    $fromName = from_html($storedOptions['from_name']);
157
                    $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
158
                    $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
159
                } // if
160
                $defaults = $current_user->getPreferredEmail();
161
                $fromAddress = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
162
                $fromName = (!empty($fromName)) ? $fromName : $defaults['name'];
163
                $to[0]['email'] = $contactAddr;
164
165
                // handle to name: address, prefer reply-to
166
                if(!empty($email->reply_to_name)) {
167
                    $to[0]['display'] = $email->reply_to_name;
168
                } elseif(!empty($email->from_name)) {
169
                    $to[0]['display'] = $email->from_name;
170
                }
171
172
                $et = new EmailTemplate();
173
                $et->retrieve($createCaseTemplateId);
174
                if(empty($et->subject))		{ $et->subject = ''; }
175
                if(empty($et->body))		{ $et->body = ''; }
176
                if(empty($et->body_html))	{ $et->body_html = ''; }
177
178
                $et->subject = "Re:" . " " . str_replace('%1', $c->case_number, $c->getEmailSubjectMacro() . " ". $c->name);
179
180
                $html = trim($email->description_html);
181
                $plain = trim($email->description);
182
183
                $email->email2init();
184
                $email->from_addr = $email->from_addr_name;
185
                $email->to_addrs = $email->to_addrs_names;
186
                $email->cc_addrs = $email->cc_addrs_names;
187
                $email->bcc_addrs = $email->bcc_addrs_names;
188
                $email->from_name = $email->from_addr;
189
190
                $email = $email->et->handleReplyType($email, "reply");
191
                $ret = $email->et->displayComposeEmail($email);
192
                $ret['description'] = empty($email->description_html) ?  str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
193
194
                $reply = new Email();
195
                $reply->type				= 'out';
196
                $reply->to_addrs			= $to[0]['email'];
197
                $reply->to_addrs_arr		= $to;
198
                $reply->cc_addrs_arr		= array();
199
                $reply->bcc_addrs_arr		= array();
200
                $reply->from_name			= $fromName;
201
                $reply->from_addr			= $fromAddress;
202
                $reply->reply_to_name		= $replyToName;
203
                $reply->reply_to_addr		= $replyToAddr;
204
                $reply->name				= $et->subject;
205
                $reply->description			= $et->body . "<div><hr /></div>" .  $email->description;
206
                if (!$et->text_only) {
207
                    $reply->description_html	= $et->body_html .  "<div><hr /></div>" . $email->description;
208
                }
209
                $GLOBALS['log']->debug('saving and sending auto-reply email');
210
                //$reply->save(); // don't save the actual email.
211
                $reply->send();
212
            } // if
213
214
        } else {
215
            echo "First if not matching\n";
216
            if(!empty($email->reply_to_email)) {
217
                $contactAddr = $email->reply_to_email;
218
            } else {
219
                $contactAddr = $email->from_addr;
220
            }
221
            $this->handleAutoresponse($email, $contactAddr);
222
        }
223
        echo "End of handle create case\n";
224
225
    } // fn
226
}