Completed
Pull Request — master (#27)
by Michael
01:42
created

functions.php ➔ xnewsletter_emailSize()   F

Complexity

Conditions 21
Paths 1172

Size

Total Lines 147

Duplication

Lines 29
Ratio 19.73 %

Importance

Changes 0
Metric Value
cc 21
nc 1172
nop 1
dl 29
loc 147
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
 *  Version : 1 Mon 2012/11/05 14:31:32 :  Exp $
26
 * ****************************************************************************
27
 */
28
29
use XoopsModules\Xnewsletter;
30
31
require_once __DIR__ . '/common.php';
32
33
/**
34
 * @param $cats
35
 *
36
 * @return string
37
 */
38
function xnewsletter_block_addCatSelect($cats)
39
{
40
    if (is_array($cats)) {
41
        $cat_sql = '(' . current($cats);
42
        array_shift($cats);
43
        foreach ($cats as $cat) {
44
            $cat_sql .= ',' . $cat;
45
        }
46
        $cat_sql .= ')';
47
    }
48
49
    return $cat_sql;
0 ignored issues
show
Bug introduced by
The variable $cat_sql 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...
50
}
51
52
/**
53
 * @return bool
54
 */
55
function xnewsletter_checkModuleAdmin()
56
{
57
    if (file_exists($GLOBALS['xoops']->path('/Frameworks/moduleclasses/moduleadmin/moduleadmin.php'))) {
58
        require_once $GLOBALS['xoops']->path('/Frameworks/moduleclasses/moduleadmin/moduleadmin.php');
59
60
        return true;
61
    }
62
    echo xoops_error("Error: You don't use the Frameworks \"admin module\". Please install this Frameworks");
63
64
    return false;
65
}
66
67
/**
68
 * Checks if a user is admin of xnewsletter
69
 *
70
 * @return bool
71
 */
72
function xnewsletter_userIsAdmin()
73
{
74
    global $xoopsUser;
75
    $helper = Xnewsletter\Helper::getInstance();
76
77
    static $xnewsletter_isAdmin;
78
79
    if (isset($xnewsletter_isAdmin)) {
80
        return $xnewsletter_isAdmin;
81
    }
82
83
    if (!$xoopsUser) {
84
        $xnewsletter_isAdmin = false;
85
    } else {
86
        $xnewsletter_isAdmin = $xoopsUser->isAdmin($helper->getModule()->mid());
87
    }
88
89
    return $xnewsletter_isAdmin;
90
}
91
92
/**
93
 * @param      $email
94
 * @param bool $antispam
95
 *
96
 * @return bool|mixed
97
 */
98
function xnewsletter_checkEmail($email, $antispam = false)
99
{
100
    require_once XOOPS_ROOT_PATH . '/include/functions.php';
101
102
    return checkEmail($email, $antispam);
103
}
104
105
/**
106
 * @param $html
107
 *
108
 * @throws Html2TextException
109
 * @return string
110
 */
111
function xnewsletter_html2text($html)
112
{
113
    require_once XNEWSLETTER_ROOT_PATH . '/include/html2text/html2text.php';
114
115
    return convert_html_to_text($html);
116
}
117
118
/**
119
 * @param        $global
120
 * @param        string $key
121
 * @param string $default
122
 * @param string $type
123
 * @param bool   $notset
124
 *
125
 * @return bool|int|mixed|string
126
 */
127
function xnewsletter_CleanVars(&$global, $key, $default = '', $type = 'int', $notset = false)
128
{
129
    require_once XOOPS_ROOT_PATH . '/include/functions.php';
130
    switch ($type) {
131
        case 'string':
132
                        if(defined('FILTER_SANITIZE_ADD_SLASHES')){
133
                $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_ADD_SLASHES) : $default;
134
            } else {
135
                $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_MAGIC_QUOTES) : $default;
136
            }
137
            if ($notset) {
138
                if ('' == trim($ret)) {
139
                    $ret = $default;
140
                }
141
            }
142
            break;
143
        case 'date':
144
            $ret = isset($global[$key]) ? strtotime($global[$key]) : $default;
145
            break;
146
        case 'email':
147
            $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_EMAIL) : $default;
148
            $ret = checkEmail($ret);
149
            break;
150
        case 'array':
151
            if (isset($global[$key])) {
152
                //ToDo!!
153
                $ret = $global[$key];
154
            }
155
            break;
156
        case 'int':
