Completed
Pull Request — master (#29)
by Goffy
01:40
created

include/functions.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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;
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) {
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']) {
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
    /** @var \XoopsGroupPermHandler $grouppermHandler */
298
    $grouppermHandler = xoops_getHandler('groupperm');
299
    /** @var \XoopsMemberHandler $memberHandler */
300
    $memberHandler = xoops_getHandler('member');
301
    $helper        = Xnewsletter\Helper::getInstance();
302
303
    $uid    = (is_object($xoopsUser) && isset($xoopsUser)) ? $xoopsUser->uid() : 0;
304
    $groups = is_object($xoopsUser) ? $xoopsUser->getGroups() : [0 => XOOPS_GROUP_ANONYMOUS];
305
306
    $permissions = [
307
        'read'   => false,
308
        'edit'   => false,
309
        'delete' => false,
310
        'create' => false,
311
        'send'   => false,
312
        'list'   => false,
313
    ];
314
315
    if ($uid > 0 && $xoopsUser->isAdmin()) {
316
        $permissions['read']   = true;
317
        $permissions['edit']   = true;
318
        $permissions['delete'] = true;
319
        $permissions['create'] = true;
320
        $permissions['send']   = true;
321
        $permissions['list']   = true;
322
    } else {
323
        $letterObj   = $helper->getHandler('Letter')->get($letter_id);
324
        $letter_cats = explode('|', $letterObj->getVar('letter_cats'));
325
        foreach ($letter_cats as $cat_id) {
326
            if ($grouppermHandler->checkRight('newsletter_admin_cat', $cat_id, $groups, $helper->getModule()->mid())) {
327
                $permissions['read']   = true;
328
                $permissions['edit']   = true;
329
                $permissions['delete'] = true;
330
                $permissions['create'] = true;
331
                $permissions['send']   = true;
332
                $permissions['list']   = true;
333
            } else {
334
                if ($grouppermHandler->checkRight('newsletter_create_cat', $cat_id, $groups, $helper->getModule()->mid())) {
335
                    $permissions['create'] = true;
336
                    $permissions['read']   = true; //creator should have perm to read all letters of this cat
337
                    if ($uid == $letterObj->getVar('letter_submitter')) {
338
                        $permissions['edit']   = true; //creator must have perm to edit own letters
339
                        $permissions['delete'] = true; //creator must have perm to edit own letters
340
                        $permissions['send']   = true; //creator must have perm to send/resend own letters
341
                    }
342
                }
343
                if ($grouppermHandler->checkRight('newsletter_read_cat', $cat_id, $groups, $helper->getModule()->mid())) {
344
                    $permissions['read'] = true;
345
                }
346
                if ($grouppermHandler->checkRight('newsletter_list_cat', $cat_id, $groups, $helper->getModule()->mid())) {
347
                    $permissions['list'] = true;
348
                }
349
            }
350
        }
351
    }
352
353
    return $permissions;
354
}
355
356
/**
357
 * Check the rights of current user
358
 * if a cat is defined, than only check for this cat, otherwise check whether there is minimum one cat with right create
359
 *
360
 * @param int $cat_id
361
 *
362
 * @return bool
363
 */
364
function xnewsletter_userAllowedCreateCat($cat_id = 0)
365
{
366
    global $xoopsUser;
367
    $grouppermHandler = xoops_getHandler('groupperm');
368
    $memberHandler    = xoops_getHandler('member');
369
    $helper           = Xnewsletter\Helper::getInstance();
370
371
    $allowedit = 0;
372
    $uid       = (is_object($xoopsUser) && isset($xoopsUser)) ? $xoopsUser->uid() : 0;
373
    if (0 == $uid) {
374
        return false;
375
    }
376
377
    $groups = $memberHandler->getGroupsByUser($uid);
378
379
    if ($cat_id > 0) {
380
        $catObj    = $helper->getHandler('Cat')->get($cat_id);
381
        $allowedit = $grouppermHandler->checkRight('newsletter_create_cat', $cat_id, $groups, $helper->getModule()->mid());
382
    } else {
383
        $catCriteria = new \CriteriaCompo();
384
        $catObjs     = $helper->getHandler('Cat')->getAll($catCriteria);
385
        foreach ($catObjs as $i => $catObj) {
386
            $cat_id    = $catObj->getVar('cat_id');
387
            $allowedit += $grouppermHandler->checkRight('newsletter_create_cat', $cat_id, $groups, $helper->getModule()->mid());
388
        }
389
    }
390
391
    return ($allowedit > 0);
392
}
393
394
/**
395
 * @param string $email
396
 *
397
 * @return bool
398
 */
