EmailsController::update()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 14
nc 5
nop 2
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers\Admin\helpdesk;
4
5
// controllers
6
use App\Http\Controllers\Admin\MailFetch as Fetch;
7
use App\Http\Controllers\Controller;
8
use App\Http\Requests\helpdesk\EmailsRequest;
9
// model
10
use App\Http\Requests\helpdesk\Mail\MailRequest;
11
use App\Model\helpdesk\Agent\Department;
12
use App\Model\helpdesk\Email\Emails;
13
use App\Model\helpdesk\Manage\Help_topic;
14
use App\Model\helpdesk\Settings\Email;
15
use App\Model\helpdesk\Ticket\Ticket_Priority;
16
// classes
17
use App\Model\helpdesk\Utility\MailboxProtocol;
18
use Crypt;
19
use Exception;
20
use Lang;
21
22
/**
23
 * ======================================
24
 * EmailsController.
25
 * ======================================
26
 * This Controller is used to define below mentioned set of functions applied to the Emails in the system.
27
 *
28
 * @author Ladybird <[email protected]>
29
 */
30
class EmailsController extends Controller
31
{
32
    /**
33
     * Defining constructor variables.
34
     *
35
     * @return type
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
36
     */
37
    public function __construct()
38
    {
39
        $this->middleware('auth');
40
        $this->middleware('roles');
41
    }
42
43
    /**
44
     * Display a listing of the Emails.
45
     *
46
     * @param type Emails $emails
47
     *
48
     * @return type view
49
     */
50 View Code Duplication
    public function index(Emails $email)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
51
    {
52
        try {
53
            // fetch all the emails from emails table
54
            $emails = $email->get();
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<App\Model\helpdesk\Email\Emails>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
55
56
            return view('themes.default1.admin.helpdesk.emails.emails.index', compact('emails'));
57
        } catch (Exception $e) {
58
            return redirect()->back()->with('fails', $e->getMessage());
59
        }
60
    }
61
62
    /**
63
     * Show the form for creating a new resource.
64
     *
65
     * @param type Department      $department
66
     * @param type Help_topic      $help
67
     * @param type Priority        $priority
68
     * @param type MailboxProtocol $mailbox_protocol
69
     *
70
     * @return type Response
71
     */
72
    public function create(Department $department, Help_topic $help, Ticket_Priority $ticket_priority, MailboxProtocol $mailbox_protocol)
73
    {
74
        try {
75
            // fetch all the departments from the department table
76
            $departments = $department->get();
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<App\Model\helpdesk\Agent\Department>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
77
            // fetch all the helptopics from the helptopic table
78
            $helps = $help->where('status', '=', 1)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Manage\Help_topic>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
79
            // fetch all the types of priority from the ticket_priority table
80
            $priority = $ticket_priority->where('status', '=', 1)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Ticket\Ticket_Priority>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
81
            // fetch all the types of mailbox protocols from the mailbox_protocols table
82
            $mailbox_protocols = $mailbox_protocol->get();
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<App\Model\helpdes...tility\MailboxProtocol>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
83
84
            $service = new \App\Model\MailJob\MailService();
85
            $services = $service->lists('name', 'id')->toArray();
0 ignored issues
show
Documentation Bug introduced by
The method lists does not exist on object<App\Model\MailJob\MailService>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
86
87
            // return with all the table data
88
            return view('themes.default1.admin.helpdesk.emails.emails.create', compact('mailbox_protocols', 'priority', 'departments', 'helps', 'services'));
89
        } catch (Exception $e) {
90
            // return error messages if any
91
            return redirect()->back()->with('fails', $e->getMessage());
92
        }
93
    }
94
95
    /**
96
     * Check for email input validation.
97
     *
98
     * @param EmailsRequest $request
99
     *
100
     * @return int
101
     */
102
    public function validatingEmailSettings(MailRequest $request, $id = '')
103
    {
104
        //dd($request->all());
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
105
        try {
106
            $service_request = $request->except('sending_status', '_token', 'email_address', 'email_name', 'password', 'department', 'priority', 'help_topic', 'fetching_protocol', 'fetching_host', 'fetching_port', 'fetching_encryption', 'imap_authentication', 'sending_protocol', 'sending_host', 'sending_port', 'sending_encryption', 'smtp_authentication', 'internal_notes', '_wysihtml5_mode', 'code');
107
            $service = $request->input('sending_protocol');
108
            $validate = '/novalidate-cert';
109
            $fetch = 1;
110
            $send = 1;
111
            //dd($request->input('fetching_status'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
80% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
112
            if ($request->input('fetching_status')) {
113
                $fetch = $this->getImapStream($request, $validate);
0 ignored issues
show
Documentation introduced by
$request is of type object<App\Http\Requests...pdesk\Mail\MailRequest>, but the function expects a object<App\Http\Controllers\Admin\helpdesk\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Unused Code introduced by
The call to EmailsController::getImapStream() has too many arguments starting with $validate.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
114
            }
115
            if ($request->input('sending_status') === 'on') {
116
                $this->emailService($service, $service_request);
117
                $send = $this->checkMail($request);
118
            }
119
            if ($send == 1 && $fetch == 1) {
120
                $this->store($request, $service_request, $id);
121
122
                return $this->jsonResponse('success', Lang::get('lang.success'));
123
            }
124
125
            return $this->validateEmailError($send, $fetch);
126
        } catch (Exception $ex) {
127
            $message = $ex->getMessage();
128
            if ($request->input('fetching_status') && imap_last_error()) {
129
                $message = imap_last_error();
130
            }
131
            loging('mail-config', $message);
132
133
            return $this->jsonResponse('fails', $message);
134
        }
135
    }
136
137
    public function validateEmailError($out, $in)
138
    {
139
        if ($out !== 1) {
140
            return $this->jsonResponse('fails', Lang::get('lang.outgoing_email_connection_failed'));
141
        }
142
        if ($in !== 1) {
143
            return $this->jsonResponse('fails', Lang::get('lang.incoming_email_connection_failed_please_check_email_credentials_or_imap_settings'));
144
        }
145
    }
146
147
    public function jsonResponse($type, $message)
148
    {
149
        if ($type == 'fails') {
150
            $result = ['fails' => $message];
151
        }
152
        if ($type == 'success') {
153
            $result = ['success' => $message];
154
        }
155
156
        return response()->json(compact('result'));
157
    }
158
159
    /**
160
     * Store a newly created resource in storage.
161
     *
162
     * @param type Emails        $email
163
     * @param type EmailsRequest $request
164
     *
165
     * @return type Redirect
166
     */
167
    public function store($request, $service_request = [], $id = '')
168
    {
169
        $email = new Emails();
170
        if ($id !== '') {
171
            $email = $email->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Email\Emails>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
172
        }
173
174
        $email->email_address = $request->email_address;
175
176
        $email->email_name = $request->email_name;
177
        $email->fetching_host = $request->fetching_host;
178
        $email->fetching_port = $request->fetching_port;
179
        $email->fetching_protocol = $request->fetching_protocol;
180
        $email->sending_host = $request->sending_host;
181
        $email->sending_port = $request->sending_port;
182
        $email->sending_protocol = $this->getDriver($request->sending_protocol);
183
        $email->sending_encryption = $request->sending_encryption;
184
185
        if ($request->smtp_validate == 'on') {
186
            $email->smtp_validate = $request->smtp_validate;
187
        }
188
189
        if ($request->input('password')) {
190
            $email->password = Crypt::encrypt($request->input('password'));
191
        }
192
        if ($request->input('fetching_status') == 'on') {
193
            $email->fetching_status = 1;
194
        } else {
195
            $email->fetching_status = 0;
196
        }
197
        if ($request->input('sending_status') == 'on') {
198
            $email->sending_status = 1;
199
        } else {
200
            $email->sending_status = 0;
201
        }
202
        if ($request->input('auto_response') == 'on') {
203
            $email->auto_response = 1;
204
        } else {
205
            $email->auto_response = 0;
206
        }
207
        $email->fetching_encryption = $request->input('fetching_encryption');
208
        if (!$request->input('imap_validate')) {
209
            $email->mailbox_protocol = 'novalidate-cert';
210
        }
211
        $email->department = $this->departmentValue($request->input('department'));
212
        // fetching priority value
213
        $email->priority = $this->priorityValue($request->input('priority'));
214
        // fetching helptopic value
215
        $email->help_topic = $this->helpTopicValue($request->input('help_topic'));
216
        // inserting the encrypted value of password
217
        $email->password = Crypt::encrypt($request->input('password'));
218
        $email->save(); // run save
219
        if ($request->input('fetching_status')) {
220
            $this->fetch($email);
221
        }
222
        if ($id === '') {
223
            // Creating a default system email as the first email is inserted to the system
224
            $email_settings = Email::where('id', '=', '1')->first();
225
            $email_settings->sys_email = $email->id;
226
            $email_settings->save();
227
        } else {
228
            $this->update($id, $request);
0 ignored issues
show
Documentation introduced by
$id is of type string, but the function expects a object<App\Http\Controllers\Admin\helpdesk\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
229
        }
230
        if (count($service_request) > 0) {
231
            $this->saveMailService($email->id, $service_request, $this->getDriver($request->sending_protocol));
232
        }
233
        if ($request->input('fetching_status')) {
234
            $this->fetch($email);
235
        }
236
237
        return 1;
238
    }
239
240
    public function checkMail($request)
241
    {
242
        $mailservice_id = $request->input('sending_protocol');
243
        $driver = $this->getDriver($mailservice_id);
244
        $username = $request->input('email_address');
245
        $password = $request->input('password');
246
        $name = $request->input('email_name');
247
        $host = $request->input('sending_host');
248
        $port = $request->input('sending_port');
249
        $enc = $request->input('sending_encryption');
250
        $service_request = $request->except('sending_status', '_token', 'email_address', 'email_name', 'password', 'department', 'priority', 'help_topic', 'fetching_protocol', 'fetching_host', 'fetching_port', 'fetching_encryption', 'imap_authentication', 'sending_protocol', 'sending_host', 'sending_port', 'sending_encryption', 'smtp_authentication', 'internal_notes', '_wysihtml5_mode');
251
252
        $this->emailService($driver, $service_request);
253
        $this->setMailConfig($driver, $username, $name, $password, $enc, $host, $port);
254
        $transport = \Swift_SmtpTransport::newInstance($host, $port, $enc);
255
        $transport->setUsername($username);
256
        $transport->setPassword($password);
257
        $mailer = \Swift_Mailer::newInstance($transport);
258
        $mailer->getTransport()->start();
259
260
        return 1;
261
    }
262
263
    public function sendDiagnoEmail($request)
264
    {
265
        $mailservice_id = $request->input('sending_protocol');
266
        $driver = $this->getDriver($mailservice_id);
267
        $username = $request->input('email_address');
268
        $password = $request->input('password');
269
        $name = $request->input('email_name');
270
        $host = $request->input('sending_host');
271
        $port = $request->input('sending_port');
272
        $enc = $request->input('sending_encryption');
273
        $service_request = $request->except('sending_status', '_token', 'email_address', 'email_name', 'password', 'department', 'priority', 'help_topic', 'fetching_protocol', 'fetching_host', 'fetching_port', 'fetching_encryption', 'imap_authentication', 'sending_protocol', 'sending_host', 'sending_port', 'sending_encryption', 'smtp_authentication', 'internal_notes', '_wysihtml5_mode');
274
275
        $this->emailService($driver, $service_request);
276
        $this->setMailConfig($driver, $username, $name, $password, $enc, $host, $port);
277
        $controller = new \App\Http\Controllers\Common\PhpMailController();
278
        $subject = 'test';
279
        $data = 'test';
280
        //dd(\Config::get('mail'),\Config::get('services'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
281
        $send = $controller->laravelMail($username, $name, $subject, $data, [], []);
282
283
        return $send;
284
    }
285
286
    public function setMailConfig($driver, $username, $name, $password, $enc, $host, $port)
287
    {
288
        $configs = [
289
            'username'   => $username,
290
            'from'       => ['address' => $username, 'name' => $name],
291
            'password'   => $password,
292
            'encryption' => $enc,
293
            'host'       => $host,
294
            'port'       => $port,
295
            'driver'     => $driver,
296
        ];
297 View Code Duplication
        foreach ($configs as $key => $config) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
298
            if (is_array($config)) {
299
                foreach ($config as $from) {
300
                    \Config::set('mail.'.$key, $config);
301
                }
302
            } else {
303
                \Config::set('mail.'.$key, $config);
304
            }
305
        }
306
    }