157
        default:
158
            $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_NUMBER_INT) : $default;
159
            break;
160
    }
161
    if (false === $ret) {
0 ignored issues
show
Bug introduced by
The variable $ret 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...
162
        return $default;
163
    }
164
165
    return $ret;
166
}
167
168
/**
169
 * @param string $str
170
 * @param array  $vars associative array
171
 *
172
 * @param string $char
173
 * @return string
174
 */
175
function xnewsletter_sprintf($str = '', $vars = [], $char = '')
176
{
177
    if (!$str) {
178
        return '';
179
    }
180
    if (count($vars) > 0) {
181
        foreach ($vars as $k => $v) {
182
            $str = str_replace($char . $k, $v, $str);
183
        }
184
    }
185
186
    return $str;
187
}
188
189
/**
190
 * @param $contentObj
191
 * @param $sets
192
 *
193
 * @return mixed
194
 */
195
function xnewsletter_setPost($contentObj, $sets)
196
{
197
    if (!is_object($contentObj)) {
198
        return false;
199
    }
200
    if (isset($sets)) {
201
        $contentObj->setVar('accounts_id', xnewsletter_CleanVars($sets, 'accounts_id', 0, 'int'));
202
        $contentObj->setVar('accounts_type', xnewsletter_CleanVars($sets, 'accounts_type', 1, 'int'));
203
        $contentObj->setVar('accounts_name', xnewsletter_CleanVars($sets, 'accounts_name', _AM_XNEWSLETTER_ACCOUNTS_TYPE_NAME, 'string', true));
204
        $contentObj->setVar('accounts_yourname', xnewsletter_CleanVars($sets, 'accounts_yourname', _AM_XNEWSLETTER_ACCOUNTS_YOURNAME, 'string', true));
205
        $contentObj->setVar('accounts_yourmail', xnewsletter_CleanVars($sets, 'accounts_yourmail', _AM_XNEWSLETTER_ACCOUNTS_TYPE_YOUREMAIL, 'email', true));
206
        $contentObj->setVar('accounts_username', xnewsletter_CleanVars($sets, 'accounts_username', _AM_XNEWSLETTER_ACCOUNTS_USERNAME, 'string', true));
207
        $contentObj->setVar('accounts_password', xnewsletter_CleanVars($sets, 'accounts_password', _AM_XNEWSLETTER_ACCOUNTS_PASSWORD, 'string', true));
208
        if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_SMTP == $contentObj->getVar('accounts_type')) {
209
            if ($contentObj->isNew()) {
210
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_SERVER_IN == @$set['accounts_server_in']) {
0 ignored issues
show
Bug introduced by
The variable $set does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
211
                    $sets['accounts_server_in'] = null;
212
                }
213
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_PORT_IN == @$set['accounts_port_in']) {
214
                    $sets['accounts_port_in'] = null;
215
                }
216
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_SERVER_OUT == @$set['accounts_server_out']) {
217
                    $sets['accounts_server_out'] = null;
218
                }
219
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_PORT_OUT == @$set['accounts_port_out']) {
220
                    $sets['accounts_port_out'] = null;
221
                }
222
            }
223
            $contentObj->setVar('accounts_server_in', xnewsletter_CleanVars($sets, 'accounts_server_in', _AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_SERVER_IN, 'string', true));
224
            $contentObj->setVar('accounts_port_in', xnewsletter_CleanVars($sets, 'accounts_port_in', _AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_PORT_IN, 'string', true));
225
            $contentObj->setVar('accounts_server_out', xnewsletter_CleanVars($sets, 'accounts_server_out', _AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_SERVER_OUT, 'string', true));
226
            $contentObj->setVar('accounts_port_out', xnewsletter_CleanVars($sets, 'accounts_port_out', _AM_XNEWSLETTER_ACCOUNTS_TYPE_SMTP_PORT_OUT, 'string', true));
227
            $contentObj->setVar('accounts_securetype_in', xnewsletter_CleanVars($sets, 'accounts_securetype_in', '', 'string'));
228
            $contentObj->setVar('accounts_securetype_out', xnewsletter_CleanVars($sets, 'accounts_securetype_out', '', 'string'));
229
        } elseif (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_GMAIL == $contentObj->getVar('accounts_type')) {
230
            if ($contentObj->isNew()) {
231
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_SERVER_IN == @$set['accounts_server_in']) {
232
                    $sets['accounts_server_in'] = null;
233
                }
234
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_PORT_IN == @$set['accounts_port_in']) {
235
                    $sets['accounts_port_in'] = null;
236
                }
