task.inc.php ➔ xnewsletter_createTasks()   F
last analyzed

Complexity

Conditions 22
Paths 1632

Size

Total Lines 120

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
nc 1632
nop 4
dl 0
loc 120
rs 0
c 0
b 0
f 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
2
/**
3
 * ****************************************************************************
4
 *  - A Project by Developers TEAM For Xoops - ( https://xoops.org )
5
 * ****************************************************************************
6
 *  XNEWSLETTER - MODULE FOR XOOPS
7
 *  Copyright (c) 2007 - 2012
8
 *  Goffy ( wedega.com )
9
 *
10
 *  You may not change or alter any portion of this comment or credits
11
 *  of supporting developers from this source code or any supporting
12
 *  source code which is considered copyrighted (c) material of the
13
 *  original comment or credit authors.
14
 *
15
 *  This program is distributed in the hope that it will be useful,
16
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 *  GNU General Public License for more details.
19
 *  ---------------------------------------------------------------------------
20
 * @copyright  Goffy ( wedega.com )
21
 * @license    GPL 2.0
22
 * @package    xnewsletter
23
 * @author     Goffy ( [email protected] )
24
 *
25
 * ****************************************************************************
26
 */
27
28
use XoopsModules\Xnewsletter;
29
30
// defined("XOOPS_ROOT_PATH") || die("XOOPS root path not defined");
31
require_once __DIR__ . '/common.php';
32
33
/**
34
 * @param $op
35
 * @param $letter_id
36
 * @param $xn_send_in_packages
37
 * @param $xn_send_in_packages_time
38
 *
39
 * @return null|bool
40
 */