399
function xnewsletter_pluginCheckEmail($email = '')
400
{
401
    global $xoopsDB;
402
403
    if ('' == $email) {
404
        return false;
405
    }
406
    $sql = "SELECT `subscr_id` FROM {$xoopsDB->prefix('xnewsletter_subscr')}";
407
    $sql .= " WHERE ((subscr_email)='{$email}')";
408
    if (!$subscriber = $xoopsDB->query($sql)) {
409
        die('MySQL-Error in xnewsletter_pluginCheckEmail: ' . $GLOBALS['xoopsDB']->error());
410
    }
411
    $row_result = mysqli_fetch_assoc($subscriber);
412
    $ret        = $row_result['subscr_id'] > 0 ? $row_result['subscr_id'] : false;
413
    unset($row_result);
414
    unset($subscriber);
415
416
    return $ret;
417
}
418
419
/**
420
 * @param bool $subscr_id
421
 * @param $cat_id
422
 *
423
 * @return bool
424
 */
425
function xnewsletter_pluginCheckCatSubscr($subscr_id, $cat_id)
426
{
427
    global $xoopsDB;
428
429
    if (0 == $subscr_id || 0 == $cat_id) {
430
        return false;
431
    }
432
    $sql = 'SELECT `catsubscr_id`';
433
    $sql .= " FROM {$xoopsDB->prefix('xnewsletter_catsubscr')}";
434
    $sql .= " WHERE ((catsubscr_subscrid)={$subscr_id} AND (catsubscr_catid)={$cat_id})";
435
    if (!$subscriber = $xoopsDB->query($sql)) {
436
        die('MySQL-Error in xnewsletter_pluginCheckCatSubscr: ' . $GLOBALS['xoopsDB']->error());
437
    }
438
    $row_result = mysqli_fetch_assoc($subscriber);
439
    $ret        = $row_result['catsubscr_id'] > 0 ? $row_result['catsubscr_id'] : false;
440
    unset($row_result);
441
    unset($subscriber);
442
443
    return $ret;
444
}
445
446
/**
447
 * @param     $bytes
448
 * @param int $precision
449
 *
450
 * @return string
451
 */
452
function xnewsletter_bytesToSize1024($bytes, $precision = 2)
453
{
454
    // human readable format -- powers of 1024
455
    $unit = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB'];
456
457
    $i = floor(log($bytes, 1024));
458
459
    return @round($bytes / (pow(1024, $i )), $precision) . ' ' . $unit[(int)$i];
460
}
461
462
/**
463
 * Try to calculate email size (quite precise)
464
 *
465
 * @param int $letter_id
466
 *
467
 * @return int|string|bool
468
 * @throws \Html2TextException
469
 * @throws \phpmailerException
470
 */
