MailHandler::execute()   F
last analyzed

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 223
Code Lines 165

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 36
eloc 165
c 2
b 0
f 0
nc 1646412
nop 0
dl 0
loc 223
rs 0

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 declare(strict_types=1);
2
3
4
namespace XoopsModules\Wgevents;
5
6
/*
7
 You may not change or alter any portion of this comment or credits
8
 of supporting developers from this source code or any supporting source code
9
 which is considered copyrighted (c) material of the original comment or credit authors.
10
11
 This program is distributed in the hope that it will be useful,
12
 but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
*/
15
16
/**
17
 * wgEvents module for xoops
18
 *
19
 * @copyright    2021 XOOPS Project (https://xoops.org)
20
 * @license      GPL 2.0 or later
21
 * @package      wgevents
22
 * @since        1.0.0
23
 * @min_xoops    2.5.11 Beta1
24
 * @author       Goffy - Wedega - Email:[email protected] - Website:https://xoops.wedega.com
25
 */
26
27
use XoopsModules\Wgevents\{
28
    Helper,
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModules\Wgevents\Helper. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
29
    Constants
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModules\Wgevents\Constants. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
30
};
31
32
/**
33
 * Class Object Handler Mails
34
 */
35
class MailHandler
36
{
37
    /**
38
     * @var array
39
     */
40
    public $mailParams = [];
41
42
    /**
43
     * @var int
44
     */
45
    public $type = 0;
46
47
    /**
48
     * @var bool
49
     */
50
    public $isHtml = false;
51
52
    /**
53
     * @var bool
54
     */
55
    public $isCron = false;
56
    
57
    /**
58
     * Constructor
59
     *
60
     */
61
    public function __construct()
62
    {
63
    }
64
65
    /**
66
     * @param $value
67
     * @return void
68
     */
69
    public function setParams($value)
70
    {
71
        $this->mailParams = $value;
72
    }
73
74
    /**
75
     * @param $value
76
     * @return void
77
     */
78
    public function setType($value)
79
    {
80
        $this->type = $value;
81
    }
82
83
    /**
84
     * @param $value
85
     * @return void
86
     */
87
    public function setHtml($value)
88
    {
89
        $this->isHtml = $value;
90
    }
91
92
    /**
93
     * Function to send mails for new/update registrations
94
     * 
95
     * @return int
96
     */
97
    public function execute()
98
    {
99
        $helper = Helper::getInstance();
100
        $accountHandler = $helper->getHandler('Account');
101
        $useLogs = $helper->getConfig('use_logs') > Constants::LOG_NONE;
102
        if ($useLogs) {
103
            $logHandler = $helper->getHandler('Log');
104
        }
105
        $logInfo = '<br>Task ID: ' . $this->mailParams['taskId'];
106
107
        $errorCode = 0;
108
109
        $eventLink      = '';
110
        $eventUrl       = \WGEVENTS_URL . '/event.php?op=show&id=' . $this->mailParams['evId'];
111
        $eventName      = $this->getCleanParam('evName');
112
        $eventDate      = \formatTimestamp($this->mailParams['evDatefrom'], 'm');
113
        $eventLocation  = $this->getCleanParam('evLocation');
114
        $senderMail     = $this->getCleanParam('evRegister_sendermail');
115
        $senderName     = $this->getCleanParam('evRegister_sendername');
116
        $senderSignatur = $this->getCleanParam('evRegister_signature');
117
        $firstname      = $this->getCleanParam('regFirstname');
118
        $lastname       = $this->getCleanParam('regLastname');
119
        $infotext       = $this->getCleanParam('infotext');
120
        $mailBody       = $this->getCleanParam('mailBody');
121
        $recipients     = $this->mailParams['recipients'];
122
        $userName       = $GLOBALS['xoopsConfig']['anonymous'];
123
        if (\is_object($GLOBALS['xoopsUser'])) {
124
            $userName  = ('' !== (string)$GLOBALS['xoopsUser']->name()) ? $GLOBALS['xoopsUser']->name() : $GLOBALS['xoopsUser']->uname();
125
        }
126
127
        switch ($this->type) {
128
            case 0:
129
            default:
130
                return 0;
131
            case Constants::MAIL_REG_CONFIRM_OUT:
132
                $template = 'mail_reg_confirm_out.tpl';
133
                $subject = \_MA_WGEVENTS_MAIL_REG_OUT_SUBJECT;
134
                break;
135
            case Constants::MAIL_REG_NOTIFY_OUT:
136
                $template = 'mail_reg_notify_out.tpl';
137
                $subject = \_MA_WGEVENTS_MAIL_REG_OUT_SUBJECT;
138
                break;
139
            case Constants::MAIL_REG_CONFIRM_IN:
140
                $template = 'mail_reg_confirm_in.tpl';
141
                $subject = \_MA_WGEVENTS_MAIL_REG_IN_SUBJECT;
142
                break;
143
            case Constants::MAIL_REG_CONFIRM_MODIFY:
144
                $template = 'mail_reg_confirm_modify.tpl';
145
                $subject = \_MA_WGEVENTS_MAIL_REG_MODIFY_SUBJECT;
146
                break;
147
            case Constants::MAIL_REG_NOTIFY_IN:
148
                $template = 'mail_reg_notify_in.tpl';
149
                $subject = \_MA_WGEVENTS_MAIL_REG_IN_SUBJECT;
150
                break;
151
            case Constants::MAIL_REG_NOTIFY_MODIFY:
152
                $template = 'mail_reg_notify_modify.tpl';
153
                $subject = \_MA_WGEVENTS_MAIL_REG_MODIFY_SUBJECT;
154
                break;
155
            case Constants::MAIL_EVENT_NOTIFY_MODIFY:
156
                $template = 'mail_event_notify_modify.tpl';
157
                $subject = \_MA_WGEVENTS_MAIL_EVENT_NOTIFY_MODIFY_SUBJECT;
158
                break;
159
            case Constants::MAIL_EVENT_NOTIFY_ALL:
160
                $template = 'mail_event_notify_all.tpl';
161
                $subject = $this->mailParams['mailSubject'];
162
                break;
163
            case Constants::MAIL_REG_NOTIFY_CANCEL:
164
                $template = 'mail_reg_notify_cancel.tpl';
165
                $subject = \_MA_WGEVENTS_MAIL_EVENT_CANCEL_SUBJECT;
166
                break;
167
            case Constants::MAIL_REG_CONFIRM_CANCEL:
168
                $template = 'mail_reg_confirm_cancel.tpl';
169
                $subject = \_MA_WGEVENTS_MAIL_EVENT_CANCEL_SUBJECT;
170
                break;
171
        }
172
173
        // get settings of primary account
174
        $primaryAcc = $accountHandler->getPrimary();
175
        $account_type           = (int)$primaryAcc['type'];
176
        //$account_yourname       = (string)$primaryAcc['yourname'];
177
        $account_username       = (string)$primaryAcc['yourmail'];
178
        $account_password       = (string)$primaryAcc['password'];
179
        $account_server_out     = (string)$primaryAcc['server_out'];
180
        $account_port_out       = (int)$primaryAcc['port_out'];
181
        $account_securetype_out = (string)$primaryAcc['securetype_out'];
182
183
        // create info for log
184
        if ($useLogs) {
185
            switch ($account_type) {
186
                case '':
187
                default:
188
                    $accountTypeDesc = 'XOOPS system';
189
                    break;
190
                case Constants::ACCOUNT_TYPE_VAL_GMAIL:
191
                    $accountTypeDesc = 'gmail';
192
                    break;
193
                case Constants::ACCOUNT_TYPE_VAL_PHP_MAIL:
194
                    $accountTypeDesc = 'php mail';
195
                    break;
196
                case Constants::ACCOUNT_TYPE_VAL_PHP_SENDMAIL:
197
                    $accountTypeDesc = 'sendmail';
198
                    break;
199
                case Constants::ACCOUNT_TYPE_VAL_POP3:
200
                    $accountTypeDesc = 'pop3';
201
                    break;
202
                case Constants::ACCOUNT_TYPE_VAL_SMTP:
203
                    $accountTypeDesc = 'smtp';
204
                    break;
205
            }
206
            $logInfo .= '<br>Mailer: ' . $accountTypeDesc;
207
            $logInfo .= '<br>Template: ' . $template;
208
        }
209
210
        try {
211
            /*
212
            if ($account_type == Constants::ACCOUNT_TYPE_VAL_PHP_SENDMAIL) {
213
                $pop = new POP3();
214
                $pop->authorise($account_server_out, $account_port_out, 30, $account_username, $account_password, 1);
215
            }
216
            */
217
            $xoopsMailer = xoops_getMailer();
218
            $xoopsMailer->useMail();
219
            // check whether mail body contains any html tags
220
            if (\preg_match('/<\s?[^\>]*\/?\s?>/i', $mailBody)) {
221
                $this->isHtml = true;
222
                $logInfo .= '<br>Check isHtml: true';
223
                $eventLink = "<a href='" . $eventUrl . "' title='" . $eventUrl . "'>" . $eventName . '</a>';
224
            }
225
            $xoopsMailer->setHTML($this->isHtml);
226
            //set template path
227
            if (\file_exists(\WGEVENTS_PATH . '/language/' . $GLOBALS['xoopsConfig']['language'] . '/')) {
228
                $xoopsMailer->setTemplateDir(\WGEVENTS_PATH . '/language/' . $GLOBALS['xoopsConfig']['language'] . '/mail_template/');
229
            } else {
230
                $xoopsMailer->setTemplateDir(\WGEVENTS_PATH . '/language/english/mail_template/');
231
            }
232
            //set template name
233
            $xoopsMailer->setTemplate($template);
234
            $xoopsMailer->CharSet = _CHARSET; //use xoops default character set
0 ignored issues
show
Bug Best Practice introduced by
The property CharSet does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
235
            //set account settings
236
            if (Constants::ACCOUNT_TYPE_VAL_SMTP == $account_type
237
                || Constants::ACCOUNT_TYPE_VAL_GMAIL == $account_type) {
238
239
                $xoopsMailer->multimailer->isSMTP();
240
                $xoopsMailer->multimailer->Port       = $account_port_out; // set the SMTP port
241
                $xoopsMailer->multimailer->Host       = $account_server_out; //sometimes necessary to repeat
242
                $xoopsMailer->multimailer->SMTPAuth   = true;
243
                $xoopsMailer->multimailer->SMTPSecure = $account_securetype_out;
244
                $xoopsMailer->multimailer->Username   = $account_username; // SMTP account username
245
                $xoopsMailer->multimailer->Password   = $account_password; // SMTP account password
246
                $xoopsMailer->multimailer->SMTPDebug  = 0;
247
            }
248
            /* old version:
249
            if ('' != $account_securetype_out) {
250
                $xoopsMailer->SMTPAuth   = true;
251
                $xoopsMailer->SMTPSecure = $account_securetype_out; // sets the prefix to the server
252
            }
253
            */
254
255
            if (Constants::ACCOUNT_TYPE_VAL_SMTP == $account_type
256
                || Constants::ACCOUNT_TYPE_VAL_GMAIL == $account_type) {
257
                $xoopsMailer->Port = $account_port_out; // set the SMTP port
0 ignored issues
show
Bug introduced by
The property Port does not seem to exist on XoopsMailer.
Loading history...
Bug introduced by
The property Port does not seem to exist on XoopsMailerLocal.
Loading history...
258
                $xoopsMailer->Host = $account_server_out; //sometimes necessary to repeat
0 ignored issues
show
Bug introduced by
The property Host does not seem to exist on XoopsMailerLocal.
Loading history...
Bug introduced by
The property Host does not seem to exist on XoopsMailer.
Loading history...
259
            }
260
261
            if ('' !== $account_securetype_out) {
262
                $xoopsMailer->SMTPAuth   = true;
0 ignored issues
show
Bug introduced by
The property SMTPAuth does not seem to exist on XoopsMailerLocal.
Loading history...
Bug introduced by
The property SMTPAuth does not seem to exist on XoopsMailer.
Loading history...
263
                $xoopsMailer->SMTPSecure = $account_securetype_out; // sets the prefix to the server
0 ignored issues
show
Bug introduced by
The property SMTPSecure does not seem to exist on XoopsMailer.
Loading history...
Bug introduced by
The property SMTPSecure does not seem to exist on XoopsMailerLocal.
Loading history...
264
            }
265
266
            //set sender
267
            $xoopsMailer->setFromEmail($senderMail);
268
            //set sender name
269
            $xoopsMailer->setFromName($senderName);
270
            //set subject
271
            $xoopsMailer->setSubject($subject);
272
            //assign vars
273
            $xoopsMailer->assign('UNAME', $userName);
274
            $xoopsMailer->assign('NAME', \trim($firstname . ' ' . $lastname));
275
            $xoopsMailer->assign('EVENTNAME', $eventName);
276
            $xoopsMailer->assign('EVENTDATEFROM', $eventDate);
277
            $xoopsMailer->assign('EVENTLOCATION', $eventLocation);
278
            $xoopsMailer->assign('INFOTEXT', $infotext);
279
            if ('' !== $eventLink) {
280
                $xoopsMailer->assign('EVENTURL', $eventLink);
281
            } else {
282
                $xoopsMailer->assign('EVENTURL', $eventUrl);
283
            }
284
            $xoopsMailer->assign('BODY', $mailBody);
285
            $xoopsMailer->assign('SIGNATURE', $senderSignatur);
286
            //set recipient
287
            $xoopsMailer->setToEmails($recipients);
288
            //execute sending
289
            if ($xoopsMailer->send()) {
290
                if ($useLogs) {
291
                    $logHandler->createLog('Result MailHandler/executeReg: success' . $logInfo);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $logHandler does not seem to be defined for all execution paths leading up to this point.
Loading history...
292
                }
293
            } else {
294
                if ($useLogs) {
295
                    $logHandler->createLog('Result MailHandler/executeReg: failed' .$xoopsMailer->getErrors() . $logInfo);
296
                }
297
                $errMsg = $xoopsMailer->getErrors();
298
                // check for SMTP error 554 (maximum number of mails exceeded)
299
                $errIds = ['SMTP','554', 'error'];
300
                $arrMsg = \explode(' ', \preg_replace('/[^a-z0-9]/i',' ',$errMsg));
301
                $countMatches = \count(\array_intersect($arrMsg, $errIds));
302
                if ($countMatches > 0) {
303
                    $errorCode = 554;
304
                } else {
305
306
                    $errorCode = 900; // wgevents internal code for misc error
307
                }
308
            }
309
            $xoopsMailer->reset();
310
            unset($xoopsMailer);
311
        }
312
        catch (\Exception $e) {
313
            $errorCode = 999; // wgevents internal code for misc error
314
            if ($useLogs) {
315
                $logHandler->createLog('MailHandler/executeReg failed: Exception - ' . $e->getMessage());
316
            }
317
        }
318
319
        return $errorCode;
320
    }
321
322
    /**
323
     * Function to get clean mail parameter if exists
324
     *
325
     * @param string $name
326
     * @return string
327
     */
328
    private function getCleanParam($name) {
329
        $return = ' ';
330
        if (array_key_exists($name, $this->mailParams)) {
331
            $return  = '' === (string)$this->mailParams[$name] ? ' ' : $this->mailParams[$name];
332
        }
333
334
        return $return;
335
    }
336
337
    /**
338
     * Function to create mail parameters
339
     *
340
     * @param \XoopsObject $eventObj
341
     * @param int $regId
342
     * @return array
343
     */
344
    public function getMailParam($eventObj, $regId) {
345
        $helper = Helper::getInstance();
346
        $registrationHandler = $helper->getHandler('Registration');
347
        $registrationObj = $registrationHandler->get($regId);
348
349
        $mailParams = [];
350
        $mailParams['regIp']                 = $registrationObj->getVar('ip');
351
        $mailParams['regFirstname']          = $registrationObj->getVar('firstname');
352
        $mailParams['regLastname']           = $registrationObj->getVar('lastname');
353
        $mailParams['regEmail']              = $registrationObj->getVar('email');
354
        $mailParams['regSubmitter']          = $registrationObj->getVar('submitter');
355
        $mailParams['evId']                  = $eventObj->getVar('id');
356
        $mailParams['evSubmitter']           = $eventObj->getVar('submitter');
357
        $mailParams['evStatus']              = $eventObj->getVar('status');
358
        $mailParams['evName']                = $eventObj->getVar('name');
359
        $mailParams['evDatefrom']            = $eventObj->getVar('datefrom');
360
        $mailParams['evLocation']            = $this->replaceLinebreaks((string)$eventObj->getVar('location'), ', ');
361
        $mailParams['evRegister_sendermail'] = $eventObj->getVar('register_sendermail');
362
        $mailParams['evRegister_sendername'] = $eventObj->getVar('register_sendername');
363
        $mailParams['evRegister_signature']  = $eventObj->getVar('register_signature');
364
        $mailParams['infotext']              = '';
365
        $mailParams['taskId']                = 0;
366
367
        return $mailParams;
368
    }
369
370
    /**
371
    * Function to create a table of modifications
372
     *
373
     * @param array $changedValues
374
     * @return string
375
     */
376
    public function array2table ($changedValues) {
377
        // create object
378
        $xoopsTpl = new \XoopsTpl;
379
        // assign array
380
        $xoopsTpl->assign('changedValues', $changedValues);
381
        // display it
382
        return $xoopsTpl->fetch('db:wgevents_mail_table.tpl');
383
    }
384
385
    /**
386
     * Function to replace line breaks
387
     *
388
     * @param string $string
389
     * @param string $replaceBy
390
     * @return string
391
     */
392
    public function replaceLinebreaks($string, $replaceBy) {
393
394
        // replace
395
        return str_replace(["\r\n", "\r", "\n", '<br />', '<br>'], $replaceBy, $string);
396
397
    }
398
}
399