41
function xnewsletter_createTasks($op, $letter_id, $xn_send_in_packages, $xn_send_in_packages_time)
42
{
43
    global $xoopsUser, $xoopsDB;
44
    $helper = Xnewsletter\Helper::getInstance();
45
46
    $uid = (is_object($xoopsUser) && isset($xoopsUser)) ? $xoopsUser->uid() : 0;
47
48
    // check data before creating task list
49
    if (0 == $letter_id) {
50
        redirect_header('letter.php', 3, _AM_XNEWSLETTER_SEND_ERROR_NO_LETTERID);
51
    }
52
    $letterObj = $helper->getHandler('Letter')->get($letter_id);
53
    if (0 == count($letterObj)) {
54
        redirect_header('letter.php', 3, _AM_XNEWSLETTER_SEND_ERROR_NO_LETTERID);
55
    }
56
57
    // read categories
58
    $letter_cats = $letterObj->getVar('letter_cats');
59
    if ('' == $letter_cats) {
60
        // no cats
61
        redirect_header('letter.php', 3, _MA_XNEWSLETTER_LETTER_NONEAVAIL);
62
    }
63
64
    if ('send_test' === $op) {
65
        //check for valid email for testing
66
        $letter_email_test = $letterObj->getVar('letter_email_test');
67
        if ('' == $letter_email_test) {
68
            redirect_header('letter.php', 3, _AM_XNEWSLETTER_SEND_ERROR_NO_EMAIL);
69
        }
70
    }
71
72
    // get emails of subscribers
73
    $recipients = [];
74
    if ('send_test' === $op) {
75
        $recipients[] = 0;
76
    } else {
77
        // read all subscribers
78
        $sql = 'SELECT subscr_id, subscr_actkey ';
79
        $sql .= " FROM {$xoopsDB->prefix('xnewsletter_subscr')} INNER JOIN {$xoopsDB->prefix('xnewsletter_catsubscr')} ON subscr_id = catsubscr_subscrid ";
80
        $sql .= ' WHERE subscr_activated=1 AND (((catsubscr_catid) IN (';
81
        $sql .= str_replace('|', ',', $letter_cats);
82
        $sql .= '))) GROUP BY subscr_id;';
83
84
        if (!$subscrs = $xoopsDB->query($sql)) {
85
            die();
86
        }
87
88
        while (false !== ($subscr = $xoopsDB->fetchArray($subscrs))) {
89
            $subscr_id = $subscr['subscr_id'];
90
            if ('resend_letter' === $op) {
91
                // read subscribers, where send failed
92
                $protocolCriteria = new \CriteriaCompo();
93
                $protocolCriteria->add(new \Criteria('protocol_letter_id', $letter_id));
94
                $protocolCriteria->add(new \Criteria('protocol_subscriber_id', $subscr_id));
95
                $protocolCriteria->add(new \Criteria('protocol_success', true));
96
                $protocolsCriteria = $helper->getHandler('Protocol')->getCount($protocolCriteria);
97
                if ($protocolsCriteria > 0) {
98
                    $subscr_id = 0;
99
                } // letter already successfully sent
100
            }
101
            if ($subscr_id > 0) {
102
                if ('' == $subscr['subscr_actkey']) {
103
                    $subscrObj               = $helper->getHandler('Subscr')->get($subscr_id);
104
                    $subscr['subscr_actkey'] = xoops_makepass();
105
                    $subscrObj->setVar('subscr_actkey', $subscr['subscr_actkey']);
106
                    $helper->getHandler('Subscr')->insert($subscrObj);
107
                    unset($subscrObj);
108
                }
109
                $recipients[] = $subscr['subscr_id'];
110
            }
111
        }
112
    }
113
114
    if (0 == count($recipients)) {
115
        redirect_header('letter.php', 3, _AM_XNEWSLETTER_SEND_ERROR_NO_SUBSCR);
116
    } else {
117
        // creating task list
118
        $counter        = 0;
119
        $task_starttime = time() - 1;
120
        foreach ($recipients as $subscr_id) {
121
            // calculate start time, if letter should be sent in packages
122
            if ($xn_send_in_packages > 0) {
123
                if ($counter == $xn_send_in_packages) {
124
                    $task_starttime = $task_starttime + 60 * $xn_send_in_packages_time;
125
                    $counter        = 0;
126
                }
127
            }
128
            ++$counter;
129
            // create task list item
130
            $sql = "INSERT INTO `{$xoopsDB->prefix('xnewsletter_task')}`";
131
            $sql .= ' (`task_letter_id`, `task_subscr_id`,  `task_starttime`, `task_submitter`, `task_created` )';
132
            $sql .= " VALUES ({$letter_id}, {$subscr_id}, {$task_starttime}, {$uid}, " . time() . ')';
133
            if (!$xoopsDB->queryF($sql)) {
134
                $protocolObj = $helper->getHandler('Protocol')->create();
135
                $protocolObj->setVar('protocol_letter_id', $letter_id);
136
                $protocolObj->setVar('protocol_subscriber_id', $subscr_id);
137
                $protocolObj->setVar('protocol_status', _AM_XNEWSLETTER_TASK_ERROR_CREATE);
138
                $protocolObj->setVar('protocol_status_str_id', _XNEWSLETTER_PROTOCOL_STATUS_ERROR_CREATE_TASK);
139
                $protocolObj->setVar('protocol_status_vars', []);
140
                $protocolObj->setVar('protocol_success', false);
141
                $protocolObj->setVar('protocol_submitter', $uid);
142
                $protocolObj->setVar('protocol_created', time());
143
                if (!$helper->getHandler('Protocol')->insert($protocolObj)) {
144
                    echo $protocolObj->getHtmlErrors();
145
                }
146
                unset($protocolObj);
147
148
                return false;
149
            } elseif ('send_test' !== $op) {
150
                // update letter
151
                $letterObj = $helper->getHandler('Letter')->get($letter_id);
152
                $letterObj->setVar('letter_sender', $uid);
153
                $letterObj->setVar('letter_sent', time());
154
                $helper->getHandler('Letter')->insert($letterObj);
155
            }
156
        }
157
    }
158
159
    return true;
160
}
161
162
/**
163
 * @param     $xn_send_in_packages
164
 * @param int $letter_id
165
 *
166
 * @param int $cron
167
 * @return mixed|string
168
 */