471
function xnewsletter_emailSize($letter_id = 0)
472
{
473
//    require_once XNEWSLETTER_ROOT_PATH . '/class/class.xnewslettermailer.php';
474
    global $XoopsTpl;
475
    $helper = Xnewsletter\Helper::getInstance();
476
477 View Code Duplication
    if (!isset($xoopsTpl) || !is_object($xoopsTpl)) {
478
        require_once XOOPS_ROOT_PATH . '/class/template.php';
479
        $xoopsTpl = new \XoopsTpl();
480
    }
481
    // get template path
482
    $template_path = XNEWSLETTER_ROOT_PATH . '/language/' . $GLOBALS['xoopsConfig']['language'] . '/templates/';
483
    if (!is_dir($template_path)) {
484
        $template_path = XNEWSLETTER_ROOT_PATH . '/language/english/templates/';
485
    }
486
    if (!is_dir($template_path)) {
487
        return str_replace('%p', $template_path, _AM_XNEWSLETTER_SEND_ERROR_INALID_TEMPLATE_PATH);
488
    }
489
490
    $letterObj = $helper->getHandler('Letter')->get($letter_id);
491
    if (!is_object($letterObj)) {
492
        return false;
493
    }
494
495
    // read categories
496
    $letter_cats = $letterObj->getVar('letter_cats');
497
    if ('' == $letter_cats) {
498
        //no cats
499
        return false;
500
    }
501
502
    // read data of account
503
    $letter_account = $letterObj->getVar('letter_account');
504
    if ('' == $letter_account || 0 == $letter_account) {
505
        return false;
506
    }
507
    $accountObj             = $helper->getHandler('Accounts')->get($letter_account);
508
    if (!is_object($accountObj)) {
509
        return false;
510
    }
511
    $account_type           = $accountObj->getVar('accounts_type');
512
    $account_yourname       = $accountObj->getVar('accounts_yourname');
513
    $account_yourmail       = $accountObj->getVar('accounts_yourmail');
514
    $account_username       = $accountObj->getVar('accounts_username');
515
    $account_password       = $accountObj->getVar('accounts_password');
516
    $account_server_out     = $accountObj->getVar('accounts_server_out');
517
    $account_port_out       = $accountObj->getVar('accounts_port_out');
518
    $account_securetype_out = $accountObj->getVar('accounts_securetype_out');
519
520
    // create basic mail body
521
    $letter_title   = $letterObj->getVar('letter_title');
522
    $letter_content = $letterObj->getVar('letter_content', 'n');
523
524
    $letterTpl = new \XoopsTpl();
525
    // letter data
526
    $letterTpl->assign('content', $letter_content);
527
    $letterTpl->assign('title', $letter_title); // new from v1.3
528
    // letter attachments as link
529
    $attachmentAslinkCriteria = new \CriteriaCompo();
530
    $attachmentAslinkCriteria->add(new \Criteria('attachment_letter_id', $letter_id));
531
    $attachmentAslinkCriteria->add(new \Criteria('attachment_mode', _XNEWSLETTER_ATTACHMENTS_MODE_ASLINK));
532
    $attachmentAslinkCriteria->setSort('attachment_id');
533
    $attachmentAslinkCriteria->setOrder('ASC');
534
    $attachmentObjs = $helper->getHandler('Attachment')->getObjects($attachmentAslinkCriteria, true);
535 View Code Duplication
    foreach ($attachmentObjs as $attachment_id => $attachmentObj) {
536
        $attachment_array                    = $attachmentObj->toArray();
537
        $attachment_array['attachment_url']  = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
538
        $attachment_array['attachment_link'] = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
539
        $letterTpl->append('attachments', $attachment_array);
540
    }
541
    // extra data
542
    $letterTpl->assign('date', time()); // new from v1.3
543
    $letterTpl->assign('xoops_url', XOOPS_URL); // new from v1.3
544
    $letterTpl->assign('xoops_langcode', _LANGCODE); // new from v1.3
545
    $letterTpl->assign('xoops_charset', _CHARSET); // new from v1.3
546
    // subscr data
547
    $letterTpl->assign('sex', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW);
548
    $letterTpl->assign('salutation', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW); // new from v1.3
549
    $letterTpl->assign('firstname', _AM_XNEWSLETTER_SUBSCR_FIRSTNAME_PREVIEW);
550
    $letterTpl->assign('lastname', _AM_XNEWSLETTER_SUBSCR_LASTNAME_PREVIEW);
551
    $letterTpl->assign('subscr_email', $letterObj->getVar('letter_email_test'));
552
    $letterTpl->assign('email', $letterObj->getVar('letter_email_test')); // new from v1.3
553
    $letterTpl->assign('unsubscribe_link', 'Test');
554
    $letterTpl->assign('unsubscribe_url', 'Test'); // new from v1.3
555
556
    $templateObj = $helper->getHandler('Template')->get($letterObj->getVar('letter_templateid'));
557
    $letter['template_err'] = false;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$letter was never initialized. Although not strictly required by PHP, it is generally a good practice to add $letter = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
558
    if (is_object($templateObj)) {
559
        if ( $templateObj->getVar('template_type') === _XNEWSLETTER_MAILINGLIST_TPL_CUSTOM_VAL) {
560
            // get template from database
561
            $htmlBody = $letterTpl->fetchFromData($templateObj->getVar('template_content', 'n'));
562
        } else {
563
            // get template from filesystem
564
            $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/' . $GLOBALS['xoopsConfig']['language'] . '/templates/';
565
            if (!is_dir($template_path)) {
566
                $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/english/templates/';
567
            }
568
            $template = $template_path . $templateObj->getVar('template_title') . '.tpl';
569
            if (file_exists($template)) {
570
                $htmlBody = $letterTpl->fetch($template);
571
            } else {
572
                $htmlBody = '';
573
                $letter['template_err'] = true;
574
                $letter['template_err_text'] = _AM_XNEWSLETTER_TEMPLATE_ERR_FILE;
575
            }
576
        }
577
    } else {
578
        $letter['template_err'] = true;
579
        $letter['template_err_text'] = _AM_XNEWSLETTER_TEMPLATE_ERR_TABLE;
580
    }
581
    $textBody = '';
582
    if ('' !== $htmlBody) {
583
        try {
584
            $textBody = xnewsletter_html2text($htmlBody);
0 ignored issues
show
The variable $htmlBody 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...
585
        }
586
        catch (Html2TextException $e) {
587
            $helper->addLog($e);
588
        }
589
    }
590
591
    // new from v1.3
592
    //$textBody = mb_convert_encoding($textBody, 'ISO-8859-1', _CHARSET); // "text/plain; charset=us-ascii" [http://www.w3.org/Protocols/rfc1341/7_1_Text.html]
593
594
    // get letter attachments as attachment
595
    $attachmentAsattachmentCriteria = new \CriteriaCompo();
596
    $attachmentAsattachmentCriteria->add(new \Criteria('attachment_letter_id', $letter_id));
597
    $attachmentAsattachmentCriteria->add(new \Criteria('attachment_mode', _XNEWSLETTER_ATTACHMENTS_MODE_ASATTACHMENT));
598
    $attachmentAsattachmentCriteria->setSort('attachment_id');
599
    $attachmentAsattachmentCriteria->setOrder('ASC');
600
    $attachmentObjs  = $helper->getHandler('Attachment')->getObjects($attachmentAsattachmentCriteria, true);
601
    $attachmentsPath = [];
602 View Code Duplication
    foreach ($attachmentObjs as $attachment_id => $attachmentObj) {
603
        $attachmentsPath[] = XOOPS_UPLOAD_PATH . $helper->getConfig('xn_attachment_path') . $letter_id . '/' . $attachmentObj->getVar('attachment_name');
604
    }
605
606
    $mail           = new Xnewsletter\XnewsletterMailer();
607
    $mail->CharSet  = _CHARSET; //use xoops default character set
608
    $mail->Username = $account_username; // SMTP account username
609
    $mail->Password = $account_password; // SMTP account password
610
    if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_POP3 == $account_type) {
611
        $mail->isSMTP();
612
        //$mail->SMTPDebug = 2;
613
        $mail->Host = $account_server_out;
614
    }
