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

letter.php (5 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
 * ****************************************************************************
26
 */
27
28
use Xmf\Request;
29
use XoopsModules\Xnewsletter;
30
31
$currentFile = basename(__FILE__);
32
require_once __DIR__ . '/header.php';
33
34
$helper = Xnewsletter\Helper::getInstance();
35
36
$uid    = (is_object($xoopsUser) && isset($xoopsUser)) ? $xoopsUser->uid() : 0;
37
$groups = is_object($xoopsUser) ? $xoopsUser->getGroups() : [0 => XOOPS_GROUP_ANONYMOUS];
38
39
$op        = Request::getString('op', 'list_letters');
40
$letter_id = Request::getInt('letter_id', 0);
41
$cat_id    = Request::getInt('cat_id', 0);
42
43
switch ($op) {
44
    case 'list_subscrs':
45
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter_list_subscrs.tpl";
46
        require_once XOOPS_ROOT_PATH . '/header.php';
47
48
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
49
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
50
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
51
        // breadcrumb
52
        $breadcrumb = new Xnewsletter\Breadcrumb();
53
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
54
        $breadcrumb->addLink(_MD_XNEWSLETTER_LIST_SUBSCR, '');
55
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
56
57
        // check right to edit/delete subscription of other persons
58
        $permissionChangeOthersSubscriptions = false;
59
        foreach ($groups as $group) {
60
            if (in_array($group, $helper->getConfig('xn_groups_change_other')) || XOOPS_GROUP_ADMIN == $group) {
61
                $permissionChangeOthersSubscriptions = true;
62
                break;
63
            }
64
        }
65
        $xoopsTpl->assign('permissionChangeOthersSubscriptions', $permissionChangeOthersSubscriptions);
66
        // get search subscriber form
67
        if ($permissionChangeOthersSubscriptions) {
68
            $subscrObj = $helper->getHandler('Subscr')->create();
69
            $xoopsTpl->assign('searchSubscriberForm', $subscrObj->getSearchForm('subscription.php')->render());
70
        } else {
71
            $xoopsTpl->assign('searchSubscriberForm', '');
72
        }
73
        // get cat objects
74
        $catCriteria = new \CriteriaCompo();
75
        $catCriteria->setSort('cat_id');
76
        $catCriteria->setOrder('ASC');
77
        $catObjs = $helper->getHandler('Cat')->getAll($catCriteria, null, true, true);
78
        // cats table
79
        foreach ($catObjs as $cat_id => $catObj) {
80
            $permissionShowCats[$cat_id] = $grouppermHandler->checkRight('newsletter_list_cat', $cat_id, $groups, $helper->getModule()->mid());
81
            if (true === $permissionShowCats[$cat_id]) {
82
                $cat_array         = $catObj->toArray();
83
                $catsubscrCriteria = new \CriteriaCompo();
84
                $catsubscrCriteria->add(new \Criteria('catsubscr_catid', $cat_id));
85
                $cat_array['catsubscrCount'] = $helper->getHandler('Catsubscr')->getCount($catsubscrCriteria);
86
                $xoopsTpl->append('cats', $cat_array);
87
            }
88
        }
89
        // get cat_id
90
        $cat_id = Request::getInt('cat_id', 0);
91
        $xoopsTpl->assign('cat_id', $cat_id);
92
        if ($cat_id > 0) {
93
            $catObj = $helper->getHandler('Cat')->get($cat_id);
94
            $xoopsTpl->assign('cat_name', $catObj->getVar('cat_name'));
95
            // subscrs table
96
            if (true === $permissionShowCats[$cat_id]) {
97
                $counter = 0;
98
                $sql     = 'SELECT `subscr_sex`, `subscr_lastname`, `subscr_firstname`, `subscr_email`, `subscr_id`';
99
                $sql     .= " FROM {$xoopsDB->prefix('xnewsletter_subscr')} INNER JOIN {$xoopsDB->prefix('xnewsletter_catsubscr')} ON `subscr_id` = `catsubscr_subscrid`";
100
                $sql     .= " WHERE (((`catsubscr_catid`)={$cat_id}) AND ((`catsubscr_quited`)=0)) ORDER BY `subscr_lastname`, `subscr_email`;";
101
                if (!$subscrs = $xoopsDB->query($sql)) {
102
                    die('MySQL-Error: ' . $GLOBALS['xoopsDB']->error());
103
                }
104
                while (null !== ($subscr_array = mysqli_fetch_assoc($subscrs))) {
105
                    $subscr_array['counter'] = ++$counter;
106
                    $xoopsTpl->append('subscrs', $subscr_array);
107
                }
108
            }
109
        }
110
        break;
111
    case 'show_preview':
112
    case 'show_letter_preview':
113
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter_preview.tpl";
114
        require_once XOOPS_ROOT_PATH . '/header.php';
115
116
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
117
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
118
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
119
        // breadcrumb
120
        $breadcrumb = new Xnewsletter\Breadcrumb();
121
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
122
        $breadcrumb->addLink(_MD_XNEWSLETTER_LIST, 'javascript:history.go(-1)');
123
        $breadcrumb->addLink(_MD_XNEWSLETTER_LETTER_PREVIEW, '');
124
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
125
126
        // get letter_id
127
        $letter_id = Request::getInt('letter_id', 0);
128
        // get letter object
129
        $letterObj = $helper->getHandler('Letter')->get($letter_id);
130
        // subscr data
131
        $xoopsTpl->assign('sex', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW);
132
        $xoopsTpl->assign('salutation', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW); // new from v1.3
133
        $xoopsTpl->assign('firstname', _AM_XNEWSLETTER_SUBSCR_FIRSTNAME_PREVIEW);
134
        $xoopsTpl->assign('lastname', _AM_XNEWSLETTER_SUBSCR_LASTNAME_PREVIEW);
135
        $xoopsTpl->assign('subscr_email', _AM_XNEWSLETTER_SUBSCR_EMAIL_PREVIEW);
136
        $xoopsTpl->assign('email', _AM_XNEWSLETTER_SUBSCR_EMAIL_PREVIEW); // new from v1.3
137
        // letter data
138
        $xoopsTpl->assign('title', $letterObj->getVar('letter_title', 'n')); // new from v1.3
139
        $xoopsTpl->assign('content', $letterObj->getVar('letter_content', 'n'));
140
        // letter attachments as link
141
        $attachmentAslinkCriteria = new \CriteriaCompo();
142
        $attachmentAslinkCriteria->add(new \Criteria('attachment_letter_id', $letter_id));
143
        $attachmentAslinkCriteria->add(new \Criteria('attachment_mode', _XNEWSLETTER_ATTACHMENTS_MODE_ASLINK));
144
        $attachmentAslinkCriteria->setSort('attachment_id');
145
        $attachmentAslinkCriteria->setOrder('ASC');
146
        $attachmentObjs = $helper->getHandler('Attachment')->getObjects($attachmentAslinkCriteria, true);
147 View Code Duplication
        foreach ($attachmentObjs as $attachment_id => $attachmentObj) {
148
            $attachment_array                    = $attachmentObj->toArray();
149
            $attachment_array['attachment_url']  = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
150
            $attachment_array['attachment_link'] = XNEWSLETTER_URL . "/attachment.php?attachment_id={$attachment_id}";
151
            $xoopsTpl->append('attachments', $attachment_array);
152
        }
153
        // extra data
154
        $xoopsTpl->assign('date', time()); // new from v1.3
155
        $xoopsTpl->assign('unsubscribe_url', XOOPS_URL . '/modules/xnewsletter/');
156
        $xoopsTpl->assign('catsubscr_id', '0');
157
158
        $letter_array = $letterObj->toArray();
159
160
        $templateObj = $helper->getHandler('Template')->get($letterObj->getVar('letter_templateid'));
161 View Code Duplication
        if (is_object($templateObj)) {
0 ignored issues
show
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...
162
            if ( (int)$templateObj->getVar('template_type') === _XNEWSLETTER_MAILINGLIST_TPL_CUSTOM_VAL) {
163
                // get template from database
164
                $htmlBody = $xoopsTpl->fetchFromData($templateObj->getVar('template_content', 'n'));
165
            } else {
166
                // get template from filesystem
167
                $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/' . $GLOBALS['xoopsConfig']['language'] . '/templates/';
168
                if (!is_dir($template_path)) {
169
                    $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/english/templates/';
170
                }
171
                $template = $template_path . $templateObj->getVar('template_title') . '.tpl';
172
                $htmlBody = $xoopsTpl->fetch($template);
173
            }
174
            try {
175
                $textBody = xnewsletter_html2text($htmlBody);
176
            }
177
            catch (Html2TextException $e) {
178
                $helper->addLog($e);
179
            }
180
        } else {
181
            $htmlBody = _AM_XNEWSLETTER_TEMPLATE_ERR;
182
        }
183
184
        $letter_array['letter_content_templated']      = $htmlBody;
185
        $letter_array['letter_content_templated_html'] = $htmlBody;
186
        $letter_array['letter_content_templated_text'] = $textBody; // new from v1.3
187
        $letter_array['letter_created_formatted']      = formatTimestamp($letterObj->getVar('letter_created'), $helper->getConfig('dateformat'));
188
        $letter_array['letter_submitter_name']         = \XoopsUserUtility::getUnameFromId($letterObj->getVar('letter_submitter'));
189
        $xoopsTpl->assign('letter', $letter_array);
190
        break;
191
    case 'print_letter':
192
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter_print.tpl";
193
        require_once XOOPS_ROOT_PATH . '/header.php';
194
195
        //$xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
196
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
197
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
198
199
        // get letter_id
200
        $letter_id = Request::getInt('letter_id', 0);
201
        // get letter object
202
        $letterObj = $helper->getHandler('Letter')->get($letter_id);
203
        // subscr data
204
        $xoopsTpl->assign('sex', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW);
205
        $xoopsTpl->assign('salutation', _AM_XNEWSLETTER_SUBSCR_SEX_PREVIEW); // new from v1.3
206
        $xoopsTpl->assign('firstname', _AM_XNEWSLETTER_SUBSCR_FIRSTNAME_PREVIEW);
207
        $xoopsTpl->assign('lastname', _AM_XNEWSLETTER_SUBSCR_LASTNAME_PREVIEW);
208
        $xoopsTpl->assign('subscr_email', _AM_XNEWSLETTER_SUBSCR_EMAIL_PREVIEW);
209
        $xoopsTpl->assign('email', _AM_XNEWSLETTER_SUBSCR_EMAIL_PREVIEW); // new from v1.3
210
        // letter data
211
        $xoopsTpl->assign('title', $letterObj->getVar('letter_title', 'n')); // new from v1.3
212
        $xoopsTpl->assign('content', $letterObj->getVar('letter_content', 'n'));
213
        // extra data
214
        $xoopsTpl->assign('date', time()); // new from v1.3
215
        $xoopsTpl->assign('unsubscribe_url', XOOPS_URL . '/modules/xnewsletter/');
216
        $xoopsTpl->assign('catsubscr_id', '0');
217
218
        $letter_array = $letterObj->toArray();
219
220
        $templateObj = $helper->getHandler('Template')->get($letterObj->getVar('letter_templateid'));
221 View Code Duplication
        if (is_object($templateObj)) {
0 ignored issues
show
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...
222
            if ( (int)$templateObj->getVar('template_type') === _XNEWSLETTER_MAILINGLIST_TPL_CUSTOM_VAL) {
223
                // get template from database
224
                $htmlBody = $xoopsTpl->fetchFromData($templateObj->getVar('template_content', 'n'));
225
            } else {
226
                // get template from filesystem
227
                $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/' . $GLOBALS['xoopsConfig']['language'] . '/templates/';
228
                if (!is_dir($template_path)) {
229
                    $template_path = XOOPS_ROOT_PATH . '/modules/xnewsletter/language/english/templates/';
230
                }
231
                $template = $template_path . $templateObj->getVar('template_title') . '.tpl';
232
                $htmlBody = $xoopsTpl->fetch($template);
233
            }
234
            try {
235
                $textBody = xnewsletter_html2text($htmlBody);
236
            }
237
            catch (Html2TextException $e) {
238
                $helper->addLog($e);
239
            }
240
        } else {
241
            $htmlBody = _AM_XNEWSLETTER_TEMPLATE_ERR;
242
        }
243
244
        $letter_array['letter_content_templated']      = $htmlBody;
245
        $letter_array['letter_content_templated_html'] = $htmlBody;
246
        $letter_array['letter_content_templated_text'] = $textBody; // new from v1.3
247
        $letter_array['letter_created_formatted']      = formatTimestamp($letterObj->getVar('letter_created'), $helper->getConfig('dateformat'));
248
        $letter_array['letter_submitter_name']         = \XoopsUserUtility::getUnameFromId($letterObj->getVar('letter_submitter'));
249
        $xoopsTpl->assign('letter', $letter_array);
250
        break;
251
    case 'list_letters':
252
    default:
253
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter_list_letters.tpl";
254
        require_once XOOPS_ROOT_PATH . '/header.php';
255
256
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
257
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
258
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
259
        // breadcrumb
260
        $breadcrumb = new Xnewsletter\Breadcrumb();
261
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
262
        $breadcrumb->addLink(_MD_XNEWSLETTER_LIST, '');
263
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
264
265
        // get letters array with right to read
266
        $letterCount = $helper->getHandler('Letter')->getCount();
267
        $letterObjs = $helper->getHandler('Letter')->getAll();
268
        $letter_filter = [];
269
        if ($letterCount > 0) {
270
            foreach ($letterObjs as $letter_id => $letterObj) {
271
                $userPermissions = xnewsletter_getUserPermissionsByLetter($letter_id);
272
                if (($userPermissions['read'] && $letterObj->getVar('letter_sent') > 0)
273
                    || (true === $userPermissions['send'])) {
274
                    $letter_cat_ids = explode('|', $letterObj->getVar('letter_cats'));
275
                    // skip letter
276
                    if ((0 != $cat_id) && !in_array($cat_id, $letter_cat_ids)) {
277
                        continue;
278
                    }
279
                    // get categories
280 View Code Duplication
                    foreach ($letter_cat_ids as $letter_cat_id) {
0 ignored issues
show
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...
281
                        $catObj = $helper->getHandler('Cat')->get($letter_cat_id);
282
                        if ($grouppermHandler->checkRight('newsletter_read_cat', $catObj->getVar('cat_id'), $groups, $helper->getModule()->mid())) {
283
                            $letter_filter[] = $letterObj->getVar('letter_id');
284
                        }
285
                        unset($catObj);
286
                    }
287
                }
288
            }
289
        }
290
291
        // get letters array
292
        $letterCriteria = new \CriteriaCompo();
293
        $letterCriteria->add(new \Criteria('letter_id', '(' . implode(',', $letter_filter) . ')', 'IN'));
294
        $letterCriteria->setSort('letter_id');
295
        $letterCriteria->setOrder('DESC');
296
        $letterCount = $helper->getHandler('Letter')->getCount($letterCriteria);
297
        $start       = Request::getInt('start', 0);
298
        $limit       = $helper->getConfig('adminperpage');
299
        $letterCriteria->setStart($start);
300
        $letterCriteria->setLimit($limit);
301
        $letterObjs = $helper->getHandler('Letter')->getAll($letterCriteria, null, true, true);
302
303
        // pagenav
304 View Code Duplication
        if ($letterCount > $limit) {
0 ignored issues
show
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...
305
            $pagenav = new \XoopsPageNav($letterCount, $limit, $start, 'start', "op={$op}");
306
            $xoopsTpl->assign('pagenav', $pagenav->renderNav());
307
        }
308
309
310
        // letters table
311
        $showAdminColumns = false;
312
        if ($letterCount > 0) {
313
            foreach ($letterObjs as $letter_id => $letterObj) {
314
                $userPermissions = xnewsletter_getUserPermissionsByLetter($letter_id);
315
                $letter_array                             = $letterObj->toArray();
316
                $letter_array['letter_created_formatted'] = formatTimestamp($letterObj->getVar('letter_created'), $helper->getConfig('dateformat'));
317
                $letter_array['letter_submitter_name']    = \XoopsUserUtility::getUnameFromId($letterObj->getVar('letter_submitter'));
318
                $letter_array['letter_sent_formatted']    = 0 != $letterObj->getVar('letter_sent') ? formatTimestamp($letterObj->getVar('letter_sent'), $helper->getConfig('dateformat')) : '';
319
                $letter_array['letter_sender_name']       = \XoopsUserUtility::getUnameFromId($letterObj->getVar('letter_sender'));
320
                
321
                $letter['template_title'] = $helper->getHandler('Template')->get($letterObj->getVar('letter_templateid'))->getVar('template_title');
322
323
                $letter_cat_ids = explode('|', $letterObj->getVar('letter_cats'));
324
                // skip letter
325
                if ((0 != $cat_id) && !in_array($cat_id, $letter_cat_ids)) {
326
                    continue;
327
                }
328
                // get categories
329
                unset($letter_array['letter_cats']); // IN PROGRESS
330 View Code Duplication
                foreach ($letter_cat_ids as $letter_cat_id) {
0 ignored issues
show
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...
331
                    $catObj = $helper->getHandler('Cat')->get($letter_cat_id);
332
                    if ($grouppermHandler->checkRight('newsletter_read_cat', $catObj->getVar('cat_id'), $groups, $helper->getModule()->mid())) {
333
                        $letter_array['letter_cats'][] = $catObj->toArray();
334
                    }
335
                    unset($catObj);
336
                }
337
                // count letter attachements
338
                $attachmentCriteria = new \CriteriaCompo();
339
                $attachmentCriteria->add(new \Criteria('attachment_letter_id', $letterObj->getVar('letter_id')));
340
                $letter_array['attachmentCount'] = $helper->getHandler('Attachment')->getCount($attachmentCriteria);
341
                // get protocols
342
                if ($userPermissions['edit']) {
343
                    // take last item protocol_subscriber_id=0 from table protocol as actual status
344
                    $protocolCriteria = new \CriteriaCompo();
345
                    $protocolCriteria->add(new \Criteria('protocol_letter_id', $letterObj->getVar('letter_id')));
346
                    //$criteria->add(new \Criteria('protocol_subscriber_id', '0'));
347
                    $protocolCriteria->setSort('protocol_id');
348
                    $protocolCriteria->setOrder('DESC');
349
                    $protocolCriteria->setLimit(1);
350
                    $protocolObjs       = $helper->getHandler('Protocol')->getAll($protocolCriteria);
351
                    $protocol_status    = '';
352
                    $protocol_letter_id = 0;
353
                    foreach ($protocolObjs as $protocolObj) {
354
                        $letter_array['protocols'][] = [
355
                            'protocol_status'    => $protocolObj->getVar('protocol_status'),
356
                            'protocol_letter_id' => $protocolObj->getVar('protocol_letter_id'),
357
                        ];
358
                    }
359
                }
360
                // check if table show admin columns
361
                if ((true === $userPermissions['edit']) || (true === $userPermissions['delete'])
362
                    || (true === $userPermissions['create'])
363
                    || (true === $userPermissions['send'])) {
364
                    $showAdminColumns = true;
365
                }
366
                $letter_array['userPermissions'] = $userPermissions;
367
                $xoopsTpl->append('letters', $letter_array);
368
            }
369
        }
370
        $xoopsTpl->assign('showAdminColumns', $showAdminColumns);
371
        break;
372 View Code Duplication
    case 'new_letter':
373
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter.tpl"; // IN PROGRESS
374
        require_once XOOPS_ROOT_PATH . '/header.php';
375
376
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
377
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
378
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
379
        // breadcrumb
380
        $breadcrumb = new Xnewsletter\Breadcrumb();
381
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
382
        $breadcrumb->addLink(_MD_XNEWSLETTER_LETTER_CREATE, '');
383
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
384
385
        /** @var Xnewsletter\Letter $letterObj */
386
        $letterObj = $helper->getHandler('Letter')->create();
387
        /** @var \XoopsThemeForm $form */
388
        $form    = $letterObj->getForm();
389
        $content = $form->render();
390
        $xoopsTpl->assign('content', $content);
391
        break;
392 View Code Duplication
    case 'edit_letter':
393
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter.tpl";
394
        require_once XOOPS_ROOT_PATH . '/header.php';
395
396
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
397
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
398
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
399
        // breadcrumb
400
        $breadcrumb = new Xnewsletter\Breadcrumb();
401
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
402
        $breadcrumb->addLink(_MD_XNEWSLETTER_LIST, 'javascript:history.go(-1)');
403
        $breadcrumb->addLink(_MD_XNEWSLETTER_LETTER_EDIT, '');
404
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
405
406
        $letterObj = $helper->getHandler('Letter')->get($letter_id);
407
        $form      = $letterObj->getForm();
408
        $content   = $form->render();
409
        $xoopsTpl->assign('content', $content);
410
        break;
411
    case 'delete_attachment':
412
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter.tpl";
413
        require_once XOOPS_ROOT_PATH . '/header.php';
414
415
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
416
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
417
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
418
        // breadcrumb
419
        $breadcrumb = new Xnewsletter\Breadcrumb();
420
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
421
        $breadcrumb->addLink(_MD_XNEWSLETTER_LIST, 'javascript:history.go(-1)');
422
        $breadcrumb->addLink(_MD_XNEWSLETTER_LETTER_EDIT, '');
423
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
424
425
        // update existing_attachments
426
        $existing_attachments_mode = Request::getArray('existing_attachments_mode', []);
427
        foreach ($existing_attachments_mode as $attachment_id => $attachment_mode) {
428
            $attachmentObj = $helper->getHandler('Attachment')->get($attachment_id);
429
            $attachmentObj->setVar('attachment_mode', $attachment_mode);
430
            $helper->getHandler('Attachment')->insert($attachmentObj);
431
        }
432
433
        $attachment_id = Request::getInt('deleted_attachment_id', 0, 'POST');
434
        if (0 == $attachment_id) {
435
            redirect_header($currentFile, 3, _AM_XNEWSLETTER_LETTER_ERROR_INVALID_ATT_ID);
436
        }
437
        $attachmentObj   = $helper->getHandler('Attachment')->get($attachment_id);
438
        $attachment_name = $attachmentObj->getVar('attachment_name');
439
440
        if ($helper->getHandler('Attachment')->delete($attachmentObj, true)) {
441
            $letterObj = $helper->getHandler('Letter')->get($letter_id);           
442
            $letterObj->setVar('letter_title',      Request::getString('letter_title', ''));
443
            $letterObj->setVar('letter_content',    Request::getText('letter_content', ''));
444
            $letterObj->setVar('letter_templateid', Request::getInt('letter_templateid', 0));
445
            $letterObj->setVar('letter_cats',       implode('|', Request::getArray('letter_cats', [])));
446
            $letterObj->setVar('letter_account',    Request::getInt('letter_account', 0));
447
            $letterObj->setVar('letter_email_test', Request::getString('letter_email_test', ''));
448
449
            $form    = $letterObj->getForm(false, true);
450
            $content = $form->render();
451
            $xoopsTpl->assign('content', $content);
452
        } else {
453
            $content = $attachmentObj->getHtmlErrors();
454
            $xoopsTpl->assign('content', $content);
455
        }
456
        break;
457
    case 'save_letter':
458
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_empty.tpl";
459
        require_once XOOPS_ROOT_PATH . '/header.php';
460
461
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
462
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
463
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
464
        // breadcrumb
465
        $breadcrumb = new Xnewsletter\Breadcrumb();
466
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
467
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
468
469
        if (!$GLOBALS['xoopsSecurity']->check()) {
470
            redirect_header($currentFile, 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
471
        }
472
        $letterObj = $helper->getHandler('Letter')->get($letter_id); // create if doesn't exist
473
        $letterObj->setVar('letter_title',      Request::getString('letter_title', ''));
474
        $letterObj->setVar('letter_content',    Request::getText('letter_content', ''));
475
        $letterObj->setVar('letter_templateid', Request::getInt('letter_templateid', 0));
476
        $letterObj->setVar('letter_cats',       implode('|', Request::getArray('letter_cats', [])));
477
        $letterObj->setVar('letter_account',    Request::getInt('letter_account', 0));
478
        $letterObj->setVar('letter_email_test', Request::getString('letter_email_test', ''));
479
        $letterObj->setVar('letter_submitter',  Request::getInt('letter_submitter', 0));
480
        $letterObj->setVar('letter_created',    Request::getInt('letter_created', time()));
481
482 View Code Duplication
        if ($helper->getHandler('Letter')->insert($letterObj)) {
483
            $letter_id = $letterObj->getVar('letter_id');
484
            // update existing_attachments
485
            $existing_attachments_mode = Request::getArray('existing_attachments_mode', []);
486
            foreach ($existing_attachments_mode as $attachment_id => $attachment_mode) {
487
                $attachmentObj = $helper->getHandler('Attachment')->get($attachment_id);
488
                $attachmentObj->setVar('attachment_mode', $attachment_mode);
489
                $helper->getHandler('Attachment')->insert($attachmentObj);
490
            }
491
            // upload attachments
492
            $uploadedFiles = [];
493
            require_once XOOPS_ROOT_PATH . '/class/uploader.php';
494
            $uploaddir = XOOPS_UPLOAD_PATH . $helper->getConfig('xn_attachment_path') . $letter_id . '/';
495
            // check upload_dir
496
            if (!is_dir($uploaddir)) {
497
                $indexFile = XOOPS_UPLOAD_PATH . '/index.html';
498
                if (!mkdir($uploaddir, 0777) && !is_dir($uploaddir)) {
499
                    throw new \RuntimeException(sprintf('Directory "%s" was not created', $uploaddir));
500
                }
501
                chmod($uploaddir, 0777);
502
                copy($indexFile, $uploaddir . 'index.html');
503
            }
504
            $new_attachments_mode = Request::getArray('new_attachments_mode', []);
505
            for ($upl = 0; $upl < $helper->getConfig('xn_maxattachments'); ++$upl) {
506
                $uploader = new \XoopsMediaUploader($uploaddir, $helper->getConfig('xn_mimetypes'), $helper->getConfig('xn_maxsize'), null, null);
507
                if ($uploader->fetchMedia(@$_POST['xoops_upload_file'][$upl])) {
508
                    //$uploader->setPrefix("xn_") ; keep original name
509
                    $uploader->fetchMedia($_POST['xoops_upload_file'][$upl]);
510
                    if (!$uploader->upload()) {
511
                        $errors = $uploader->getErrors();
512
                        redirect_header('<script>javascript:history.go(-1)</script>', 3, $errors);
513
                    } else {
514
                        preg_match('/ne\w_attachment_index=([0-9]+)/', $_POST['xoops_upload_file'][$upl], $matches);
515
                        $index           = $matches[1];
516
                        $uploadedFiles[] = [
517
                            'name' => $uploader->getSavedFileName(),
518
                            'type' => $uploader->getMediaType(),
519
                            'size' => $uploader->getMediaSize(),
520
                            'mode' => $new_attachments_mode[$index],
521
                        ];
522
                    }
523
                }
524
            }
525
            // create items in attachments
526
            foreach ($uploadedFiles as $file) {
527
                $attachmentObj = $helper->getHandler('Attachment')->create();
528
                $attachmentObj->setVar('attachment_letter_id', $letter_id);
529
                $attachmentObj->setVar('attachment_name', $file['name']);
530
                $attachmentObj->setVar('attachment_type', $file['type']);
531
                $attachmentObj->setVar('attachment_submitter', $xoopsUser->uid());
532
                $attachmentObj->setVar('attachment_created', time());
533
                $attachmentObj->setVar('attachment_size', $file['size']);
534
                $attachmentObj->setVar('attachment_mode', $file['mode']);
535
536
                $helper->getHandler('Attachment')->insert($attachmentObj);
537
            }
538
            // create item in protocol
539
            $protocolObj = $helper->getHandler('Protocol')->create();
540
            $protocolObj->setVar('protocol_letter_id', $letter_id);
541
            $protocolObj->setVar('protocol_subscriber_id', 0);
542
            $protocolObj->setVar('protocol_success', true);
543
            $action = Request::getInt('letter_action', _XNEWSLETTER_LETTER_ACTION_VAL_NO);
544
            switch ($action) {
545
                case _XNEWSLETTER_LETTER_ACTION_VAL_PREVIEW:
546
                    $redirectUrl = "?op=show_preview&letter_id={$letter_id}";
547
                    break;
548
                case _XNEWSLETTER_LETTER_ACTION_VAL_SEND:
549
                    $redirectUrl = "sendletter.php?op=send_letter&letter_id={$letter_id}";
550
                    break;
551
                case _XNEWSLETTER_LETTER_ACTION_VAL_SENDTEST:
552
                    $redirectUrl = "sendletter.php?op=send_test&letter_id={$letter_id}";
553
                    break;
554
                default:
555
                    $redirectUrl = '?op=list_letters';
556
                    break;
557
            }
558
            $protocolObj->setVar('protocol_status', _AM_XNEWSLETTER_LETTER_ACTION_SAVED);
559
            $protocolObj->setVar('protocol_status_str_id', _XNEWSLETTER_PROTOCOL_STATUS_SAVED); // new from v1.3
560
            $protocolObj->setVar('protocol_status_vars', []); // new from v1.3
561
            $protocolObj->setVar('protocol_submitter', $xoopsUser->uid());
562
            $protocolObj->setVar('protocol_created', time());
563
564
            if ($helper->getHandler('Protocol')->insert($protocolObj)) {
565
                // create protocol is ok
566
                redirect_header($redirectUrl, 3, _AM_XNEWSLETTER_FORMOK);
567
            } else {
568
                $GLOBALS['xoopsTpl']->assign('error', 'Error create protocol: ' . $protocolObj->getHtmlErrors());
569
            }
570
        } else {
571
            $GLOBALS['xoopsTpl']->assign('error', 'Error create letter: ' . $protocolObj->getHtmlErrors());
572
        }
573
        break;
574
    case 'copy_letter':
575
    case 'clone_letter':
576
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_letter.tpl";
577
        require_once XOOPS_ROOT_PATH . '/header.php';
578
579
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
580
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
581
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
582
        // breadcrumb
583
        $breadcrumb = new Xnewsletter\Breadcrumb();
584
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
585
        $breadcrumb->addLink(_MD_XNEWSLETTER_LIST, 'javascript:history.go(-1)');
586
        $breadcrumb->addLink(_MD_XNEWSLETTER_LETTER_COPY, '');
587
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
588
589
        $oldLetterObj = $helper->getHandler('Letter')->get($letter_id);
590
        $newLetterObj = $helper->getHandler('Letter')->create();
591
        $newLetterObj->setVar('letter_title',      sprintf(_AM_XNEWSLETTER_LETTER_CLONED, $oldLetterObj->getVar('letter_title')));
592
        $newLetterObj->setVar('letter_content',    $oldLetterObj->getVar('letter_content', 'n'));
593
        $newLetterObj->setVar('letter_template',   $oldLetterObj->getVar('letter_template'));
594
        $newLetterObj->setVar('letter_cats',       $oldLetterObj->getVar('letter_cats'));
595
        $newLetterObj->setVar('letter_account',    $oldLetterObj->getVar('letter_account'));
596
        $newLetterObj->setVar('letter_email_test', $oldLetterObj->getVar('letter_email_test'));
597
        unset($oldLetterObj);
598
        $action  = XOOPS_URL . "/modules/xnewsletter/{$currentFile}?op=copy_letter";
599
        $form    = $newLetterObj->getForm($action);
600
        $content = $form->render();
601
        $xoopsTpl->assign('content', $content);
602
        break;
603
    case 'delete_letter':
604
        $GLOBALS['xoopsOption']['template_main'] = "{$helper->getModule()->dirname()}_empty.tpl";
605
        require_once XOOPS_ROOT_PATH . '/header.php';
606
607
        $xoTheme->addStylesheet(XNEWSLETTER_URL . '/assets/css/module.css');
608
        $xoTheme->addMeta('meta', 'keywords', $helper->getConfig('keywords')); // keywords only for index page
609
        $xoTheme->addMeta('meta', 'description', strip_tags(_MA_XNEWSLETTER_DESC)); // description
610
        // breadcrumb
611
        $breadcrumb = new Xnewsletter\Breadcrumb();
612
        $breadcrumb->addLink($helper->getModule()->getVar('name'), XNEWSLETTER_URL);
613
        $breadcrumb->addLink(_MD_XNEWSLETTER_LIST, 'javascript:history.go(-1)');
614
        $breadcrumb->addLink(_MD_XNEWSLETTER_LETTER_DELETE, '');
615
        $xoopsTpl->assign('xnewsletter_breadcrumb', $breadcrumb->render());
616
617
        // IN PROGRESS FROM HERE
618
619
        $letterObj = $helper->getHandler('Letter')->get($letter_id);
620 View Code Duplication
        if (true === Request::getBool('ok', false, 'POST')) {
621
            if (!$GLOBALS['xoopsSecurity']->check()) {
622
                redirect_header($currentFile, 3, implode(',', $GLOBALS['xoopsSecurity']->getErrors()));
623
            }
624
            if ($helper->getHandler('Letter')->delete($letterObj)) {
625
                //delete protocols
626
                $sql = 'DELETE';
627
                $sql .= " FROM `{$xoopsDB->prefix('xnewsletter_protocol')}`";
628
                $sql .= " WHERE `protocol_letter_id`={$letter_id}";
629
                if (!$result = $xoopsDB->query($sql)) {
630
                    die('MySQL-Error: ' . $GLOBALS['xoopsDB']->error());
631
                }
632
                // delete attachments
633
                $attachmentCriteria = new \Criteria('attachment_letter_id', $letter_id);
634
                $helper->getHandler('Attachment')->deleteAll($attachmentCriteria, true, true);
635
                redirect_header($currentFile, 3, _AM_XNEWSLETTER_FORMDELOK);
636
            } else {
637
                $GLOBALS['xoopsTpl']->assign('error', $letterObj->getHtmlErrors());
638
            }
639
        } else {
640
            xoops_confirm(['ok' => true, 'letter_id' => $letter_id, 'op' => 'delete_letter'], $_SERVER['REQUEST_URI'], sprintf(_AM_XNEWSLETTER_FORMSUREDEL, $letterObj->getVar('letter_title')));
641
        }
642
        break;
643
}
644
645
require_once __DIR__ . '/footer.php';
646