237
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_SERVER_OUT == @$set['accounts_server_out']) {
238
                    $sets['accounts_server_out'] = null;
239
                }
240
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_PORT_OUT == @$set['accounts_port_out']) {
241
                    $sets['accounts_port_out'] = null;
242
                }
243
            }
244
            $contentObj->setVar('accounts_server_in', xnewsletter_CleanVars($sets, 'accounts_server_in', _AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_SERVER_IN, 'string', true));
245
            $contentObj->setVar('accounts_port_in', xnewsletter_CleanVars($sets, 'accounts_port_in', _AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_PORT_IN, 'string', true));
246
            $contentObj->setVar('accounts_server_out', xnewsletter_CleanVars($sets, 'accounts_server_out', _AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_SERVER_OUT, 'string', true));
247
            $contentObj->setVar('accounts_port_out', xnewsletter_CleanVars($sets, 'accounts_port_out', _AM_XNEWSLETTER_ACCOUNTS_TYPE_GMAIL_PORT_OUT, 'string', true));
248
            $contentObj->setVar('accounts_securetype_in', xnewsletter_CleanVars($sets, 'accounts_securetype_in', _AM_XNEWSLETTER_ACCOUNTS_TYPE_SECURETYPE_IN, 'string'));
249
            $contentObj->setVar('accounts_securetype_out', xnewsletter_CleanVars($sets, 'accounts_securetype_out', _AM_XNEWSLETTER_ACCOUNTS_TYPE_SECURETYPE_OUT, 'string'));
250
        } else {
251
            if ($contentObj->isNew()) {
252
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_SERVER_IN == @$set['accounts_server_in']) {
253
                    $sets['accounts_server_in'] = null;
254
                }
255
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_PORT_IN == @$set['accounts_port_in']) {
256
                    $sets['accounts_port_in'] = null;
257
                }
258
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_SERVER_OUT == @$set['accounts_server_out']) {
259
                    $sets['accounts_server_out'] = null;
260
                }
261
                if (_AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_PORT_OUT == @$set['accounts_port_out']) {
262
                    $sets['accounts_port_out'] = null;
263
                }
264
            }
265
            $contentObj->setVar('accounts_server_in', xnewsletter_CleanVars($sets, 'accounts_server_in', _AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_SERVER_IN, 'string', true));
266
            $contentObj->setVar('accounts_port_in', xnewsletter_CleanVars($sets, 'accounts_port_in', _AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_PORT_IN, 'string', true));
267
            $contentObj->setVar('accounts_server_out', xnewsletter_CleanVars($sets, 'accounts_server_out', _AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_SERVER_OUT, 'string', true));
268
            $contentObj->setVar('accounts_port_out', xnewsletter_CleanVars($sets, 'accounts_port_out', _AM_XNEWSLETTER_ACCOUNTS_TYPE_POP3_PORT_OUT, 'string', true));
269
            $contentObj->setVar('accounts_securetype_in', xnewsletter_CleanVars($sets, 'accounts_securetype_in', '', 'string'));
270
            $contentObj->setVar('accounts_securetype_out', xnewsletter_CleanVars($sets, 'accounts_securetype_out', '', 'string'));
271
        }
272
        $contentObj->setVar('accounts_use_bmh', xnewsletter_CleanVars($sets, 'accounts_use_bmh', 0, 'int'));
273
        $contentObj->setVar('accounts_inbox', xnewsletter_CleanVars($sets, 'accounts_inbox', _XNEWSLETTER_ACCOUNTS_TYPE_INBOX, 'string', true));
274
        $contentObj->setVar('accounts_hardbox', xnewsletter_CleanVars($sets, 'accounts_hardbox', _XNEWSLETTER_ACCOUNTS_TYPE_HARDBOX, 'string'));
275
        $contentObj->setVar('accounts_movehard', xnewsletter_CleanVars($sets, 'accounts_movehard', 0, 'int'));
276
        $contentObj->setVar('accounts_softbox', xnewsletter_CleanVars($sets, 'accounts_softbox', _XNEWSLETTER_ACCOUNTS_TYPE_SOFTBOX, 'string'));
277
        $contentObj->setVar('accounts_movesoft', xnewsletter_CleanVars($sets, 'accounts_movesoft', 0, 'int'));