615 View Code Duplication
    if (_XNEWSLETTER_ACCOUNTS_TYPE_VAL_SMTP == $account_type || _XNEWSLETTER_ACCOUNTS_TYPE_VAL_GMAIL == $account_type) {
616
        $mail->Port = $account_port_out; // set the SMTP port
617
        $mail->Host = $account_server_out; //sometimes necessary to repeat
618
    }
619
    if ('' != $account_securetype_out) {
620
        $mail->SMTPAuth   = true;
621
        $mail->SMTPSecure = $account_securetype_out; // sets the prefix to the server
622
    }
623
    $mail->setFrom($account_yourmail, $account_yourname);
624
    $mail->addReplyTo($account_yourmail, $account_yourname);
625
    $mail->Subject = html_entity_decode($letter_title, ENT_QUOTES);
626
627
    $mail->addAddress($letterObj->getVar('letter_email_test'), _AM_XNEWSLETTER_SUBSCR_FIRSTNAME_PREVIEW . ' ' . _AM_XNEWSLETTER_SUBSCR_LASTNAME_PREVIEW);
628
    $mail->msgHTML($htmlBody); // $mail->Body = $htmlBody;
629
    $mail->AltBody = $textBody;
630
631
    foreach ($attachmentsPath as $attachmentPath) {
632
        if (file_exists($attachmentPath)) {
633
            $mail->addAttachment($attachmentPath);
634
        }
635
    }
636
637
    return $mail->getSize();
638
//    unset($mail);
639
}
640
641
/**
642
 * @param      $filePath
643
 * @param bool $isBinary
644
 * @param bool $retBytes
645
 *
646
 * @return bool|int|mixed
647
 */