169
function xnewsletter_executeTasks($xn_send_in_packages, $letter_id = 0, $cron = 0)
170
{
171
    require_once XOOPS_ROOT_PATH . '/modules/xnewsletter/include/functions.php';
172
//    require_once XNEWSLETTER_ROOT_PATH . '/class/class.xnewslettermailer.php';
173
174
    global $XoopsTpl, $xoopsDB, $xoopsUser;
175
    $helper = Xnewsletter\Helper::getInstance();
176
177
    //get letters ready to send groups by letter_id
178
    $sql = "SELECT `task_letter_id` FROM {$xoopsDB->prefix('xnewsletter_task')}";
179
    if ($letter_id > 0) {
180
        $sql .= " WHERE (`task_letter_id`={$letter_id})";
181
    }
182
    $sql .= ' GROUP BY `task_letter_id`';
183
    $task_letters = $xoopsDB->query($sql);
184
    if ($xoopsDB->getRowsNum($task_letters) == 0) {
185
        return _AM_XNEWSLETTER_SEND_ERROR_NO_LETTERID;
186
    }
187
188 View Code Duplication
    if (!isset($xoopsTpl) || !is_object($xoopsTpl)) {
0 ignored issues
show
Bug introduced by
The variable $xoopsTpl seems only to be defined at a later point. As such the call to isset() seems to always evaluate to false.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
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...
189
        require_once XOOPS_ROOT_PATH . '/class/template.php';
190
        $xoopsTpl = new \XoopsTpl();
0 ignored issues
show
Unused Code introduced by
$xoopsTpl 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...
191
    }
192
193
    // get once template path
194
    $template_path = XNEWSLETTER_ROOT_PATH . '/language/' . $GLOBALS['xoopsConfig']['language'] . '/templates/';
195
    if (!is_dir($template_path)) {
196
        $template_path = XNEWSLETTER_ROOT_PATH . '/language/english/templates/';
197
    }
198
    if (!is_dir($template_path)) {
199
        return str_replace('%p', $template_path, _AM_XNEWSLETTER_SEND_ERROR_INALID_TEMPLATE_PATH);
200
    }
201
202
    $uid         = (is_object($xoopsUser) && isset($xoopsUser)) ? $xoopsUser->uid() : 0;
203
    $count_total = 0;
204
    $count_err   = 0;
205
206
    while (false !== ($task_letter = $xoopsDB->fetchArray($task_letters))) {
207
        $letter_id = $task_letter['task_letter_id'];
208
        $letterObj = $helper->getHandler('Letter')->get($letter_id);
209
        if (!is_object($letterObj)) {
210
            return _AM_XNEWSLETTER_SEND_ERROR_NO_LETTERID;
211
        }
212
        $letter_title = $letterObj->getVar('letter_title');
0 ignored issues
show
Unused Code introduced by
$letter_title 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...
213
        // read categories
214
        $letter_cats = $letterObj->getVar('letter_cats');
215
        if ('' == $letter_cats) {
216
            //no cats
217
            return _MA_XNEWSLETTER_LETTER_NONEAVAIL;
218
        }
219
220
        // read data of account
221
        $letter_account = $letterObj->getVar('letter_account');
222
        if ('' == $letter_account || 0 == $letter_account) {
223
            return _MA_XNEWSLETTER_ACCOUNTS_NONEAVAIL;
224
        }
225
        $accountObj             = $helper->getHandler('Accounts')->get($letter_account);
226
        $account_type           = $accountObj->getVar('accounts_type');
227
        $account_yourname       = $accountObj->getVar('accounts_yourname');
228
        $account_yourmail       = $accountObj->getVar('accounts_yourmail');
229
        $account_username       = $accountObj->getVar('accounts_username');
230
        $account_password       = $accountObj->getVar('accounts_password');
231
        $account_server_out     = $accountObj->getVar('accounts_server_out');
232
        $account_port_out       = $accountObj->getVar('accounts_port_out');
233
        $account_securetype_out = $accountObj->getVar('accounts_securetype_out');
234
235
        // create basic mail body
236
        $letter_title   = $letterObj->getVar('letter_title');
237
        $letter_content = $letterObj->getVar('letter_content', 'n');
238
239
        $letterTpl = new \XoopsTpl();
240
        // letter data
241
        $letterTpl->assign('content', $letter_content);
242
        $letterTpl->assign('title', $letter_title); // new from v1.3
243
        // letter attachments as link
244
        $attachmentAslinkCriteria = new \CriteriaCompo();
245
        $attachmentAslinkCriteria->add(new \Criteria('attachment_letter_id', $letter_id));
246
        $attachmentAslinkCriteria->add(new \Criteria('attachment_mode', _XNEWSLETTER_ATTACHMENTS_MODE_ASLINK));
247
        $attachmentAslinkCriteria->setSort('attachment_id');
248
        $attachmentAslinkCriteria->setOrder('ASC');
249
        $attachmentObjs = $helper->getHandler('Attachment')->getObjects($attachmentAslinkCriteria, true);
250 View Code Duplication
        foreach ($attachmentObjs as $attachment_id => $attachmentObj) {
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...
251
            $attachment_array                    = $attachmentObj->toArray();
252
            $attachment_array['attachment_url']  = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
253
            $attachment_array['attachment_link'] = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
254
            $letterTpl->append('attachments', $attachment_array);
255
        }
256
        // extra data
257
        $letterTpl->assign('date', time()); // new from v1.3
258
        $letterTpl->assign('xoops_url', XOOPS_URL); // new from v1.3
259
        $letterTpl->assign('xoops_langcode', _LANGCODE); // new from v1.3
260
        $letterTpl->assign('xoops_charset', _CHARSET); // new from v1.3
261
262
        // get emails of subscribers
263
        $recipients   = [];
0 ignored issues
show
Unused Code introduced by
$recipients 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...
264
        $sql_tasklist = "SELECT `task_id`, `task_subscr_id` FROM {$xoopsDB->prefix('xnewsletter_task')}";
265
        $sql_tasklist .= " WHERE ((`task_letter_id`= {$letter_id}) AND (`task_starttime` < " . time() . '))';
266
        if (!$task_letters = $xoopsDB->query($sql_tasklist)) {
267
            return $task_letters->getErrors();
268
        }
269
        $recipients = [];
270
        while (false !== ($task_letter = $xoopsDB->fetchArray($task_letters))) {
271
            $subscr_id = $task_letter['task_subscr_id'];
272
            $task_id   = $task_letter['task_id'];
273
            if (0 == $subscr_id) {
274
                $recipients[] = [
275
                    'task_id'           => $task_id,
276
                    'address'           => $letterObj->getVar('letter_email_test'),
277
                    'firstname'         => _AM_XNEWSLETTER_SUBSCR_FIRSTNAME_PREVIEW,
278
                    'lastname'          => _AM_XNEWSLETTER_SUBSCR_LASTNAME_PREVIEW,
279
                    'subscr_sex'        => _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW,
280
                    'subscriber_id'     => '0',
281
                    'catsubscr_id'      => '0',
282
                    'subscriber_actkey' => 'Test',
283
                ];
284
            } else {
285
                $sql_subscr = "SELECT * FROM {$xoopsDB->prefix('xnewsletter_subscr')}";
286
                $sql_subscr .= " WHERE `subscr_id`= {$subscr_id}";
287
                if (!$task_subscrs = $xoopsDB->query($sql_subscr)) {
288
                    return $task_subscrs->getErrors();
289
                }
290
291
                $subscr       = $xoopsDB->fetchArray($task_subscrs);
292
                $recipients[] = [
293
                    'task_id'           => $task_id,
294
                    'address'           => $subscr['subscr_email'],
295
                    'firstname'         => $subscr['subscr_firstname'],
296
                    'lastname'          => $subscr['subscr_lastname'],
297
                    'subscr_sex'        => $subscr['subscr_sex'],
298
                    'subscriber_id'     => $subscr['subscr_id'],
299
                    'subscriber_actkey' => $subscr['subscr_actkey'],
300
                ];
301
            }
302
            if ($xn_send_in_packages > 0 && count($recipients) == $xn_send_in_packages) {
303
                break;
304
            }
305
        }
306
307
        if (0 == count($recipients)) {
308
            return null;
309
        }
310
311
        // get letter attachments as attachment
312
        $attachmentAsattachmentCriteria = new \CriteriaCompo();
313
        $attachmentAsattachmentCriteria->add(new \Criteria('attachment_letter_id', $letter_id));
314
        $attachmentAsattachmentCriteria->add(new \Criteria('attachment_mode', _XNEWSLETTER_ATTACHMENTS_MODE_ASATTACHMENT));
315
        $attachmentAsattachmentCriteria->setSort('attachment_id');
316
        $attachmentAsattachmentCriteria->setOrder('ASC');
317
        $attachmentObjs  = $helper->getHandler('Attachment')->getObjects($attachmentAsattachmentCriteria, true);
318
        $attachmentsPath = [];
319 View Code Duplication
        foreach ($attachmentObjs as $attachment_id => $attachmentObj) {
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...
320
            $attachmentsPath[] = XOOPS_UPLOAD_PATH . $helper->getConfig('xn_attachment_path') . $letter_id . '/' . $attachmentObj->getVar('attachment_name');
321
        }
322
323
        try {
324
            if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_PHP_SENDMAIL == $account_type) {
325
                $pop = new POP3();
326
                $pop->authorise($account_server_out, $account_port_out, 30, $account_username, $account_password, 1);
327
            }
328
329
            //$mail = new PHPMailer();
330
            $mail = new Xnewsletter\XnewsletterMailer();
331
332
            $mail->CharSet = _CHARSET; //use xoops default character set
333
334
            if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_PHP_SENDMAIL == $account_type) {
335
                //$mail->IsSendmail();  Fix Error
336
            }
337
338
            $mail->Username = $account_username; // SMTP account username
339
            $mail->Password = $account_password; // SMTP account password
340
341
            if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_POP3 == $account_type) {
342
                $mail->isSMTP();
343
                //$mail->SMTPDebug = 2;
344
                $mail->Host = $account_server_out;
345
            }