278
        $contentObj->setVar('accounts_default', xnewsletter_CleanVars($sets, 'accounts_default', 0, 'int'));
279
        $contentObj->setVar('accounts_submitter', xnewsletter_CleanVars($sets, 'accounts_submitter', 0, 'int'));
280
        $contentObj->setVar('accounts_created', time());
281
    }
282
283
    return $contentObj;
284
}
285
286
/**
287
 * Check the rights of current user for this letter
288
 * returns the permission as array
289
 *
290
 * @param int $letter_id
291
 *
292
 * @return array
293
 */
294
function xnewsletter_getUserPermissionsByLetter($letter_id = 0)
295
{
296
    global $xoopsUser;
297
    $grouppermHandler = xoops_getHandler('groupperm');
298
    $memberHandler    = xoops_getHandler('member');
0 ignored issues
show
Unused Code introduced by
$memberHandler 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...
299
    $helper           = Xnewsletter\Helper::getInstance();
300
301
    $uid    = (is_object($xoopsUser) && isset($xoopsUser)) ? $xoopsUser->uid() : 0;
302
    $groups = is_object($xoopsUser) ? $xoopsUser->getGroups() : [0 => XOOPS_GROUP_ANONYMOUS];
303
304
    $permissions = [
305
        'read'   => false,
306
        'edit'   => false,
307
        'delete' => false,
308
        'create' => false,
309
        'send'   => false,
310
        'list'   => false,
311
    ];
312
313
    if ($uid > 0 && $xoopsUser->isAdmin()) {
314
        $permissions['read']   = true;
315
        $permissions['edit']   = true;
316
        $permissions['delete'] = true;
317
        $permissions['create'] = true;
318
        $permissions['send']   = true;
319
        $permissions['list']   = true;
320
    } else {
321
        $letterObj   = $helper->getHandler('Letter')->get($letter_id);
322
        $letter_cats = explode('|', $letterObj->getVar('letter_cats'));
323
        foreach ($letter_cats as $cat_id) {
324
            if ($grouppermHandler->checkRight('newsletter_admin_cat', $cat_id, $groups, $helper->getModule()->mid())) {
325
                $permissions['read']   = true;
326
                $permissions['edit']   = true;
327
                $permissions['delete'] = true;
328
                $permissions['create'] = true;
329
                $permissions['send']   = true;
330
                $permissions['list']   = true;
331
            } else {
332
                if ($grouppermHandler->checkRight('newsletter_create_cat', $cat_id, $groups, $helper->getModule()->mid())) {
333
                    $permissions['create'] = true;
334
                    $permissions['read']   = true; //creator should have perm to read all letters of this cat
335
                    if ($uid == $letterObj->getVar('letter_submitter')) {
336
                        $permissions['edit']   = true; //creator must have perm to edit own letters
337
                        $permissions['delete'] = true; //creator must have perm to edit own letters
338
                        $permissions['send']   = true; //creator must have perm to send/resend own letters
339
                    }
340
                }
341
                if ($grouppermHandler->checkRight('newsletter_read_cat', $cat_id, $groups, $helper->getModule()->mid())) {
342
                    $permissions['read'] = true;
343
                }
344
                if ($grouppermHandler->checkRight('newsletter_list_cat', $cat_id, $groups, $helper->getModule()->mid())) {
345
                    $permissions['list'] = true;
346
                }
347
            }
348
        }
349
    }
350
351
    return $permissions;
352
}
353
354
/**
355
 * Check the rights of current user
356
 * if a cat is defined, than only check for this cat, otherwise check whether there is minimum one cat with right create
357
 *
358
 * @param int $cat_id
359
 *
360
 * @return bool
361
 */