307
308
    public function getDriver($driver_id)
309
    {
310
        $short = '';
311
        $email_drivers = new \App\Model\MailJob\MailService();
312
        $email_driver = $email_drivers->find($driver_id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\MailJob\MailService>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
313
        if ($email_driver) {
314
            $short = $email_driver->short_name;
315
        }
316
317
        return $short;
318
    }
319
320
    /**
321
     * Show the form for editing the specified resource.
322
     *
323
     * @param type int             $id
324
     * @param type Department      $department
325
     * @param type Help_topic      $help
326
     * @param type Emails          $email
327
     * @param type Priority        $priority
328
     * @param type MailboxProtocol $mailbox_protocol
329
     *
330
     * @return type Response
331
     */
332
    public function edit($id, Department $department, Help_topic $help, Emails $email, Ticket_Priority $ticket_priority, MailboxProtocol $mailbox_protocol)
333
    {
334
        try {
335
            $sys_email = \DB::table('settings_email')->select('sys_email')->where('id', '=', 1)->first();
336
            // dd($sys_email);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
337
            // fetch the selected emails
338
            $emails = $email->whereId($id)->first();
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<App\Model\helpdesk\Email\Emails>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
339
            // get all the departments
340
            $departments = $department->get();
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<App\Model\helpdesk\Agent\Department>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
341
            //get count of emails
342
            $count = $email->count();
0 ignored issues
show
Documentation Bug introduced by
The method count does not exist on object<App\Model\helpdesk\Email\Emails>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
343
            // get all the helptopic
344
            $helps = $help->where('status', '=', 1)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Manage\Help_topic>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
345
            // get all the priority
346
            $priority = $ticket_priority->where('status', '=', 1)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Ticket\Ticket_Priority>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
347
            // get all the mailbox protocols
348
            $mailbox_protocols = $mailbox_protocol->get();
0 ignored issues
show
Documentation Bug introduced by
The method get does not exist on object<App\Model\helpdes...tility\MailboxProtocol>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
349
350
            $service = new \App\Model\MailJob\MailService();
351
            $services = $service->lists('name', 'id')->toArray();
0 ignored issues
show
Documentation Bug introduced by
The method lists does not exist on object<App\Model\MailJob\MailService>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
352
353
            // return if the execution is succeeded
354
            return view('themes.default1.admin.helpdesk.emails.emails.edit', compact('mailbox_protocols', 'priority', 'departments', 'helps', 'emails', 'sys_email', 'services'))->with('count', $count);
0 ignored issues
show
Bug introduced by
The method with does only exist in Illuminate\View\View, but not in Illuminate\Contracts\View\Factory.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
355
        } catch (Exception $e) {
356
            // return if try fails
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
357
            return redirect()->back()->with('fails', $e->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The return type of return redirect()->back(...ls', $e->getMessage()); (Illuminate\Http\RedirectResponse) is incompatible with the return type documented by App\Http\Controllers\Adm...\EmailsController::edit of type App\Http\Controllers\Admin\helpdesk\type.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
358
        }
359
    }
360
361
    /**
362
     * Check for email input validation.
363
     *
364
     * @param EmailsRequest $request
365
     *
366
     * @return int
367
     */
368
    public function validatingEmailSettingsUpdate($id, MailRequest $request)
369
    {
370
        try {
371
            return $this->validatingEmailSettings($request, $id);
372
        } catch (Exception $ex) {
373
            $message = $ex->getMessage();
374
            if (imap_last_error()) {
375
                $message = imap_last_error();
376
            }
377
            //dd($ex->getMessage());
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
378
            loging('mail-config', $message);
379
            //Log::error($ex->getMessage());
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
380
            return $this->jsonResponse('fails', $message);
381
        }
382
    }
383
384
    /**
385
     * Update the specified resource in storage.
386
     *
387
     * @param type                   $id
388
     * @param type Emails            $email
389
     * @param type EmailsEditRequest $request
390
     *
391
     * @return type Response
392
     */
393
    public function update($id, $request)
394
    {
395
        try {
396
            if ($request->sys_email == 'on') {
397
                $system = \DB::table('settings_email')
0 ignored issues
show
Unused Code introduced by
$system is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
398
                        ->where('id', '=', 1)
399
                        ->update(['sys_email' => $id]);
400
            } elseif ($request->input('count') <= 1 && $request->sys_email == null) {
401
                $system = \DB::table('settings_email')
0 ignored issues
show
Unused Code introduced by
$system is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
402
                        ->where('id', '=', 1)
403
                        ->update(['sys_email' => null]);
404
            }
405
            $return = 1;
406
        } catch (Exception $e) {
407
            $return = $e->getMessage();
408
        }
409
410
        return $return;
411
    }
412
413
    /**
414
     * Remove the specified resource from storage.
415
     *
416
     * @param type int    $id
417
     * @param type Emails $email
418
     *
419
     * @return type Redirect
420
     */
421 View Code Duplication
    public function destroy($id, Emails $email)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
422
    {
423
        // fetching the details on the basis of the $id passed to the function
424
        $default_system_email = Email::where('id', '=', '1')->first();
425
        if ($default_system_email->sys_email) {
426
            // checking if the default system email is the passed email
427
            if ($id == $default_system_email->sys_email) {
428
                return redirect('emails')->with('fails', Lang::get('lang.you_cannot_delete_system_default_email'));
429
            }
430
        }
431
        try {
432
            // fetching the database instance of the current email
433
            $emails = $email->whereId($id)->first();
0 ignored issues
show
Documentation Bug introduced by
The method whereId does not exist on object<App\Model\helpdesk\Email\Emails>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
434
            // checking if deleting the email is success or if it's carrying any dependencies
435
            $emails->delete();
436
437
            return redirect('emails')->with('success', Lang::get('lang.email_deleted_sucessfully'));
438
        } catch (Exception $e) {
439
            // returns if the try fails
440
            return redirect()->back()->with('fails', $e->getMessage());
441
        }
442
    }
443
444
    /**
445
     * Create imap connection.
446
     *
447
     * @param type $request
448
     *
449
     * @return type int
450
     */
451
    public function getImapStream($request)
452
    {
453
        $host = $request->input('fetching_host');
454
        $port = $request->input('fetching_port');
455
        $service = $request->input('fetching_protocol');
456
        $encryption = $request->input('fetching_encryption');
457
        $validate = $request->input('imap_validate');
458
        $username = $request->input('email_address');
459
        $password = $request->input('password');
460
        $server = new Fetch($host, $port, $service);
461
        //$server->setFlag('novalidate-cert');
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
462
        if ($encryption != '') {
463
            $server->setFlag($encryption);
464
        }
465
        if (!$validate) {
466
            $server->setFlag('novalidate-cert');
467
        } else {
468
            $server->setFlag('validate-cert');
469
        }
470
471
        $server->setAuthentication($username, $password);
472
        $server->getImapStream();
473
474
        return 1;
475
    }
476
477
    /**
478
     * Check connection.
479
     *
480
     * @param type $imap_stream
481
     *
482
     * @return type int
483
     */
484
    public function checkImapStream($imap_stream)
485
    {
486
        $check_imap_stream = imap_check($imap_stream);
487
        if ($check_imap_stream) {
488
            $imap_stream = 1;
489
        } else {
490
            $imap_stream = 0;
491
        }
492
493
        return $imap_stream;
494
    }
495
496
    /**
497
     * Get smtp connection.
498
     *
499
     * @param type $request
500
     *
501
     * @return int
502
     */
503
    public function getSmtp($request)
504
    {
505
        $sending_status = $request->input('sending_status');
0 ignored issues
show
Unused Code introduced by
$sending_status is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
506
        // cheking for the sending protocol
507
        if ($request->input('sending_protocol') == 'smtp') {
508
            $mail = new \PHPMailer();
509
            $mail->isSMTP();
510
            $mail->Host = $request->input('sending_host');            // Specify main and backup SMTP servers
511
            //$mail->SMTPAuth = true;                                   // Enable SMTP authentication
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
512
            $mail->Username = $request->input('email_address');       // SMTP username
513
            $mail->Password = $request->input('password');            // SMTP password
514
            $mail->SMTPSecure = $request->input('sending_encryption'); // Enable TLS encryption, `ssl` also accepted
515
            $mail->Port = $request->input('sending_port');            // TCP port to connect to
516
            if (!$request->input('smtp_validate')) {
517
                $mail->SMTPAuth = true;                               // Enable SMTP authentication
518
                $mail->SMTPOptions = [
519
                    'ssl' => [
520
                        'verify_peer'       => false,
521
                        'verify_peer_name'  => false,
522
                        'allow_self_signed' => true,
523
                    ],
524
                ];
525
                if ($mail->smtpConnect($mail->SMTPOptions) == true) {
526
                    $mail->smtpClose();
527
                    $return = 1;
528
                } else {
529
                    $return = 0;
530
                }
531
            } else {
532
                if ($mail->smtpConnect()) {
533
                    $mail->smtpClose();
534
                    $return = 1;
535
                } else {
536
                    $return = 0;
537
                }
538
            }
539
        } elseif ($request->input('sending_protocol') == 'mail') {
540
            $return = 1;
541
        }
542
543
        return $return;
0 ignored issues
show
Bug introduced by
The variable $return does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
544
    }
545
546
    /**
547
     * Checking if department value is null.
548
     *
549
     * @param type $dept
550
     *
551
     * @return type string or null
552
     */
553
    public function departmentValue($dept)
554
    {
555
        if ($dept) {
556
            $email_department = $dept;
557
        } else {
558
            $email_department = null;
559
        }
560
561
        return $email_department;
562
    }
563
564
    /**
565
     * Checking if priority value is null.
566
     *
567
     * @param type $priority
568
     *
569
     * @return type string or null
570
     */
571
    public function priorityValue($priority)
572
    {
573
        if ($priority) {
574
            $email_priority = $priority;
575
        } else {
576
            $email_priority = null;
577
        }
578
579
        return $email_priority;
580
    }
581
582
    /**
583
     * Checking if helptopic value is null.
584
     *
585
     * @param type $help_topic
586
     *
587
     * @return type string or null
588
     */
589
    public function helpTopicValue($help_topic)
590
    {
591
        if ($help_topic) {
592
            $email_help_topic = $help_topic;
593
        } else {
594
            $email_help_topic = null;
595
        }
596
597
        return $email_help_topic;
598
    }
599
600
    public function emailService($service, $value = [])
601
    {
602
        switch ($service) {
603
            case 'mailgun':
604
                $this->setServiceConfig($service, $value);
605
            case 'mandrill':
606
                $this->setServiceConfig($service, $value);
607
            case 'ses':
608
                $this->setServiceConfig($service, $value);
609
        }
610
    }
611
612
    public function setServiceConfig($service, $value)
613
    {
614
        //dd($service);
615
        if (count($value) > 0) {
616
            foreach ($value as $k => $v) {
617
                \Config::set("services.$service.$k", $v);
618
            }
619
        }
620
    }
621
622
    public function saveMailService($emailid, $request, $driver)
623
    {
624
        $mail_service = new \App\Model\MailJob\FaveoMail();
625
        $mails = $mail_service->where('email_id', $emailid)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\MailJob\FaveoMail>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
626
        if (count($request) > 0) {
627
            foreach ($mails as $mail) {
628
                $mail->delete();
629
            }
630
            foreach ($request as $key => $value) {
631
                $mail_service->create([
632
                    'drive'    => $driver,
633
                    'key'      => $key,
634
                    'value'    => $value,
635
                    'email_id' => $emailid,
636
                ]);
637
            }
638
        }
639
    }
640
641
    public function readMails()
642
    {
643
        $PhpMailController = new \App\Http\Controllers\Common\PhpMailController();
644
        $NotificationController = new \App\Http\Controllers\Common\NotificationController();
645
        $TicketController = new \App\Http\Controllers\Agent\helpdesk\TicketController($PhpMailController, $NotificationController);
646
        $TicketWorkflowController = new \App\Http\Controllers\Agent\helpdesk\TicketWorkflowController($TicketController);
647
        $controller = new \App\Http\Controllers\Agent\helpdesk\MailController($TicketWorkflowController);
648
        $emails = new Emails();
649
        $settings_email = new Email();
650
        $system = new \App\Model\helpdesk\Settings\System();
651
        $ticket = new \App\Model\helpdesk\Settings\Ticket();
652
        $controller->readmails($emails, $settings_email, $system, $ticket);
653
    }
654
655 View Code Duplication
    public function fetch($email)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
656
    {
657
        $PhpMailController = new \App\Http\Controllers\Common\PhpMailController();
658
        $NotificationController = new \App\Http\Controllers\Common\NotificationController();
659
        $TicketController = new \App\Http\Controllers\Agent\helpdesk\TicketController($PhpMailController, $NotificationController);
660
        $TicketWorkflowController = new \App\Http\Controllers\Agent\helpdesk\TicketWorkflowController($TicketController);
661
        $controller = new \App\Http\Controllers\Agent\helpdesk\MailController($TicketWorkflowController);
662
        $controller->fetch($email);
663
    }
664
}
665