346
347 View Code Duplication
            if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_SMTP == $account_type
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...
348
                || _XNEWSLETTER_ACCOUNTS_TYPE_VAL_GMAIL == $account_type) {
349
                $mail->Port = $account_port_out; // set the SMTP port
350
                $mail->Host = $account_server_out; //sometimes necessary to repeat
351
            }
352
353
            if ('' != $account_securetype_out) {
354
                $mail->SMTPAuth   = true;
355
                $mail->SMTPSecure = $account_securetype_out; // sets the prefix to the server
356
            }
357
358
            $mail->setFrom($account_yourmail, $account_yourname);
359
            $mail->addReplyTo($account_yourmail, $account_yourname);
360
            $mail->Subject = html_entity_decode($letter_title, ENT_QUOTES);
361
362
            foreach ($recipients as $recipient) {
363
                $subscr_id = $recipient['subscriber_id'];
364
                // subscr data
365
                $letterTpl->assign('sex', $recipient['subscr_sex']);
366
                $letterTpl->assign('salutation', $recipient['subscr_sex']); // new from v1.3
367
                $letterTpl->assign('firstname', $recipient['firstname']);
368
                $letterTpl->assign('lastname', $recipient['lastname']);
369
                $letterTpl->assign('subscr_email', $recipient['address']);
370
                $letterTpl->assign('email', $recipient['address']); // new from v1.3
371
                // extra data
372
                $act           = [
373
                    XOOPS_URL,
374
                    'unsub',
375
                    $subscr_id,
376
                    $recipient['subscriber_actkey'],
377
                    $recipient['address'],
378
                ];
379
                $activationKey = base64_encode(implode('||', $act));
380
                $letterTpl->assign('unsubscribe_link', XOOPS_URL . "/modules/xnewsletter/subscription.php?op=unsub&email={$recipient['address']}&actkey={$activationKey}");
381
                $letterTpl->assign('unsubscribe_url', XOOPS_URL . "/modules/xnewsletter/subscription.php?op=unsub&email={$recipient['address']}&actkey={$activationKey}"); // new from v1.3
382
                //create different activationKey for listing subscriptions
383
                $act           = [
384
                    XOOPS_URL,
385
                    'list',
386
                    $subscr_id,
387
                    $recipient['subscriber_actkey'],
388
                    $recipient['address'],
389
                ];
390
                $activationKey = base64_encode(implode('||', $act));
391
                $letterTpl->assign('listsubscription_link', XOOPS_URL . "/modules/xnewsletter/subscription.php?op=anonlistsubscr&subscr_email={$recipient['address']}&actkey={$activationKey}");
392
393
                $templateObj = $helper->getHandler('Template')->get($letterObj->getVar('letter_templateid'));
394
                if (is_object($templateObj)) {
395
                    if ( (int)$templateObj->getVar('template_type') === _XNEWSLETTER_MAILINGLIST_TPL_CUSTOM_VAL) {
396
                        // get template from database
397
                        $htmlBody = $letterTpl->fetchFromData($templateObj->getVar('template_content', 'n'));
398
                    } else {
399
                        $template = $template_path . $templateObj->getVar('template_title') . '.tpl';
400
                        $htmlBody = $letterTpl->fetch($template);
401
                    }
402
                    try {
403
                        $textBody = xnewsletter_html2text($htmlBody);
404
                    }
405
                    catch (Html2TextException $e) {
406
                        $helper->addLog($e);
407
                    }
408
                } else {
409
                    $htmlBody = _AM_XNEWSLETTER_TEMPLATE_ERR;
410
                }
411
412
                $mail->addAddress($recipient['address'], $recipient['firstname'] . ' ' . $recipient['lastname']);
413
                $mail->msgHTML($htmlBody); // $mail->Body = $htmlBody;
414
                $mail->AltBody = $textBody;
0 ignored issues
show
Bug introduced by
The variable $textBody 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...
415
416
                foreach ($attachmentsPath as $attachmentPath) {
417
                    if (file_exists($attachmentPath)) {
418
                        $mail->addAttachment($attachmentPath);
419
                    }
420
                }
421
                ++$count_total;
422
423
                if ($mail->send()) {
424
                    if (0 == $subscr_id) {
425
                        $protocol_status        = _AM_XNEWSLETTER_SEND_SUCCESS_TEST . ' (' . $recipient['address'] . ')'; // old style
426
                        $protocol_status_str_id = _XNEWSLETTER_PROTOCOL_STATUS_OK_SEND_TEST; // new from v1.3
427
                        $protocol_status_vars   = ['recipient' => $recipient['address']]; // new from v1.3
428
                    } else {
429
                        $protocol_status        = _AM_XNEWSLETTER_SEND_SUCCESS; // old style
430
                        $protocol_status_str_id = _XNEWSLETTER_PROTOCOL_STATUS_OK_SEND; // new from v1.3
431
                        $protocol_status_vars   = []; // new from v1.3
432
                    }
433
                    $protocol_success = true;
434
                    //delete item in table task
435
                    $sql_delete = "DELETE FROM {$xoopsDB->prefix('xnewsletter_task')}";
436
                    $sql_delete .= " WHERE `task_id`= {$recipient['task_id']}";
437
                    $result = $xoopsDB->queryF($sql_delete);
0 ignored issues
show
Unused Code introduced by
$result 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...
438
                } else {
439
                    $protocol_status        = _AM_XNEWSLETTER_FAILED . '-> ' . $mail->ErrorInfo; // old style
440
                    $protocol_status_str_id = _XNEWSLETTER_PROTOCOL_STATUS_ERROR_SEND; // new from v1.3
441
                    $protocol_status_vars   = ['error' => $mail->ErrorInfo, 'letter_id' => $letter_id, 'letter_title' => $letter_title]; // new from v1.3
442
443
                    $protocol_success = 0; //must be 0, because 'false' cause error when inserting protokol item
444
                    ++$count_err;
445
                }
446
                //create item in protocol for this email
447
                $text_clean      = ['<strong>', '</strong>', '<br>', '<br>'];
448
                $protocol_status = str_replace($text_clean, '', $protocol_status);
449
450
                $mail->clearAddresses();
451
452
                $protocolObj = $helper->getHandler('Protocol')->create();
453
                $protocolObj->setVar('protocol_letter_id', $letter_id);
454
                $protocolObj->setVar('protocol_subscriber_id', $subscr_id);
455
                $protocolObj->setVar('protocol_status', $protocol_status); // old style
456
                $protocolObj->setVar('protocol_status_str_id', $protocol_status_str_id); // new from v1.3
457
                $protocolObj->setVar('protocol_status_vars', $protocol_status_vars); // new from v1.3
458
                $protocolObj->setVar('protocol_success', $protocol_success);
459
                $protocolObj->setVar('protocol_submitter', $uid);
460
                $protocolObj->setVar('protocol_created', time());
461
                if ($helper->getHandler('Protocol')->insert($protocolObj)) {
462
                    // create protocol is ok
463
                } else {
464
                    echo $protocolObj->getHtmlErrors();die;
465
                }
466
                unset($protocolObj);
467
            }