648
function xnewsletter_download($filePath, $isBinary = true, $retBytes = true)
649
{
650
    // how many bytes per chunk
651
    //$chunkSize = 1 * (1024 * 1024);
652
    $chunkSize    = 8 * (1024 * 1024); //8MB (highest possible fread length)
653
    $buffer       = '';
654
    $bytesCounter = 0;
655
656
    if (true === $isBinary) {
657
        $handler = fopen($filePath, 'rb');
658
    } else {
659
        $handler = fopen($filePath, 'rb');
660
    }
661
    if (false === $handler) {
662
        return false;
663
    }
664
    while (!feof($handler)) {
665
        $buffer = fread($handler, $chunkSize);
666
        echo $buffer;
667
        ob_flush();
668
        flush();
669
        if ($retBytes) {
670
            $bytesCounter += mb_strlen($buffer);
671
        }
672
    }
673
    $status = fclose($handler);
674
    if ($retBytes && $status) {
675
        return $bytesCounter; // return num. bytes delivered like readfile() does.
676
    }
677
678
    return $status;
679
}
680
681
/**
682
 * @author     Jack Mason
683
 * @website    volunteer @ http://www.osipage.com, web access application and bookmarking tool.
684
 * @copyright  Free script, use anywhere as you like, no attribution required
685
 * @created    2014
686
 * The script is capable of downloading really large files in PHP. Files greater than 2GB may fail in 32-bit windows or similar system.
687
 * All incorrect headers have been removed and no nonsense code remains in this script. Should work well.
688
 * The best and most recommended way to download files with PHP is using xsendfile, learn
689
 * more here: https://tn123.org/mod_xsendfile/
690
 *
691
 * @param $filePath
692
 * @param $fileMimetype
693
 */
694
function xnewsletter_largeDownload($filePath, $fileMimetype)
695
{
696
    /* You may need these ini settings too */
697
    set_time_limit(0);
698
    ini_set('memory_limit', '512M');
699
    if (!empty($filePath)) {
700
        $fileInfo            = pathinfo($filePath);
701
        $fileName            = $fileInfo['basename'];
702
        $fileExtrension      = $fileInfo['extension'];
703
        $default_contentType = 'application/octet-stream';
704
        // to find and use specific content type, check out this IANA page : http://www.iana.org/assignments/media-types/media-types.xhtml
705
        $fileMimetype = !'';
706
        if ($fileMimetype) {
707
            $contentType = $fileMimetype;
708
        } else {
709
            $contentType = $default_contentType;
710
        }
711
        if (file_exists($filePath)) {
712
            $size   = filesize($filePath);
713
            $offset = 0;
714
            $length = $size;
715
            //HEADERS FOR PARTIAL DOWNLOAD FACILITY BEGINS
716
            if (\Xmf\Request::hasVar('HTTP_RANGE', 'SERVER')) {
717
                preg_match('/bytes=(\d+)-(\d+)?/', $_SERVER['HTTP_RANGE'], $matches);
718
                $offset  = (int)$matches[1];
719
                $length  = (int)$matches[2] - $offset;
720
                $fhandle = fopen($filePath, 'rb');
721
                fseek($fhandle, $offset); // seek to the requested offset, this is 0 if it's not a partial content request
722
                $data = fread($fhandle, $length);
723
                fclose($fhandle);
724
                header('HTTP/1.1 206 Partial Content');
725
                header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $size);
726
            }//HEADERS FOR PARTIAL DOWNLOAD FACILITY BEGINS
727
            //USUAL HEADERS FOR DOWNLOAD
728
            header('Content-Disposition: attachment;filename=' . $fileName);
729
            header('Content-Type: ' . $contentType);
730
            header('Accept-Ranges: bytes');
731
            header('Pragma: public');
732
            header('Expires: -1');
733
            header('Cache-Control: no-cache');
734
            header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
735
            header('Content-Length: ' . filesize($filePath));
736
            $chunksize = 8 * (1024 * 1024); //8MB (highest possible fread length)
737
            if ($size > $chunksize) {
738
                $handle = fopen($_FILES['file']['tmp_name'], 'rb');
739
                $buffer = '';
740
                while (!feof($handle) && (CONNECTION_NORMAL === connection_status())) {
741
                    $buffer = fread($handle, $chunksize);
742
                    print $buffer;
743
                    ob_flush();
744
                    flush();
745
                }
746
                if (CONNECTION_NORMAL !== connection_status()) {
747
                    //TODO traslation
748
                    echo 'Connection aborted';
749
                }
750
                fclose($handle);
751
            } else {
752
                ob_clean();
753
                flush();
754
                readfile($filePath);
755
            }
756
        } else {
757
            //TODO traslation
758
            echo 'File does not exist!';
759
        }
760
    } else {
761
        //TODO traslation
762
        echo 'There is no file to download!';
763
    }
764
}
765