362
function xnewsletter_userAllowedCreateCat($cat_id = 0)
363
{
364
    global $xoopsUser;
365
    $grouppermHandler = xoops_getHandler('groupperm');
366
    $memberHandler    = xoops_getHandler('member');
367
    $helper           = Xnewsletter\Helper::getInstance();
368
369
    $allowedit = 0;
370
    $uid       = (is_object($xoopsUser) && isset($xoopsUser)) ? $xoopsUser->uid() : 0;
371
    if (0 == $uid) {
372
        return false;
373
    }
374
375
    $groups = $memberHandler->getGroupsByUser($uid);
376
377
    if ($cat_id > 0) {
378
        $catObj    = $helper->getHandler('Cat')->get($cat_id);
0 ignored issues
show
Unused Code introduced by
$catObj 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...
379
        $allowedit = $grouppermHandler->checkRight('newsletter_create_cat', $cat_id, $groups, $helper->getModule()->mid());
380
    } else {
381
        $catCriteria = new \CriteriaCompo();
382
        $catObjs     = $helper->getHandler('Cat')->getAll($catCriteria);
383
        foreach ($catObjs as $i => $catObj) {
384
            $cat_id    = $catObj->getVar('cat_id');
385
            $allowedit += $grouppermHandler->checkRight('newsletter_create_cat', $cat_id, $groups, $helper->getModule()->mid());
386
        }
387
    }
388
389
    return ($allowedit > 0);
390
}
391
392
/**
393
 * @param string $email
394
 *
395
 * @return bool
396
 */
397
function xnewsletter_pluginCheckEmail($email = '')
398
{
399
    global $xoopsDB;
400
401
    if ('' == $email) {
402
        return false;
403
    }
404
    $sql = "SELECT `subscr_id` FROM {$xoopsDB->prefix('xnewsletter_subscr')}";
405
    $sql .= " WHERE ((subscr_email)='{$email}')";
406
    if (!$subscriber = $xoopsDB->query($sql)) {
407
        die('MySQL-Error in xnewsletter_pluginCheckEmail: ' . $GLOBALS['xoopsDB']->error());
408
    }
409
    $row_result = mysqli_fetch_assoc($subscriber);
410
    $ret        = $row_result['subscr_id'] > 0 ? $row_result['subscr_id'] : false;
411
    unset($row_result);
412
    unset($subscriber);
413
414
    return $ret;
415
}
416
417
/**
418
 * @param bool $subscr_id
419
 * @param $cat_id
420
 *
421
 * @return bool
422
 */
423
function xnewsletter_pluginCheckCatSubscr($subscr_id, $cat_id)
424
{
425
    global $xoopsDB;
426
427
    if (0 == $subscr_id || 0 == $cat_id) {
428
        return false;
429
    }
430
    $sql = 'SELECT `catsubscr_id`';
431
    $sql .= " FROM {$xoopsDB->prefix('xnewsletter_catsubscr')}";
432
    $sql .= " WHERE ((catsubscr_subscrid)={$subscr_id} AND (catsubscr_catid)={$cat_id})";
433
    if (!$subscriber = $xoopsDB->query($sql)) {
434
        die('MySQL-Error in xnewsletter_pluginCheckCatSubscr: ' . $GLOBALS['xoopsDB']->error());
435
    }
436
    $row_result = mysqli_fetch_assoc($subscriber);
437
    $ret        = $row_result['catsubscr_id'] > 0 ? $row_result['catsubscr_id'] : false;
438
    unset($row_result);
439
    unset($subscriber);
440
441
    return $ret;
442
}
443
444
/**
445
 * @param     $bytes
446
 * @param int $precision
447
 *
448
 * @return string
449
 */
450
function xnewsletter_bytesToSize1024($bytes, $precision = 2)
451
{
452
    // human readable format -- powers of 1024
453
    $unit = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB'];
454
455
    $i = floor(log($bytes, 1024));
456
457
    return @round($bytes / (pow(1024, $i )), $precision) . ' ' . $unit[(int)$i];
458
}
459
460
/**
461
 * Try to calculate email size (quite precise)
462
 *
463
 * @param int $letter_id
464
 *
465
 * @return int
0 ignored issues
show
Documentation introduced by
Should the return type not be string|false|integer|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
466
 * @throws \Html2TextException
467
 * @throws \phpmailerException
468
 */
469
function xnewsletter_emailSize($letter_id = 0)
470
{
471
//    require_once XNEWSLETTER_ROOT_PATH . '/class/class.xnewslettermailer.php';
472
    global $XoopsTpl;
473
    $helper = Xnewsletter\Helper::getInstance();
474
475 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...
476
        require_once XOOPS_ROOT_PATH . '/class/template.php';
477
        $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...
478
    }
479
    // get template path
480
    $template_path = XNEWSLETTER_ROOT_PATH . '/language/' . $GLOBALS['xoopsConfig']['language'] . '/templates/';
481
    if (!is_dir($template_path)) {
482
        $template_path = XNEWSLETTER_ROOT_PATH . '/language/english/templates/';
483
    }