468
469
            unset($mail);
470
        }
471
        catch (phpmailerException $e) {
472
            // IN PROGRESS
473
            $protocol_status = _AM_XNEWSLETTER_SEND_ERROR_PHPMAILER . $e->errorMessage(); //error messages from PHPMailer
474
            ++$count_err;
475
            $protocol_success = false;
0 ignored issues
show
Unused Code introduced by
$protocol_success 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...
476
        }
477
        catch (\Exception $e) {
478
            // IN PROGRESS
479
            $protocol_status = _AM_XNEWSLETTER_SEND_ERROR_PHPMAILER . $e->getMessage(); //error messages from anything else!
480
            ++$count_err;
481
            $protocol_success = false;
0 ignored issues
show
Unused Code introduced by
$protocol_success 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...
482
        }
483
    }
484
485
    //create final protocol item
486
    if ($count_err > 0) {
487
        // IN PROGRESS
488
        $protocol_status  = xnewsletter_sprintf(_AM_XNEWSLETTER_SEND_ERROR_NUMBER, ['%e' => $count_err, '%t' => $count_total]);
489
        $protocol_status_id = 0;
490
        $protocol_success = 0; //must be 0, because 'false' cause error when inserting protokol item
491
    } else {
492
        $protocol_success = true;
493
        if ($count_total > 0) {
494
            // IN PROGRESS
495
            $protocol_status = xnewsletter_sprintf(_AM_XNEWSLETTER_SEND_SUCCESS_NUMBER, ['%t' => $count_total]);
496
        } else {
497
            // IN PROGRESS
498
            $protocol_status = '';
499
        }
500
        $protocol_status_id = 1;
501
    }
