Passed
Push — 2.x ( 3b4be6...b1b8b2 )
by Terry
01:55
created

Ajax::_test_mailgun()   B

Complexity

Conditions 9
Paths 5

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 18
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 31
rs 8.0555
1
<?php
2
/*
3
 * This file is part of the Shieldon package.
4
 *
5
 * (c) Terry L. <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
declare(strict_types=1);
12
13
namespace Shieldon\Firewall\Panel;
14
15
use Psr\Http\Message\ResponseInterface;
16
use Shieldon\Firewall\Panel\BaseController;
17
use Shieldon\Messenger as Messenger;
18
use function Shieldon\Firewall\__;
19
use function Shieldon\Firewall\get_request;
20
use function Shieldon\Firewall\get_response;
21
use function Shieldon\Firewall\get_session;
22
use function Shieldon\Firewall\set_request;
23
use function explode;
24
use function filter_var;
25
use function gethostname;
26
use function is_numeric;
27
use function json_encode;
28
use function str_replace;
29
30
/**
31
 * User
32
 */
33
class Ajax extends BaseController
34
{
35
    /**
36
     * Constructor.
37
     */
38
    public function __construct() 
39
    {
40
        parent::__construct();
41
    }
42
43
    /**
44
     * Fallback for undefined methods.
45
     *
46
     * @param string $function The method name.
47
     * @param array  $args     The arguments.
48
     *
49
     * @return bool
50
     */
51
    public function  __call($function , $args)
52
    {
53
        return false;
54
    }
55
56
    /**
57
     * Change the user's language of the UI.
58
     *
59
     * @return \Psr\Http\Message\ResponseInterface
60
     */
61
    public function changeLocale(): ResponseInterface
62
    {
63
        $langCode = get_request()->getQueryParams()['langCode'] ?? 'en';
64
        get_session()->set('shieldon_panel_lang', $langCode);
65
66
        $data['status'] = 'success';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
67
        $data['lang_code'] = $langCode;
68
        $data['session_lang_code'] = $langCode;
69
 
70
        $output = json_encode($data);
71
72
        return $this->respondJson($output);
73
    }
74
75
76
    /**
77
     * Test messenger modules.
78
     *
79
     * @return \Psr\Http\Message\ResponseInterface
80
     */
81
    public function tryMessenger(): ResponseInterface
82
    {
83
        $request = get_request();
84
85
        $getParams = $request->getQueryParams();
86
        $serverParams = $request->getServerParams();
87
88
        $serverName = $serverParams['SERVER_NAME'] ?? gethostname();
89
        $moduleName = $getParams['module'] ?? '';
90
        $moduleName = str_replace('-', '_', $moduleName);
91
92
        $data = [];
93
        $data['status'] = 'undefined';
94
        $data['result']['moduleName'] = $moduleName;
95
96
        $message['title'] = __('panel', 'test_msg_title', 'Testing Message from Host: ') . $serverName;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$message was never initialized. Although not strictly required by PHP, it is generally a good practice to add $message = array(); before regardless.
Loading history...
97
        $message['body'] = __('panel', 'test_msg_body', 'Messenger module "{0}" has been tested and confirmed successfully.', [$moduleName]);
98
    
99
        // @codeCoverageIgnoreStart
100
101
        // Name the testing method.
102
        $method = '_test_' . $moduleName;
103
104
        // Call testing method if exists.
105
        if ($this->{$method}($getParams, $message)) {
106
            $data['status'] = 'success';
107
        }
108
109
        $postParams = $request->getParsedBody();
110
        $postKey = 'messengers__' . $moduleName . '__confirm_test';
111
112
        if ('success' === $data['status']) {
113
            $postParams[$postKey] = 'on';
114
            $this->saveConfig();
115
        } elseif ('error' === $data['status']) {
116
            $postParams[$postKey] = 'off';
117
            $this->saveConfig();
118
        }
119
120
        set_request($request->withParsedBody($postParams));
121
122
        // @codeCoverageIgnoreStart
123
124
        $data['result']['postKey'] = $postKey;
125
126
        $output = json_encode($data);
127
128
        return $this->respondJson($output);
129
    }
130
131
    // @codeCoverageIgnoreStart
132
133
    /**
134
     * Test Telegram.
135
     *
136
     * @param array $getParams The GET params passed from tryMessenger method.
137
     * @param array $message   The message title and body.
138
     *
139
     * @return bool
140
     */
141
    private function _test_telegram($getParams, $message)
142
    {
143
        $apiKey = $getParams['apiKey'] ?? '';
144
        $channel = $getParams['channel'] ?? '';
145
        if (!empty($apiKey) && !empty($channel)) {
146
            $messenger = new Messenger\Telegram($apiKey, $channel);
147
            if ($messenger->send($message['body'])) {
148
                return true;
149
            }
150
        }
151
        return false;
152
    }
153
154
    /**
155
     * Test Line Notify.
156
     *
157
     * @param array $getParams The GET params passed from tryMessenger method.
158
     * @param array $message   The message title and body.
159
     *
160
     * @return bool
161
     */
162
    private function _test_line_notify($getParams, $message)
163
    {
164
        $accessToken = $getParams['accessToken'] ?? '';
165
        if (!empty($accessToken)) {
166
            $messenger = new Messenger\LineNotify($accessToken);
167
            if ($messenger->send($message['body'])) {
168
                return true;
169
            }
170
        }
171
        return false;
172
    }
173
174
    /**
175
     * Test Slack.
176
     *
177
     * @param array $getParams The GET params passed from tryMessenger method.
178
     * @param array $message   The message title and body.
179
     *
180
     * @return bool
181
     */
182
    private function _test_slack($getParams, $message)
183
    {
184
        $botToken = $getParams['botToken'] ?? '';
185
        $channel = $getParams['channel'] ?? '';
186
        if (!empty($botToken) && !empty($channel)) {
187
            $messenger = new Messenger\Slack($botToken, $channel);
188
            if ($messenger->send($message['body'])) {
189
                return true;
190
            }
191
        }
192
        return false;
193
    }
194
195
    /**
196
     * Test Slack WebHook.
197
     *
198
     * @param array $getParams The GET params passed from tryMessenger method.
199
     * @param array $message   The message title and body.
200
     *
201
     * @return bool
202
     */
203
    private function _test_slack_webhook($getParams, $message)
204
    {
205
        $webhookUrl = $getParams['webhookUrl'] ?? '';
206
        if (!empty($webhookUrl)) {
207
            $messenger = new Messenger\SlackWebhook($webhookUrl);
208
            if ($messenger->send($message['body'])) {
209
                return true;
210
            }
211
        }
212
        return false;
213
    }
214
215
    /**
216
     * Test Rocket Chat.
217
     *
218
     * @param array $getParams The GET params passed from tryMessenger method.
219
     * @param array $message   The message title and body.
220
     *
221
     * @return bool
222
     */
223
    private function _test_rocket_chat($getParams, $message)
224
    {
225
        $serverUrl = $getParams['serverUrl'] ?? '';
226
        $userId = $getParams['userId'] ?? '';
227
        $accessToken = $getParams['accessToken'] ?? '';
228
        $channel = $getParams['channel'] ?? '';
229
230
        if (
231
            !empty($serverUrl) &&
232
            !empty($userId) &&
233
            !empty($accessToken) &&
234
            !empty($channel)
235
        ) {
236
            $messenger = new Messenger\RocketChat($accessToken, $userId, $serverUrl, $channel);
237
            if ($messenger->send($message['body'])) {
238
                return true;
239
            }
240
        }
241
        return false;
242
    }
243
244
    /**
245
     * Test SMTP.
246
     *
247
     * @param array $getParams The GET params passed from tryMessenger method.
248
     * @param array $message   The message title and body.
249
     *
250
     * @return bool
251
     */
252
    private function _test_smtp($getParams, $message)
253
    {
254
        $type = $getParams['type'] ?? '';
255
        $host = $getParams['host'] ?? '';
256
        $user = $getParams['user'] ?? '';
257
        $pass = $getParams['pass'] ?? '';
258
        $port = $getParams['port'] ?? '';
259
260
        $sender = $getParams['sender'] ?? '';
261
        $recipients = $getParams['recipients'] ?? '';
262
263
        if (
264
            (
265
                !filter_var($host, FILTER_VALIDATE_IP) && 
266
                !filter_var($host, FILTER_VALIDATE_DOMAIN)
267
            ) || 
268
            !is_numeric($port) || 
269
            empty($user) || 
270
            empty($pass) 
271
        ) {
272
            $data['result']['message'] = 'Invalid fields.';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
273
            $output = json_encode($data);
274
            return $this->respondJson($output);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->respondJson($output) returns the type Psr\Http\Message\ResponseInterface which is incompatible with the documented return type boolean.
Loading history...
275
        }
276
277
        if ('ssl' === $type || 'tls' === $type) {
278
            $host = $type . '://' . $host;
279
        }
280
281
        if (!empty($sender) && $recipients) {
282
            $recipients = str_replace("\r", '|', $recipients);
283
            $recipients = str_replace("\n", '|', $recipients);
284
            $recipients = explode('|', $recipients);
285
286
            $messenger = new Messenger\Smtp($user, $pass, $host, (int) $port);
287
288
            foreach($recipients as $recipient) {
289
                if (filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
290
                    $messenger->addRecipient($recipient);
291
                }
292
            }
293
294
            if (filter_var($sender, FILTER_VALIDATE_EMAIL)) {
295
                $messenger->addSender($sender);
296
            }
297
298
            $messenger->setSubject($message['title']);
299
300
            if ($messenger->send($message['body'])) {
301
                return true;
302
            }
303
        }
304
        return false;
305
    }
306
307
    /**
308
     * Test Native PHP mail.
309
     *
310
     * @param array $getParams The GET params passed from tryMessenger method.
311
     * @param array $message   The message title and body.
312
     *
313
     * @return bool
314
     */
315
    private function _test_native_php_mail($getParams, $message)
316
    {
317
        $sender = $getParams['sender'] ?? '';
318
        $recipients = $getParams['recipients'] ?? '';
319
320
        if (!empty($sender) && !empty($recipients)) {
321
            $recipients = str_replace("\r", '|', $recipients);
322
            $recipients = str_replace("\n", '|', $recipients);
323
            $recipients = explode('|', $recipients);
324
325
            $messenger = new Messenger\Mail();
326
327
            foreach($recipients as $recipient) {
328
                if (filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
329
                    $messenger->addRecipient($recipient);
330
                }
331
            }
332
333
            if (filter_var($sender, FILTER_VALIDATE_EMAIL)) {
334
                $messenger->addSender($sender);
335
            }
336
337
            $messenger->setSubject($message['title']);
338
339
            if ($messenger->send($message['body'])) {
340
                return true;
341
            }
342
        }
343
        return false;
344
    }
345
346
    /**
347
     * Test Sendgrid.
348
     *
349
     * @param array $getParams The GET params passed from tryMessenger method.
350
     * @param array $message   The message title and body.
351
     *
352
     * @return bool
353
     */
354
    private function _test_sendgrid($getParams, $message)
355
    {
356
        $apiKey = $getParams['apiKey'] ?? '';
357
        $sender = $getParams['sender'] ?? '';
358
        $recipients = $getParams['recipients'] ?? '';
359
360
        if (!empty($sender) && !empty($recipients) && !empty($apiKey)) {
361
            $recipients = str_replace("\r", '|', $recipients);
362
            $recipients = str_replace("\n", '|', $recipients);
363
            $recipients = explode('|', $recipients);
364
365
            $messenger = new Messenger\Sendgrid($apiKey);
366
367
            foreach($recipients as $recipient) {
368
                if (filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
369
                    $messenger->addRecipient($recipient);
370
                }
371
            }
372
373
            if (filter_var($sender, FILTER_VALIDATE_EMAIL)) {
374
                $messenger->addSender($sender);
375
            }
376
377
            $messenger->setSubject($message['title']);
378
379
            if ($messenger->send($message['body'])) {
380
                return true;
381
            }
382
        }
383
        return false;
384
    }
385
386
    /**
387
     * Test Mailgun.
388
     *
389
     * @param array $getParams The GET params passed from tryMessenger method.
390
     * @param array $message   The message title and body.
391
     *
392
     * @return bool
393
     */
394
    private function _test_mailgun($getParams, $message)
395
    {
396
        $apiKey = $getParams['apiKey'] ?? '';
397
        $domain = $getParams['domain'] ?? '';
398
        $sender = $getParams['sender'] ?? '';
399
        $recipients = $getParams['recipients'] ?? '';
400
401
        if (!empty($sender) && !empty($recipients) && !empty($apiKey) && !empty($domain)) {
402
            $recipients = str_replace("\r", '|', $recipients);
403
            $recipients = str_replace("\n", '|', $recipients);
404
            $recipients = explode('|', $recipients);
405
406
            $messenger = new Messenger\Mailgun($apiKey, $domain);
407
408
            foreach($recipients as $recipient) {
409
                if (filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
410
                    $messenger->addRecipient($recipient);
411
                }
412
            }
413
414
            if (filter_var($sender, FILTER_VALIDATE_EMAIL)) {
415
                $messenger->addSender($sender);
416
            }
417
418
            $messenger->setSubject($message['title']);
419
420
            if ($messenger->send($message['body'])) {
421
                return true;
422
            }
423
        }
424
        return false;
425
    }
426
427
    // @codeCoverageIgnoreEnd
428
429
    /**
430
     * Respond the JSON format result.
431
     * 
432
     * @param string $output The string you want to output to the browser.
433
     *
434
     * @return \Psr\Http\Message\ResponseInterface
435
     */
436
    private function respondJson($output): ResponseInterface
437
    {
438
        $response = get_response();
439
440
        $stream = $response->getBody();
441
        $stream->write($output);
442
        $stream->rewind();
443
444
        $response = $response->withHeader('Content-Type', 'application/json');
445
        $response = $response->withAddedHeader('Content-Type', 'charset=utf-8');
446
        $response = $response->withBody($stream);
447
448
        return $response;
449
    }
450
}
451
452