484
    if (!is_dir($template_path)) {
485
        return str_replace('%p', $template_path, _AM_XNEWSLETTER_SEND_ERROR_INALID_TEMPLATE_PATH);
486
    }
487
488
    $letterObj = $helper->getHandler('Letter')->get($letter_id);
489
    if (!is_object($letterObj)) {
490
        return false;
491
    }
492
493
    // read categories
494
    $letter_cats = $letterObj->getVar('letter_cats');
495
    if ('' == $letter_cats) {
496
        //no cats
497
        return false;
498
    }
499
500
    // read data of account
501
    $letter_account = $letterObj->getVar('letter_account');
502
    if ('' == $letter_account || 0 == $letter_account) {
503
        return false;
504
    }
505
    $accountObj             = $helper->getHandler('Accounts')->get($letter_account);
506
    if (!is_object($accountObj)) {
507
        return false;
508
    }
509
    $account_type           = $accountObj->getVar('accounts_type');
510
    $account_yourname       = $accountObj->getVar('accounts_yourname');
511
    $account_yourmail       = $accountObj->getVar('accounts_yourmail');
512
    $account_username       = $accountObj->getVar('accounts_username');
513
    $account_password       = $accountObj->getVar('accounts_password');
514
    $account_server_out     = $accountObj->getVar('accounts_server_out');
515
    $account_port_out       = $accountObj->getVar('accounts_port_out');
516
    $account_securetype_out = $accountObj->getVar('accounts_securetype_out');
517
518
    // create basic mail body
519
    $letter_title   = $letterObj->getVar('letter_title');
520
    $letter_content = $letterObj->getVar('letter_content', 'n');
521
522
    $letterTpl = new \XoopsTpl();
523
    // letter data
524
    $letterTpl->assign('content', $letter_content);
525
    $letterTpl->assign('title', $letter_title); // new from v1.3
526
    // letter attachments as link
527
    $attachmentAslinkCriteria = new \CriteriaCompo();
528
    $attachmentAslinkCriteria->add(new \Criteria('attachment_letter_id', $letter_id));
529
    $attachmentAslinkCriteria->add(new \Criteria('attachment_mode', _XNEWSLETTER_ATTACHMENTS_MODE_ASLINK));
530
    $attachmentAslinkCriteria->setSort('attachment_id');
531
    $attachmentAslinkCriteria->setOrder('ASC');
532
    $attachmentObjs = $helper->getHandler('Attachment')->getObjects($attachmentAslinkCriteria, true);
533 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...
534
        $attachment_array                    = $attachmentObj->toArray();
535
        $attachment_array['attachment_url']  = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
536
        $attachment_array['attachment_link'] = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
537
        $letterTpl->append('attachments', $attachment_array);
538
    }
539
    // extra data
540
    $letterTpl->assign('date', time()); // new from v1.3
541
    $letterTpl->assign('xoops_url', XOOPS_URL); // new from v1.3
542
    $letterTpl->assign('xoops_langcode', _LANGCODE); // new from v1.3
543
    $letterTpl->assign('xoops_charset', _CHARSET); // new from v1.3
544
    // subscr data
545
    $letterTpl->assign('sex', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW);
546
    $letterTpl->assign('salutation', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW); // new from v1.3
547
    $letterTpl->assign('firstname', _AM_XNEWSLETTER_SUBSCR_FIRSTNAME_PREVIEW);
548
    $letterTpl->assign('lastname', _AM_XNEWSLETTER_SUBSCR_LASTNAME_PREVIEW);
549
    $letterTpl->assign('subscr_email', $letterObj->getVar('letter_email_test'));
550
    $letterTpl->assign('email', $letterObj->getVar('letter_email_test')); // new from v1.3
551
    $letterTpl->assign('unsubscribe_link', 'Test');
552
    $letterTpl->assign('unsubscribe_url', 'Test'); // new from v1.3
553
554
    preg_match('/db:([0-9]*)/', $letterObj->getVar('letter_template'), $matches);
555 View Code Duplication
    if (isset($matches[1]) && ($templateObj = $helper->getHandler('Template')->get((int)$matches[1]))) {
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...
556
        // get template from database
557
        $htmlBody = $letterTpl->fetchFromData($templateObj->getVar('template_content', 'n'));
558
    } else {
559
        // get template from filesystem
560
        $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/' . $GLOBALS['xoopsConfig']['language'] . '/templates/';
561
        if (!is_dir($template_path)) {
562
            $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/english/templates/';
563
        }
564
        $template = $template_path . $letterObj->getVar('letter_template') . '.tpl';
565
        $htmlBody = $letterTpl->fetch($template);
566
    }