502
    $protocolObj = $helper->getHandler('Protocol')->create();
503
    $protocolObj->setVar('protocol_letter_id', $letter_id);
504
    $protocolObj->setVar('protocol_subscriber_id', 0);
505
    $protocolObj->setVar('protocol_status', $protocol_status);
506
    $protocolObj->setVar('protocol_status_str_id', $protocol_status_id); // new from v1.3
507
    $protocolObj->setVar('protocol_status_vars', []); // new from v1.3
508
    $protocolObj->setVar('protocol_success', $protocol_success);
509
    $protocolObj->setVar('protocol_submitter', $uid);
510
    $protocolObj->setVar('protocol_created', time());
511
    if ($helper->getHandler('Protocol')->insert($protocolObj)) {
512
        // create protocol is ok
513
    } else {
514
        echo $protocolObj->getHtmlErrors();die;
515
    }
516
    unset($protocolObj);
517
518
    if ($cron == 1) {
519
        //you can enable the block for creating protocol for cron
520
        $protocolObj = $helper->getHandler('Protocol')->create();
521
        $protocolObj->setVar('protocol_letter_id', 0);
522
        $protocolObj->setVar('protocol_subscriber_id', 0);
523
        $protocolObj->setVar('protocol_status', 'Cron job: ' . $protocol_status);
524
        $protocolObj->setVar('protocol_status_str_id', $protocol_status_id);
525
        $protocolObj->setVar('protocol_status_vars', []);
526
        $protocolObj->setVar('protocol_success', $protocol_success);
527
        $protocolObj->setVar('protocol_submitter', 0);
528
        $protocolObj->setVar('protocol_created', time());
529
530
        if ($helper->getHandler('Protocol')->insert($protocolObj)) {
531
            echo '<br>protocol about exec task successfully created';
532
        } else {
533
            echo $protocolObj->getHtmlErrors();
534
            echo '<br>errors when creating protocol';
535
        }
536
    }
537
538
    return $protocol_status;
539
}
540