567
    $textBody = xnewsletter_html2text($htmlBody); // new from v1.3
568
    //$textBody = mb_convert_encoding($textBody, 'ISO-8859-1', _CHARSET); // "text/plain; charset=us-ascii" [http://www.w3.org/Protocols/rfc1341/7_1_Text.html]
569
570
    // get letter attachments as attachment
571
    $attachmentAsattachmentCriteria = new \CriteriaCompo();
572
    $attachmentAsattachmentCriteria->add(new \Criteria('attachment_letter_id', $letter_id));
573
    $attachmentAsattachmentCriteria->add(new \Criteria('attachment_mode', _XNEWSLETTER_ATTACHMENTS_MODE_ASATTACHMENT));
574
    $attachmentAsattachmentCriteria->setSort('attachment_id');
575
    $attachmentAsattachmentCriteria->setOrder('ASC');
576
    $attachmentObjs  = $helper->getHandler('Attachment')->getObjects($attachmentAsattachmentCriteria, true);
577
    $attachmentsPath = [];
578 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...
579
        $attachmentsPath[] = XOOPS_UPLOAD_PATH . $helper->getConfig('xn_attachment_path') . $letter_id . '/' . $attachmentObj->getVar('attachment_name');
580
    }
581
582
    $mail           = new Xnewsletter\XnewsletterMailer();
583
    $mail->CharSet  = _CHARSET; //use xoops default character set
584
    $mail->Username = $account_username; // SMTP account username
585
    $mail->Password = $account_password; // SMTP account password
586
    if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_POP3 == $account_type) {
587
        $mail->isSMTP();
588
        //$mail->SMTPDebug = 2;
589
        $mail->Host = $account_server_out;
590
    }
591 View Code Duplication
    if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_SMTP == $account_type || _XNEWSLETTER_ACCOUNTS_TYPE_VAL_GMAIL == $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...
592
        $mail->Port = $account_port_out; // set the SMTP port
593
        $mail->Host = $account_server_out; //sometimes necessary to repeat
594
    }
595
    if ('' != $account_securetype_out) {
596
        $mail->SMTPAuth   = true;
597
        $mail->SMTPSecure = $account_securetype_out; // sets the prefix to the server
598
    }
599
    $mail->setFrom($account_yourmail, $account_yourname);
600
    $mail->addReplyTo($account_yourmail, $account_yourname);
601
    $mail->Subject = html_entity_decode($letter_title, ENT_QUOTES);
602
603
    $mail->addAddress($letterObj->getVar('letter_email_test'), _AM_XNEWSLETTER_SUBSCR_FIRSTNAME_PREVIEW . ' ' . _AM_XNEWSLETTER_SUBSCR_LASTNAME_PREVIEW);
604
    $mail->msgHTML($htmlBody); // $mail->Body = $htmlBody;
605
    $mail->AltBody = $textBody;
606
607
    foreach ($attachmentsPath as $attachmentPath) {
608
        if (file_exists($attachmentPath)) {
609
            $mail->addAttachment($attachmentPath);
610
        }
611
    }
612
613
    return $mail->getSize();
614
    unset($mail);
0 ignored issues
show
Unused Code introduced by
unset($mail); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
615
}
616
617
/**
618
 * @param      $filePath
619
 * @param bool $isBinary
620
 * @param bool $retBytes
621
 *
622
 * @return bool|int|mixed
623
 */
624
function xnewsletter_download($filePath, $isBinary = true, $retBytes = true)
625
{
626
    // how many bytes per chunk
627
    //$chunkSize = 1 * (1024 * 1024);
628
    $chunkSize    = 8 * (1024 * 1024); //8MB (highest possible fread length)
629
    $buffer       = '';
0 ignored issues
show
Unused Code introduced by
$buffer 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...
630
    $bytesCounter = 0;
631
632
    if (true === $isBinary) {
633
        $handler = fopen($filePath, 'rb');
634
    } else {
635
        $handler = fopen($filePath, 'rb');
636
    }
637
    if (false === $handler) {
638
        return false;
639
    }
640
    while (!feof($handler)) {
641
        $buffer = fread($handler, $chunkSize);
642
        echo $buffer;
643
        ob_flush();
644
        flush();
645
        if ($retBytes) {
646
            $bytesCounter += mb_strlen($buffer);
647
        }
648
    }
649
    $status = fclose($handler);
650
    if ($retBytes && $status) {
651
        return $bytesCounter; // return num. bytes delivered like readfile() does.
652
    }
653
654
    return $status;
655
}
656
657
/**
658
 * @author     Jack Mason
659
 * @website    volunteer @ http://www.osipage.com, web access application and bookmarking tool.
660
 * @copyright  Free script, use anywhere as you like, no attribution required
661
 * @created    2014
662
 * The script is capable of downloading really large files in PHP. Files greater than 2GB may fail in 32-bit windows or similar system.
663
 * All incorrect headers have been removed and no nonsense code remains in this script. Should work well.
664
 * The best and most recommended way to download files with PHP is using xsendfile, learn
665
 * more here: https://tn123.org/mod_xsendfile/
666
 *
667
 * @param $filePath
668
 * @param $fileMimetype
669
 */
670
function xnewsletter_largeDownload($filePath, $fileMimetype)
0 ignored issues
show
Unused Code introduced by
The parameter $fileMimetype is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
671
{
672
    /* You may need these ini settings too */
673
    set_time_limit(0);
674
    ini_set('memory_limit', '512M');
675
    if (!empty($filePath)) {
676
        $fileInfo            = pathinfo($filePath);
677
        $fileName            = $fileInfo['basename'];
678
        $fileExtrension      = $fileInfo['extension'];
0 ignored issues
show
Unused Code introduced by
$fileExtrension 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...
679
        $default_contentType = 'application/octet-stream';
680
        // to find and use specific content type, check out this IANA page : http://www.iana.org/assignments/media-types/media-types.xhtml
681
        if ($fileMimetype = !'') {
682
            $contentType = $fileMimetype;
683
        } else {
684
            $contentType = $default_contentType;
685
        }
686
        if (file_exists($filePath)) {
687
            $size   = filesize($filePath);
688
            $offset = 0;
0 ignored issues
show
Unused Code introduced by
$offset 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...
689
            $length = $size;
0 ignored issues
show
Unused Code introduced by
$length 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...
690
            //HEADERS FOR PARTIAL DOWNLOAD FACILITY BEGINS
691
            if (\Xmf\Request::hasVar('HTTP_RANGE', 'SERVER')) {
692
                preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
693
                $offset  = (int)$matches[1];
694
                $length  = (int)$matches[2] - $offset;
695
                $fhandle = fopen($filePath, 'rb');
696
                fseek($fhandle, $offset); // seek to the requested offset, this is 0 if it's not a partial content request
697
                $data = fread($fhandle, $length);
0 ignored issues
show
Unused Code introduced by
$data 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...
698
                fclose($fhandle);
699
                header('HTTP/1.1 206 Partial Content');
700
                header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $size);
701
            }//HEADERS FOR PARTIAL DOWNLOAD FACILITY BEGINS
702
            //USUAL HEADERS FOR DOWNLOAD
703
            header('Content-Disposition: attachment;filename=' . $fileName);
704
            header('Content-Type: ' . $contentType);
705
            header('Accept-Ranges: bytes');
706
            header('Pragma: public');
707
            header('Expires: -1');
708
            header('Cache-Control: no-cache');
709
            header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
710
            header('Content-Length: ' . filesize($filePath));
711
            $chunksize = 8 * (1024 * 1024); //8MB (highest possible fread length)
712
            if ($size > $chunksize) {
713
                $handle = fopen($_FILES['file']['tmp_name'], 'rb');
714
                $buffer = '';
0 ignored issues
show
Unused Code introduced by
$buffer 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...
715
                while (!feof($handle) && (CONNECTION_NORMAL === connection_status())) {
716
                    $buffer = fread($handle, $chunksize);
717
                    print $buffer;
718
                    ob_flush();
719
                    flush();
720
                }
721
                if (CONNECTION_NORMAL !== connection_status()) {
722
                    //TODO traslation
723
                    echo 'Connection aborted';
724
                }
725
                fclose($handle);
726
            } else {
727
                ob_clean();
728
                flush();
729
                readfile($filePath);
730
            }
731
        } else {
732
            //TODO traslation
733
            echo 'File does not exist!';
734
        }
735
    } else {
736
        //TODO traslation
737
        echo 'There is no file to download!';
738
    }
739
}
740