Passed
Branch master (026829)
by Michael
03:14
created

Utility::editFile()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 22
c 1
b 0
f 0
nc 6
nop 3
dl 0
loc 37
rs 9.568
1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Publisher;
6
7
/*
8
 You may not change or alter any portion of this comment or credits
9
 of supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit authors.
11
12
 This program is distributed in the hope that it will be useful,
13
 but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
 */
16
17
/**
18
 * PublisherUtil Class
19
 *
20
 * @copyright   XOOPS Project (https://xoops.org)
21
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
22
 * @author      XOOPS Development Team
23
 * @since       1.03
24
 */
25
26
use Xmf\Request;
27
28
/**
29
 * Class Utility
30
 */
31
class Utility extends Common\SysUtility
32
{
33
    //--------------- Custom module methods -----------------------------
34
    /**
35
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
36
     *
37
     * @param string $folder The full path of the directory to check
38
     */
39
    public static function createFolder($folder)
40
    {
41
        try {
42
            if (!\is_dir($folder)) {
43
                if (!\is_dir($folder) && !\mkdir($folder) && !\is_dir($folder)) {
44
                    throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
45
                }
46
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
47
            }
48
        } catch (\Throwable $e) {
49
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
50
        }
51
    }
52
53
    /**
54
     * @param $file
55
     * @param $folder
56
     * @return bool
57
     */
58
    public static function copyFile($file, $folder)
59
    {
60
        return \copy($file, $folder);
61
        //        try {
62
        //            if (!is_dir($folder)) {
63
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
64
        //            } else {
65
        //                return copy($file, $folder);
66
        //            }
67
        //        } catch (\Exception $e) {
68
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br>";
69
        //        }
70
        //        return false;
71
    }
72
73
    /**
74
     * @param $src
75
     * @param $dst
76
     */
77
    public static function recurseCopy($src, $dst)
78
    {
79
        $dir = \opendir($src);
80
        //    @mkdir($dst);
81
        while (false !== ($file = \readdir($dir))) {
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of readdir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

81
        while (false !== ($file = \readdir(/** @scrutinizer ignore-type */ $dir))) {
Loading history...
82
            if (('.' !== $file) && ('..' !== $file)) {
83
                if (\is_dir($src . '/' . $file)) {
84
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
85
                } else {
86
                    \copy($src . '/' . $file, $dst . '/' . $file);
87
                }
88
            }
89
        }
90
        \closedir($dir);
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

90
        \closedir(/** @scrutinizer ignore-type */ $dir);
Loading history...
91
    }
92
93
    // auto create folders----------------------------------------
94
    //TODO rename this function? And exclude image folder?
95
    public static function createDir()
96
    {
97
        // auto crate folders
98
        //        $thePath = static::getUploadDir();
99
100
        if (static::getPathStatus('root', true) < 0) {
101
            $thePath = static::getUploadDir();
102
            $res     = static::mkdir($thePath);
103
            $msg     = $res ? \_AM_PUBLISHER_DIRCREATED : \_AM_PUBLISHER_DIRNOTCREATED;
0 ignored issues
show
Unused Code introduced by
The assignment to $msg is dead and can be removed.
Loading history...
104
        }
105
106
        if (static::getPathStatus('images', true) < 0) {
107
            $thePath = static::getImageDir();
108
            $res     = static::mkdir($thePath);
109
110
            if ($res) {
111
                $source = PUBLISHER_ROOT_PATH . '/assets/images/blank.png';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
112
                $dest   = $thePath . 'blank.png';
113
                static::copyr($source, $dest);
114
            }
115
            $msg = $res ? \_AM_PUBLISHER_DIRCREATED : \_AM_PUBLISHER_DIRNOTCREATED;
116
        }
117
118
        if (static::getPathStatus('images/category', true) < 0) {
119
            $thePath = static::getImageDir('category');
120
            $res     = static::mkdir($thePath);
121
122
            if ($res) {
123
                $source = PUBLISHER_ROOT_PATH . '/assets/images/blank.png';
124
                $dest   = $thePath . 'blank.png';
125
                static::copyr($source, $dest);
126
            }
127
            $msg = $res ? \_AM_PUBLISHER_DIRCREATED : \_AM_PUBLISHER_DIRNOTCREATED;
128
        }
129
130
        if (static::getPathStatus('images/item', true) < 0) {
131
            $thePath = static::getImageDir('item');
132
            $res     = static::mkdir($thePath);
133
134
            if ($res) {
135
                $source = PUBLISHER_ROOT_PATH . '/assets/images/blank.png';
136
                $dest   = $thePath . 'blank.png';
137
                static::copyr($source, $dest);
138
            }
139
            $msg = $res ? \_AM_PUBLISHER_DIRCREATED : \_AM_PUBLISHER_DIRNOTCREATED;
140
        }
141
142
        if (static::getPathStatus('content', true) < 0) {
143
            $thePath = static::getUploadDir(true, 'content');
144
            $res     = static::mkdir($thePath);
145
            $msg     = $res ? \_AM_PUBLISHER_DIRCREATED : \_AM_PUBLISHER_DIRNOTCREATED;
146
        }
147
    }
148
149
    public static function buildTableItemTitleRow()
150
    {
151
        echo "<table width='100%' cellspacing='1' cellpadding='3' border='0' class='outer'>";
152
        echo '<tr>';
153
        echo "<th width='40px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_ITEMID . '</strong></td>';
154
        echo "<th width='100px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_ITEMCAT . '</strong></td>';
155
        echo "<th class='bg3' align='center'><strong>" . \_AM_PUBLISHER_TITLE . '</strong></td>';
156
        echo "<th width='100px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_CREATED . '</strong></td>';
157
158
        echo "<th width='50px' class='bg3' align='center'><strong>" . \_CO_PUBLISHER_WEIGHT . '</strong></td>';
159
        echo "<th width='50px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_HITS . '</strong></td>';
160
        echo "<th width='60px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_RATE . '</strong></td>';
161
        echo "<th width='50px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_VOTES . '</strong></td>';
162
        echo "<th width='60px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_COMMENTS_COUNT . '</strong></td>';
163
164
        echo "<th width='90px' class='bg3' align='center'><strong>" . \_CO_PUBLISHER_STATUS . '</strong></td>';
165
        echo "<th width='90px' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_ACTION . '</strong></td>';
166
        echo '</tr>';
167
    }
168
169
    /**
170
     * @param Category $categoryObj
171
     * @param int      $level
172
     */
173
    public static function displayCategory(Category $categoryObj, $level = 0)
174
    {
175
        $helper = Helper::getInstance();
176
177
        $description = $categoryObj->description;
178
        if (!XOOPS_USE_MULTIBYTES && !empty($description)) {
179
            if (\mb_strlen($description) >= 100) {
180
                $description = \mb_substr($description, 0, 100 - 1) . '...';
0 ignored issues
show
Unused Code introduced by
The assignment to $description is dead and can be removed.
Loading history...
181
            }
182
        }
183
        $modify = "<a href='category.php?op=mod&amp;categoryid=" . $categoryObj->categoryid() . '&amp;parentid=' . $categoryObj->parentid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/edit.gif' title='" . \_AM_PUBLISHER_EDITCOL . "' alt='" . \_AM_PUBLISHER_EDITCOL . "'></a>";
0 ignored issues
show
Bug introduced by
The method parentid() does not exist on XoopsModules\Publisher\Category. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

183
        $modify = "<a href='category.php?op=mod&amp;categoryid=" . $categoryObj->categoryid() . '&amp;parentid=' . $categoryObj->/** @scrutinizer ignore-call */ parentid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/edit.gif' title='" . \_AM_PUBLISHER_EDITCOL . "' alt='" . \_AM_PUBLISHER_EDITCOL . "'></a>";
Loading history...
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The method categoryid() does not exist on XoopsModules\Publisher\Category. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

183
        $modify = "<a href='category.php?op=mod&amp;categoryid=" . $categoryObj->/** @scrutinizer ignore-call */ categoryid() . '&amp;parentid=' . $categoryObj->parentid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/edit.gif' title='" . \_AM_PUBLISHER_EDITCOL . "' alt='" . \_AM_PUBLISHER_EDITCOL . "'></a>";
Loading history...
184
        $delete = "<a href='category.php?op=del&amp;categoryid=" . $categoryObj->categoryid() . "'><img src='" . PUBLISHER_URL . "/assets/images/links/delete.png' title='" . \_AM_PUBLISHER_DELETECOL . "' alt='" . \_AM_PUBLISHER_DELETECOL . "'></a>";
185
        $spaces = \str_repeat('&nbsp;', ($level * 3));
186
        /*
187
        $spaces = '';
188
        for ($j = 0; $j < $level; ++$j) {
189
            $spaces .= '&nbsp;&nbsp;&nbsp;';
190
        }
191
        */
192
        echo "<tr>\n"
193
             . "<td class='even center'>"
194
             . $categoryObj->categoryid()
195
             . "</td>\n"
196
             . "<td class='even left'>"
197
             . $spaces
198
             . "<a href='"
199
             . PUBLISHER_URL
200
             . '/category.php?categoryid='
201
             . $categoryObj->categoryid()
202
             . "'><img src='"
203
             . PUBLISHER_URL
204
             . "/assets/images/links/subcat.gif' alt=''>&nbsp;"
205
             . $categoryObj->name()
0 ignored issues
show
Bug introduced by
The method name() does not exist on XoopsModules\Publisher\Category. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

205
             . $categoryObj->/** @scrutinizer ignore-call */ name()
Loading history...
206
             . "</a></td>\n"
207
             . "<td class='even center'>"
208
             . $categoryObj->weight()
0 ignored issues
show
Bug introduced by
The method weight() does not exist on XoopsModules\Publisher\Category. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

208
             . $categoryObj->/** @scrutinizer ignore-call */ weight()
Loading history...
209
             . "</td>\n"
210
             . "<td class='even center'> {$modify} {$delete} </td>\n"
211
             . "</tr>\n";
212
        $subCategoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $categoryObj->categoryid());
213
        if (\count($subCategoriesObj) > 0) {
214
            ++$level;
215
            foreach ($subCategoriesObj as $thiscat) {
216
                self::displayCategory($thiscat, $level);
217
            }
218
            unset($key);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key seems to be never defined.
Loading history...
219
        }
220
        //        unset($categoryObj);
221
    }
222
223
224
    /**
225
     * @param bool $showmenu
226
     * @param int  $fileid
227
     * @param int  $itemId
228
     */
229
    public static function editFile($showmenu = false, $fileid = 0, $itemId = 0)
0 ignored issues
show
Unused Code introduced by
The parameter $showmenu is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

229
    public static function editFile(/** @scrutinizer ignore-unused */ $showmenu = false, $fileid = 0, $itemId = 0)

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

Loading history...
230
    {
231
        $helper = Helper::getInstance();
232
        require_once $GLOBALS['xoops']->path('class/xoopsformloader.php');
233
234
        // if there is a parameter, and the id exists, retrieve data: we're editing a file
235
        if (0 != $fileid) {
236
            // Creating the File object
237
            /** @var \XoopsModules\Publisher\File $fileObj */
238
            $fileObj = $helper->getHandler('File')->get($fileid);
239
240
            if ($fileObj->notLoaded()) {
241
                redirect_header('<script>javascript:history.go(-1)</script>', 1, _AM_PUBLISHER_NOFILESELECTED);
242
            }
243
244
            echo "<br>\n";
245
            echo "<span style='color: #2F5376; font-weight: bold; font-size: 16px; margin: 6px 6px 0 0; '>" . _AM_PUBLISHER_FILE_EDITING . '</span>';
246
            echo '<span style="color: #567; margin: 3px 0 12px 0; font-size: small; display: block; ">' . _AM_PUBLISHER_FILE_EDITING_DSC . '</span>';
247
            static::openCollapsableBar('editfile', 'editfileicon', _AM_PUBLISHER_FILE_INFORMATIONS);
248
        } else {
249
            // there's no parameter, so we're adding an item
250
            $fileObj = $helper->getHandler('File')->create();
251
            $fileObj->setVar('itemid', $itemId);
252
            echo "<span style='color: #2F5376; font-weight: bold; font-size: 16px; margin: 6px 6px 0 0; '>" . _AM_PUBLISHER_FILE_ADDING . '</span>';
253
            echo '<span style="color: #567; margin: 3px 0 12px 0; font-size: small; display: block; ">' . _AM_PUBLISHER_FILE_ADDING_DSC . '</span>';
254
            static::openCollapsableBar('addfile', 'addfileicon', _AM_PUBLISHER_FILE_INFORMATIONS);
255
        }
256
257
        // FILES UPLOAD FORM
258
        /** @var File $fileObj */
259
        $uploadForm = $fileObj->getForm();
260
        $uploadForm->display();
261
262
        if (0 != $fileid) {
263
            static::closeCollapsableBar('editfile', 'editfileicon');
264
        } else {
265
            static::closeCollapsableBar('addfile', 'addfileicon');
266
        }
267
    }
268
269
    /**
270
     * @param bool          $showmenu
271
     * @param int           $categoryId
272
     * @param int           $nbSubCats
273
     * @param Category|null $categoryObj
274
     */
275
    public static function editCategory($showmenu = false, $categoryId = 0, $nbSubCats = 4, $categoryObj = null)
0 ignored issues
show
Unused Code introduced by
The parameter $showmenu is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

275
    public static function editCategory(/** @scrutinizer ignore-unused */ $showmenu = false, $categoryId = 0, $nbSubCats = 4, $categoryObj = null)

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

Loading history...
276
    {
277
        $helper = Helper::getInstance();
278
279
        // if there is a parameter, and the id exists, retrieve data: we're editing a category
280
        /** @var  Category $categoryObj */
281
        if (0 != $categoryId) {
282
            // Creating the category object for the selected category
283
            $categoryObj = $helper->getHandler('Category')->get($categoryId);
284
            if ($categoryObj->notLoaded()) {
0 ignored issues
show
Bug introduced by
The method notLoaded() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Publisher\Item or XoopsModules\Publisher\File or XoopsModules\Publisher\Category. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

284
            if ($categoryObj->/** @scrutinizer ignore-call */ notLoaded()) {
Loading history...
285
                \redirect_header('category.php', 1, \_AM_PUBLISHER_NOCOLTOEDIT);
286
            }
287
        } elseif (null === $categoryObj) {
288
            $categoryObj = $helper->getHandler('Category')->create();
289
        }
290
291
        if (0 != $categoryId) {
292
            echo "<br>\n";
293
            static::openCollapsableBar('edittable', 'edittableicon', \_AM_PUBLISHER_EDITCOL, \_AM_PUBLISHER_CATEGORY_EDIT_INFO);
294
        } else {
295
            static::openCollapsableBar('createtable', 'createtableicon', \_AM_PUBLISHER_CATEGORY_CREATE, \_AM_PUBLISHER_CATEGORY_CREATE_INFO);
296
        }
297
298
        $sform = $categoryObj->getForm($nbSubCats);
299
        $sform->display();
300
301
        if ($categoryId) {
302
            static::closeCollapsableBar('edittable', 'edittableicon');
303
        } else {
304
            static::closeCollapsableBar('createtable', 'createtableicon');
305
        }
306
307
        //Added by fx2024
308
        if ($categoryId) {
309
            $selCat = $categoryId;
310
311
            static::openCollapsableBar('subcatstable', 'subcatsicon', \_AM_PUBLISHER_SUBCAT_CAT, \_AM_PUBLISHER_SUBCAT_CAT_DSC);
312
            // Get the total number of sub-categories
313
            $categoriesObj = $helper->getHandler('Category')->get($selCat);
314
            $totalsubs     = $helper->getHandler('Category')->getCategoriesCount($selCat);
315
            // creating the categories objects that are published
316
            $subcatsObj    = $helper->getHandler('Category')->getCategories(0, 0, $categoriesObj->categoryid());
0 ignored issues
show
Bug introduced by
The method categoryid() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Publisher\Item or XoopsModules\Publisher\File or XoopsModules\Publisher\Category. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

316
            $subcatsObj    = $helper->getHandler('Category')->getCategories(0, 0, $categoriesObj->/** @scrutinizer ignore-call */ categoryid());
Loading history...
317
            $totalSCOnPage = \count($subcatsObj);
0 ignored issues
show
Unused Code introduced by
The assignment to $totalSCOnPage is dead and can be removed.
Loading history...
318
            echo "<table width='100%' cellspacing=1 cellpadding=3 border=0 class = outer>";
319
            echo '<tr>';
320
            echo "<td width='60' class='bg3' align='left'><strong>" . \_AM_PUBLISHER_CATID . '</strong></td>';
321
            echo "<td width='20%' class='bg3' align='left'><strong>" . \_AM_PUBLISHER_CATCOLNAME . '</strong></td>';
322
            echo "<td class='bg3' align='left'><strong>" . \_AM_PUBLISHER_SUBDESCRIPT . '</strong></td>';
323
            echo "<td width='60' class='bg3' align='right'><strong>" . \_AM_PUBLISHER_ACTION . '</strong></td>';
324
            echo '</tr>';
325
            if ($totalsubs > 0) {
326
                foreach ($subcatsObj as $subcat) {
327
                    $modify = "<a href='category.php?op=mod&amp;categoryid=" . $subcat->categoryid() . "'><img src='" . XOOPS_URL . '/modules/' . $helper->getModule()->dirname() . "/assets/images/links/edit.gif' title='" . \_AM_PUBLISHER_MODIFY . "' alt='" . \_AM_PUBLISHER_MODIFY . "'></a>";
328
                    $delete = "<a href='category.php?op=del&amp;categoryid=" . $subcat->categoryid() . "'><img src='" . XOOPS_URL . '/modules/' . $helper->getModule()->dirname() . "/assets/images/links/delete.png' title='" . \_AM_PUBLISHER_DELETE . "' alt='" . \_AM_PUBLISHER_DELETE . "'></a>";
329
                    echo '<tr>';
330
                    echo "<td class='head' align='left'>" . $subcat->categoryid() . '</td>';
331
                    echo "<td class='even' align='left'><a href='" . XOOPS_URL . '/modules/' . $helper->getModule()->dirname() . '/category.php?categoryid=' . $subcat->categoryid() . '&amp;parentid=' . $subcat->parentid() . "'>" . $subcat->name() . '</a></td>';
332
                    echo "<td class='even' align='left'>" . $subcat->description() . '</td>';
333
                    echo "<td class='even' align='right'> {$modify} {$delete} </td>";
334
                    echo '</tr>';
335
                }
336
                //                unset($subcat);
337
            } else {
338
                echo '<tr>';
339
                echo "<td class='head' align='center' colspan= '7'>" . \_AM_PUBLISHER_NOSUBCAT . '</td>';
340
                echo '</tr>';
341
            }
342
            echo "</table>\n";
343
            echo "<br>\n";
344
            static::closeCollapsableBar('subcatstable', 'subcatsicon');
345
346
            static::openCollapsableBar('bottomtable', 'bottomtableicon', \_AM_PUBLISHER_CAT_ITEMS, \_AM_PUBLISHER_CAT_ITEMS_DSC);
347
            $startitem = Request::getInt('startitem');
348
            // Get the total number of published ITEMS
349
            $totalitems = $helper->getHandler('Item')->getItemsCount($selCat, [Constants::PUBLISHER_STATUS_PUBLISHED]);
0 ignored issues
show
Bug introduced by
array(XoopsModules\Publi...ISHER_STATUS_PUBLISHED) of type array<integer,integer> is incompatible with the type string expected by parameter $status of XoopsModules\Publisher\I...andler::getItemsCount(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

349
            $totalitems = $helper->getHandler('Item')->getItemsCount($selCat, /** @scrutinizer ignore-type */ [Constants::PUBLISHER_STATUS_PUBLISHED]);
Loading history...
350
            // creating the items objects that are published
351
            $itemsObj         = $helper->getHandler('Item')->getAllPublished($helper->getConfig('idxcat_perpage'), $startitem, $selCat);
352
            $totalitemsOnPage = \count($itemsObj);
353
            $allcats          = $helper->getHandler('Category')->getObjects(null, true);
354
            echo "<table width='100%' cellspacing=1 cellpadding=3 border=0 class = outer>";
355
            echo '<tr>';
356
            echo "<td width='40' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_ITEMID . '</strong></td>';
357
            echo "<td width='20%' class='bg3' align='left'><strong>" . \_AM_PUBLISHER_ITEMCOLNAME . '</strong></td>';
358
            echo "<td class='bg3' align='left'><strong>" . \_AM_PUBLISHER_ITEMDESC . '</strong></td>';
359
            echo "<td width='90' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_CREATED . '</strong></td>';
360
            echo "<td width='60' class='bg3' align='center'><strong>" . \_AM_PUBLISHER_ACTION . '</strong></td>';
361
            echo '</tr>';
362
            if ($totalitems > 0) {
363
                for ($i = 0; $i < $totalitemsOnPage; ++$i) {
364
                    $categoryObj = $allcats[$itemsObj[$i]->categoryid()];
365
                    $modify      = "<a href='item.php?op=mod&amp;itemid=" . $itemsObj[$i]->itemid() . "'><img src='" . XOOPS_URL . '/modules/' . $helper->getModule()->dirname() . "/assets/images/links/edit.gif' title='" . \_AM_PUBLISHER_EDITITEM . "' alt='" . \_AM_PUBLISHER_EDITITEM . "'></a>";
366
                    $delete      = "<a href='item.php?op=del&amp;itemid="
367
                                   . $itemsObj[$i]->itemid()
368
                                   . "'><img src='"
369
                                   . XOOPS_URL
370
                                   . '/modules/'
371
                                   . $helper->getModule()->dirname()
372
                                   . "/assets/images/links/delete.png' title='"
373
                                   . \_AM_PUBLISHER_DELETEITEM
374
                                   . "' alt='"
375
                                   . \_AM_PUBLISHER_DELETEITEM
376
                                   . "'></a>";
377
                    echo '<tr>';
378
                    echo "<td class='head' align='center'>" . $itemsObj[$i]->itemid() . '</td>';
379
                    echo "<td class='even' align='left'>" . $categoryObj->name() . '</td>';
380
                    echo "<td class='even' align='left'>" . $itemsObj[$i]->getitemLink() . '</td>';
381
                    echo "<td class='even' align='center'>" . $itemsObj[$i]->getDatesub('s') . '</td>';
382
                    echo "<td class='even' align='center'> $modify $delete </td>";
383
                    echo '</tr>';
384
                }
385
            } else {
386
                $itemId = -1;
0 ignored issues
show
Unused Code introduced by
The assignment to $itemId is dead and can be removed.
Loading history...
387
                echo '<tr>';
388
                echo "<td class='head' align='center' colspan= '7'>" . \_AM_PUBLISHER_NOITEMS . '</td>';
389
                echo '</tr>';
390
            }
391
            echo "</table>\n";
392
            echo "<br>\n";
393
            $parentid         = Request::getInt('parentid', 0, 'GET');
394
            $pagenavExtraArgs = "op=mod&categoryid=$selCat&parentid=$parentid";
395
            \xoops_load('XoopsPageNav');
396
            $pagenav = new \XoopsPageNav($totalitems, $helper->getConfig('idxcat_perpage'), $startitem, 'startitem', $pagenavExtraArgs);
397
            echo '<div style="text-align:right;">' . $pagenav->renderNav() . '</div>';
398
            echo "<input type='button' name='button' onclick=\"location='item.php?op=mod&categoryid=" . $selCat . "'\" value='" . \_AM_PUBLISHER_CREATEITEM . "'>&nbsp;&nbsp;";
399
            echo '</div>';
400
        }
401
        //end of fx2024 code
402
    }
403
404
    //======================== FUNCTIONS =================================
405
406
    /**
407
     * Includes scripts in HTML header
408
     */
409
    public static function cpHeader()
410
    {
411
        \xoops_cp_header();
412
413
        //cannot use xoTheme, some conflit with admin gui
414
        echo '<link type="text/css" href="' . XOOPS_URL . '/modules/system/css/ui/' . \xoops_getModuleOption('jquery_theme', 'system') . '/ui.all.css" rel="stylesheet">
0 ignored issues
show
Deprecated Code introduced by
The function xoops_getModuleOption() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

414
        echo '<link type="text/css" href="' . XOOPS_URL . '/modules/system/css/ui/' . /** @scrutinizer ignore-deprecated */ \xoops_getModuleOption('jquery_theme', 'system') . '/ui.all.css" rel="stylesheet">
Loading history...
415
    <link type="text/css" href="' . PUBLISHER_URL . '/assets/css/publisher.css" rel="stylesheet">
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
416
    <script type="text/javascript" src="' . PUBLISHER_URL . '/assets/js/funcs.js"></script>
417
    <script type="text/javascript" src="' . PUBLISHER_URL . '/assets/js/cookies.js"></script>
418
    <script type="text/javascript" src="' . XOOPS_URL . '/browse.php?Frameworks/jquery/jquery.js"></script>
419
    <!-- <script type="text/javascript" src="' . XOOPS_URL . '/browse.php?Frameworks/jquery/jquery-migrate-1.2.1.js"></script> -->
420
    <script type="text/javascript" src="' . XOOPS_URL . '/browse.php?Frameworks/jquery/plugins/jquery.ui.js"></script>
421
    <script type="text/javascript" src="' . PUBLISHER_URL . '/assets/js/ajaxupload.3.9.js"></script>
422
    <script type="text/javascript" src="' . PUBLISHER_URL . '/assets/js/publisher.js"></script>
423
    ';
424
    }
425
426
    /**
427
     * Default sorting for a given order
428
     *
429
     * @param string $sort
430
     * @return string
431
     */
432
    public static function getOrderBy($sort)
433
    {
434
        if ('datesub' === $sort) {
435
            return 'DESC';
436
        }
437
        if ('counter' === $sort) {
438
            return 'DESC';
439
        }
440
        if ('weight' === $sort) {
441
            return 'ASC';
442
        }
443
        if ('votes' === $sort) {
444
            return 'DESC';
445
        }
446
        if ('rating' === $sort) {
447
            return 'DESC';
448
        }
449
        if ('comments' === $sort) {
450
            return 'DESC';
451
        }
452
453
        return null;
454
    }
455
456
    /**
457
     * @credits Thanks to Mithandir
458
     * @param string $str
459
     * @param int    $start
460
     * @param int    $length
461
     * @param string $trimMarker
462
     * @return string
463
     */
464
    public static function substr($str, $start, $length, $trimMarker = '...')
465
    {
466
        // if the string is empty, let's get out ;-)
467
        if ('' == $str) {
468
            return $str;
469
        }
470
471
        // reverse a string that is shortened with '' as trimmarker
472
        $reversedString = \strrev(\xoops_substr($str, $start, $length, ''));
473
474
        // find first space in reversed string
475
        $positionOfSpace = \mb_strpos($reversedString, ' ', 0);
476
477
        // truncate the original string to a length of $length
478
        // minus the position of the last space
479
        // plus the length of the $trimMarker
480
        $truncatedString = \xoops_substr($str, $start, $length - $positionOfSpace + \mb_strlen($trimMarker), $trimMarker);
481
482
        return $truncatedString;
483
    }
484
485
    /**
486
     * @param string $document
487
     * @return mixed
488
     */
489
    public static function html2text($document)
490
    {
491
        // PHP Manual:: function preg_replace
492
        // $document should contain an HTML document.
493
        // This will remove HTML tags, javascript sections
494
        // and white space. It will also convert some
495
        // common HTML entities to their text equivalent.
496
        // Credits : newbb2
497
        $search = [
498
            "'<script[^>]*?>.*?</script>'si", // Strip out javascript
499
            "'<img.*?>'si", // Strip out img tags
500
            "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
501
            "'([\r\n])[\s]+'", // Strip out white space
502
            "'&(quot|#34);'i", // Replace HTML entities
503
            "'&(amp|#38);'i",
504
            "'&(lt|#60);'i",
505
            "'&(gt|#62);'i",
506
            "'&(nbsp|#160);'i",
507
            "'&(iexcl|#161);'i",
508
            "'&(cent|#162);'i",
509
            "'&(pound|#163);'i",
510
            "'&(copy|#169);'i",
511
        ]; // evaluate as php
512
513
        $replace = [
514
            '',
515
            '',
516
            '',
517
            '\\1',
518
            '"',
519
            '&',
520
            '<',
521
            '>',
522
            ' ',
523
            \chr(161),
524
            \chr(162),
525
            \chr(163),
526
            \chr(169),
527
        ];
528
529
        $text = \preg_replace($search, $replace, $document);
530
531
        \preg_replace_callback(
532
            '/&#(\d+);/',
533
            static function ($matches) {
534
                return \chr($matches[1]);
535
            },
536
            $document
537
        );
538
539
        return $text;
540
        //<?php
541
    }
542
543
    /**
544
     * @return array
545
     */
546
    public static function getAllowedImagesTypes()
547
    {
548
        return ['jpg/jpeg', 'image/bmp', 'image/gif', 'image/jpeg', 'image/jpg', 'image/x-png', 'image/png', 'image/pjpeg'];
549
    }
550
551
    /**
552
     * @param bool $withLink
553
     * @return string
554
     */
555
    public static function moduleHome($withLink = true)
556
    {
557
        $helper = Helper::getInstance();
558
559
        if (!$helper->getConfig('format_breadcrumb_modname')) {
560
            return '';
561
        }
562
563
        if (!$withLink) {
564
            return $helper->getModule()->getVar('name');
0 ignored issues
show
Bug Best Practice introduced by
The expression return $helper->getModule()->getVar('name') also could return the type array|boolean which is incompatible with the documented return type string.
Loading history...
565
        }
566
567
        return '<a href="' . PUBLISHER_URL . '/">' . $helper->getModule()->getVar('name') . '</a>';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
568
    }
569
570
    /**
571
     * Copy a file, or a folder and its contents
572
     *
573
     * @param string $source The source
574
     * @param string $dest   The destination
575
     * @return bool   Returns true on success, false on failure
576
     * @version     1.0.0
577
     * @author      Aidan Lister <[email protected]>
578
     */
579
    public static function copyr($source, $dest)
580
    {
581
        // Simple copy for a file
582
        if (\is_file($source)) {
583
            return \copy($source, $dest);
584
        }
585
586
        // Make destination directory
587
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
588
            throw new \RuntimeException(\sprintf('Directory "%s" was not created', $dest));
589
        }
590
591
        // Loop through the folder
592
        $dir = \dir($source);
593
        while (false !== ($entry = $dir->read())) {
594
            // Skip pointers
595
            if ('.' === $entry || '..' === $entry) {
596
                continue;
597
            }
598
599
            // Deep copy directories
600
            if (("$source/$entry" !== $dest) && \is_dir("$source/$entry")) {
601
                static::copyr("$source/$entry", "$dest/$entry");
602
            } else {
603
                \copy("$source/$entry", "$dest/$entry");
604
            }
605
        }
606
607
        // Clean up
608
        $dir->close();
609
610
        return true;
611
    }
612
613
    /**
614
     * .* @credits Thanks to the NewBB2 Development Team
615
     * @param string $item
616
     * @param bool   $getStatus
617
     * @return bool|int|string
618
     */
619
    public static function getPathStatus($item, $getStatus = false)
620
    {
621
        $path = '';
622
        if ('root' !== $item) {
623
            $path = $item;
624
        }
625
626
        $thePath = static::getUploadDir(true, $path);
627
628
        if (empty($thePath)) {
629
            return false;
630
        }
631
        if (\is_writable($thePath)) {
632
            $pathCheckResult = 1;
633
            $pathStatus      = \_AM_PUBLISHER_AVAILABLE;
634
        } elseif (@\is_dir($thePath)) {
635
            $pathCheckResult = -2;
636
            $pathStatus      = \_AM_PUBLISHER_NOTWRITABLE . " <a href='" . PUBLISHER_ADMIN_URL . "/index.php?op=setperm&amp;path={$item}'>" . \_AM_PUBLISHER_SETMPERM . '</a>';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_ADMIN_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
637
        } else {
638
            $pathCheckResult = -1;
639
            $pathStatus      = \_AM_PUBLISHER_NOTAVAILABLE . " <a href='" . PUBLISHER_ADMIN_URL . "/index.php?op=createdir&amp;path={$item}'>" . \_AM_PUBLISHER_CREATETHEDIR . '</a>';
640
        }
641
        if (!$getStatus) {
642
            return $pathStatus;
643
        }
644
645
        return $pathCheckResult;
646
    }
647
648
    /**
649
     * @credits Thanks to the NewBB2 Development Team
650
     * @param string $target
651
     * @return bool
652
     */
653
    public static function mkdir($target)
654
    {
655
        // http://www.php.net/manual/en/function.mkdir.php
656
        // saint at corenova.com
657
        // bart at cdasites dot com
658
        if (empty($target) || \is_dir($target)) {
659
            return true; // best case check first
660
        }
661
662
        if (\is_dir($target) && !\is_dir($target)) {
663
            return false;
664
        }
665
666
        if (static::mkdir(\mb_substr($target, 0, \mb_strrpos($target, '/')))) {
667
            if (!\is_dir($target)) {
668
                $res = \mkdir($target, 0777); // crawl back up & create dir tree
669
                static::chmod($target);
670
671
                return $res;
672
            }
673
        }
674
        $res = \is_dir($target);
675
676
        return $res;
677
    }
678
679
    /**
680
     * @credits Thanks to the NewBB2 Development Team
681
     * @param string $target
682
     * @param int    $mode
683
     * @return bool
684
     */
685
    public static function chmod($target, $mode = 0777)
686
    {
687
        return @\chmod($target, $mode);
688
    }
689
690
    /**
691
     * @param bool   $hasPath
692
     * @param string $item
693
     * @return string
694
     */
695
    public static function getUploadDir($hasPath = true, $item = '')
696
    {
697
        if ('' !== $item) {
698
            if ('root' === $item) {
699
                $item = '';
700
            } else {
701
                $item .= '/';
702
            }
703
        }
704
705
        if ($hasPath) {
706
            return PUBLISHER_UPLOAD_PATH . '/' . $item;
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_UPLOAD_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
707
        }
708
709
        return PUBLISHER_UPLOAD_URL . '/' . $item;
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_UPLOAD_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
710
    }
711
712
    /**
713
     * @param string $item
714
     * @param bool   $hasPath
715
     * @return string
716
     */
717
    public static function getImageDir($item = '', $hasPath = true)
718
    {
719
        if ($item) {
720
            $item = "images/{$item}";
721
        } else {
722
            $item = 'images';
723
        }
724
725
        return static::getUploadDir($hasPath, $item);
726
    }
727
728
    /**
729
     * @param array $errors
730
     * @return string
731
     */
732
    public static function formatErrors($errors = [])
733
    {
734
        $ret = '';
735
        foreach ($errors as $key => $value) {
736
            $ret .= '<br> - ' . $value;
737
        }
738
739
        return $ret;
740
    }
741
742
    /**
743
     * Checks if a user is admin of Publisher
744
     *
745
     * @return bool
746
     */
747
    public static function userIsAdmin()
748
    {
749
        $helper = Helper::getInstance();
750
751
        static $publisherIsAdmin;
752
753
        if (null !== $publisherIsAdmin) {
754
            return $publisherIsAdmin;
755
        }
756
757
        if ($GLOBALS['xoopsUser']) {
758
            //            $publisherIsAdmin = $GLOBALS['xoopsUser']->isAdmin($helper->getModule()->getVar('mid'));
759
            $publisherIsAdmin = $helper->isUserAdmin();
760
        } else {
761
            $publisherIsAdmin = false;
762
        }
763
764
        return $publisherIsAdmin;
765
    }
766
767
    /**
768
     * Check is current user is author of a given article
769
     *
770
     * @param \XoopsObject $itemObj
771
     * @return bool
772
     */
773
    public static function userIsAuthor($itemObj)
774
    {
775
        return (\is_object($GLOBALS['xoopsUser']) && \is_object($itemObj) && ($GLOBALS['xoopsUser']->uid() == $itemObj->uid()));
0 ignored issues
show
Bug introduced by
The method uid() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Publisher\Item or XoopsUser or XoopsModules\Publisher\File or XoopsModules\Publisher\Category. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

775
        return (\is_object($GLOBALS['xoopsUser']) && \is_object($itemObj) && ($GLOBALS['xoopsUser']->uid() == $itemObj->/** @scrutinizer ignore-call */ uid()));
Loading history...
776
    }
777
778
    /**
779
     * Check is current user is moderator of a given article
780
     *
781
     * @param \XoopsObject $itemObj
782
     * @return bool
783
     */
784
    public static function userIsModerator($itemObj)
785
    {
786
        $helper            = Helper::getInstance();
787
        $categoriesGranted = $helper->getHandler('Permission')->getGrantedItems('category_moderation');
788
789
        return (\is_object($itemObj) && \in_array($itemObj->categoryid(), $categoriesGranted, true));
790
    }
791
792
    /**
793
     * Saves permissions for the selected category
794
     *
795
     * @param null|array $groups     : group with granted permission
796
     * @param int        $categoryId : categoryid on which we are setting permissions
797
     * @param string     $permName   : name of the permission
798
     * @return bool : TRUE if the no errors occured
799
     */
800
    public static function saveCategoryPermissions($groups, $categoryId, $permName)
801
    {
802
        $helper = Helper::getInstance();
803
804
        $result = true;
805
806
        $moduleId = $helper->getModule()->getVar('mid');
807
        /** @var \XoopsGroupPermHandler $grouppermHandler */
808
        $grouppermHandler = \xoops_getHandler('groupperm');
809
        // First, if the permissions are already there, delete them
810
        $grouppermHandler->deleteByModule($moduleId, $permName, $categoryId);
811
812
        // Save the new permissions
813
        if (\count($groups) > 0) {
814
            foreach ($groups as $groupId) {
815
                $grouppermHandler->addRight($permName, $categoryId, $groupId, $moduleId);
816
            }
817
        }
818
819
        return $result;
820
    }
821
822
    /**
823
     * @param string $tablename
824
     * @param string $iconname
825
     * @param string $tabletitle
826
     * @param string $tabledsc
827
     * @param bool   $open
828
     */
829
    public static function openCollapsableBar($tablename = '', $iconname = '', $tabletitle = '', $tabledsc = '', $open = true)
830
    {
831
        $image   = 'open12.gif';
832
        $display = 'none';
833
        if ($open) {
834
            $image   = 'close12.gif';
835
            $display = 'block';
836
        }
837
838
        echo "<h3 style=\"color: #2F5376; font-weight: bold; font-size: 14px; margin: 6px 0 0 0; \"><a href='javascript:;' onclick=\"toggle('" . $tablename . "'); toggleIcon('" . $iconname . "')\">";
839
        echo "<img id='" . $iconname . "' src='" . PUBLISHER_URL . '/assets/images/links/' . $image . "' alt=''></a>&nbsp;" . $tabletitle . '</h3>';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
840
        echo "<div id='" . $tablename . "' style='display: " . $display . ";'>";
841
        if ('' != $tabledsc) {
842
            echo '<span style="color: #567; margin: 3px 0 12px 0; font-size: small; display: block; ">' . $tabledsc . '</span>';
843
        }
844
    }
845
846
    /**
847
     * @param string $name
848
     * @param string $icon
849
     */
850
    public static function closeCollapsableBar($name, $icon)
851
    {
852
        echo '</div>';
853
854
        $urls = static::getCurrentUrls();
855
        $path = $urls['phpself'];
856
857
        $cookieName = $path . '_publisher_collaps_' . $name;
858
        $cookieName = \str_replace('.', '_', $cookieName);
859
        $cookie     = static::getCookieVar($cookieName, '');
860
861
        if ('none' === $cookie) {
862
            echo '
863
        <script type="text/javascript">
864
     <!--
865
        toggle("' . $name . '"); 
866
        toggleIcon("' . $icon . '");
867
        -->
868
        </script>
869
        ';
870
        }
871
    }
872
873
    /**
874
     * @param string $name
875
     * @param string $value
876
     * @param int    $time
877
     */
878
    public static function setCookieVar($name, $value, $time = 0)
879
    {
880
        if (0 === $time) {
881
            $time = \time() + 3600 * 24 * 365;
882
        }
883
//        setcookie($name, $value, $time, '/');
884
         setcookie($name, $value, $time, '/', ini_get('session.cookie_domain'), (bool)ini_get('session.cookie_secure'), (bool)ini_get('session.cookie_httponly'));
885
    }
886
887
    /**
888
     * @param string $name
889
     * @param string $default
890
     * @return string
891
     */
892
    public static function getCookieVar($name, $default = '')
893
    {
894
        //    if (isset($_COOKIE[$name]) && ($_COOKIE[$name] > '')) {
895
        //        return $_COOKIE[$name];
896
        //    } else {
897
        //        return $default;
898
        //    }
899
        return Request::getString($name, $default, 'COOKIE');
900
    }
901
902
    /**
903
     * @return array
904
     */
905
    public static function getCurrentUrls()
906
    {
907
        $http = false === \mb_strpos(XOOPS_URL, 'https://') ? 'http://' : 'https://';
908
        //    $phpself     = $_SERVER['SCRIPT_NAME'];
909
        //    $httphost    = $_SERVER['HTTP_HOST'];
910
        //    $querystring = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '';
911
        $phpself     = Request::getString('SCRIPT_NAME', '', 'SERVER');
912
        $httphost    = Request::getString('HTTP_HOST', '', 'SERVER');
913
        $querystring = Request::getString('QUERY_STRING', '', 'SERVER');
914
915
        if ('' != $querystring) {
916
            $querystring = '?' . $querystring;
917
        }
918
919
        $currenturl = $http . $httphost . $phpself . $querystring;
920
921
        $urls                = [];
922
        $urls['http']        = $http;
923
        $urls['httphost']    = $httphost;
924
        $urls['phpself']     = $phpself;
925
        $urls['querystring'] = $querystring;
926
        $urls['full']        = $currenturl;
927
928
        return $urls;
929
    }
930
931
    /**
932
     * @return string
933
     */
934
    public static function getCurrentPage()
935
    {
936
        $urls = static::getCurrentUrls();
937
938
        return $urls['full'];
939
    }
940
941
    /**
942
     * @param null|Category $categoryObj
943
     * @param int|array     $selectedId
944
     * @param int           $level
945
     * @param string        $ret
946
     * @return string
947
     */
948
    public static function addCategoryOption(Category $categoryObj, $selectedId = 0, $level = 0, $ret = '')
949
    {
950
        $helper = Helper::getInstance();
951
952
        $spaces = '';
953
        for ($j = 0; $j < $level; ++$j) {
954
            $spaces .= '--';
955
        }
956
957
        $ret .= "<option value='" . $categoryObj->categoryid() . "'";
958
        if (\is_array($selectedId) && \in_array($categoryObj->categoryid(), $selectedId, true)) {
959
            $ret .= ' selected';
960
        } elseif ($categoryObj->categoryid() == $selectedId) {
961
            $ret .= ' selected';
962
        }
963
        $ret .= '>' . $spaces . $categoryObj->name() . "</option>\n";
964
965
        $subCategoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $categoryObj->categoryid());
966
        if (\count($subCategoriesObj) > 0) {
967
            ++$level;
968
            foreach ($subCategoriesObj as $catId => $subCategoryObj) {
969
                $ret .= static::addCategoryOption($subCategoryObj, $selectedId, $level);
970
            }
971
        }
972
973
        return $ret;
974
    }
975
976
    /**
977
     * @param int|array $selectedId
978
     * @param int       $parentcategory
979
     * @param bool      $allCatOption
980
     * @param string    $selectname
981
     * @param bool      $multiple
982
     * @return string
983
     */
984
    public static function createCategorySelect($selectedId = 0, $parentcategory = 0, $allCatOption = true, $selectname = 'options[1]', $multiple = true)
985
    {
986
        $helper = Helper::getInstance();
987
988
        $selectedId  = \explode(',', $selectedId);
0 ignored issues
show
Bug introduced by
It seems like $selectedId can also be of type array; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

988
        $selectedId  = \explode(',', /** @scrutinizer ignore-type */ $selectedId);
Loading history...
989
        $selectedId  = \array_map('\intval', $selectedId);
990
        $selMultiple = '';
991
        if ($multiple) {
992
            $selMultiple = " multiple='multiple'";
993
        }
994
        $ret = "<select name='" . $selectname . "[]'" . $selMultiple . " size='10'>";
995
        if ($allCatOption) {
996
            $ret .= "<option value='0'";
997
            if (\in_array(0, $selectedId, true)) {
998
                $ret .= ' selected';
999
            }
1000
            $ret .= '>' . \_MB_PUBLISHER_ALLCAT . '</option>';
1001
        }
1002
1003
        // Creating category objects
1004
        $categoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $parentcategory);
1005
1006
        if (\count($categoriesObj) > 0) {
1007
            foreach ($categoriesObj as $catId => $categoryObj) {
1008
                $ret .= static::addCategoryOption($categoryObj, $selectedId);
1009
            }
1010
        }
1011
        $ret .= '</select>';
1012
1013
        return $ret;
1014
    }
1015
1016
    /**
1017
     * @param int  $selectedId
1018
     * @param int  $parentcategory
1019
     * @param bool $allCatOption
1020
     * @return string
1021
     */
1022
    public static function createCategoryOptions($selectedId = 0, $parentcategory = 0, $allCatOption = true)
1023
    {
1024
        $helper = Helper::getInstance();
1025
1026
        $ret = '';
1027
        if ($allCatOption) {
1028
            $ret .= "<option value='0'";
1029
            $ret .= '>' . \_MB_PUBLISHER_ALLCAT . "</option>\n";
1030
        }
1031
1032
        // Creating category objects
1033
        $categoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $parentcategory);
1034
        if (\count($categoriesObj) > 0) {
1035
            foreach ($categoriesObj as $catId => $categoryObj) {
1036
                $ret .= static::addCategoryOption($categoryObj, $selectedId);
1037
            }
1038
        }
1039
1040
        return $ret;
1041
    }
1042
1043
    /**
1044
     * @param array  $errArray
1045
     * @param string $reseturl
1046
     */
1047
    public static function renderErrors($errArray, $reseturl = '')
1048
    {
1049
        if ($errArray && \is_array($errArray)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $errArray of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1050
            echo '<div id="readOnly" class="errorMsg" style="border:1px solid #D24D00; background:#FEFECC url(' . PUBLISHER_URL . '/assets/images/important-32.png) no-repeat 7px 50%;color:#333;padding-left:45px;">';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1051
1052
            echo '<h4 style="text-align:left;margin:0; padding-top:0;">' . \_AM_PUBLISHER_MSG_SUBMISSION_ERR;
1053
1054
            if ($reseturl) {
1055
                echo ' <a href="' . $reseturl . '">[' . \_AM_PUBLISHER_TEXT_SESSION_RESET . ']</a>';
1056
            }
1057
1058
            echo '</h4><ul>';
1059
1060
            foreach ($errArray as $key => $error) {
1061
                if (\is_array($error)) {
1062
                    foreach ($error as $err) {
1063
                        echo '<li><a href="#' . $key . '" onclick="var e = xoopsGetElementById(\'' . $key . '\'); e.focus();">' . \htmlspecialchars($err, \ENT_QUOTES | \ENT_HTML5) . '</a></li>';
1064
                    }
1065
                } else {
1066
                    echo '<li><a href="#' . $key . '" onclick="var e = xoopsGetElementById(\'' . $key . '\'); e.focus();">' . \htmlspecialchars($error, \ENT_QUOTES | \ENT_HTML5) . '</a></li>';
1067
                }
1068
            }
1069
            echo '</ul></div><br>';
1070
        }
1071
    }
1072
1073
    /**
1074
     * Generate publisher URL
1075
     *
1076
     * @param string $page
1077
     * @param array  $vars
1078
     * @param bool   $encodeAmp
1079
     * @return string
1080
     *
1081
     * @credit : xHelp module, developped by 3Dev
1082
     */
1083
    public static function makeUri($page, $vars = [], $encodeAmp = true)
1084
    {
1085
        $joinStr = '';
1086
1087
        $amp = ($encodeAmp ? '&amp;' : '&');
1088
1089
        if (!\count($vars)) {
1090
            return $page;
1091
        }
1092
1093
        $qs = '';
1094
        foreach ($vars as $key => $value) {
1095
            $qs      .= $joinStr . $key . '=' . $value;
1096
            $joinStr = $amp;
1097
        }
1098
1099
        return $page . '?' . $qs;
1100
    }
1101
1102
    /**
1103
     * @param string $subject
1104
     * @return string
1105
     */
1106
    public static function tellAFriend($subject = '')
1107
    {
1108
        if (false !== \mb_strpos($subject, '%')) {
1109
            $subject = \rawurldecode($subject);
1110
        }
1111
1112
        $targetUri = XOOPS_URL . Request::getString('REQUEST_URI', '', 'SERVER');
1113
1114
        return XOOPS_URL . '/modules/tellafriend/index.php?target_uri=' . \rawurlencode($targetUri) . '&amp;subject=' . \rawurlencode($subject);
1115
    }
1116
1117
    /**
1118
     * @param bool $another
1119
     * @param bool $withRedirect
1120
     * @param Item|null $itemObj
1121
     * @return bool|string|null
1122
     */
1123
    public static function uploadFile($another, $withRedirect, &$itemObj=null)
1124
    {
1125
        \xoops_load('XoopsMediaUploader');
1126
        //        require_once PUBLISHER_ROOT_PATH . '/class/uploader.php';
1127
1128
        //    global $publisherIsAdmin;
1129
        $helper = Helper::getInstance();
1130
1131
        $itemId  = Request::getInt('itemid', 0, 'POST');
1132
        $uid     = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->uid() : 0;
1133
        $session = Session::getInstance();
1134
        $session->set('publisher_file_filename', Request::getString('item_file_name', '', 'POST'));
1135
        $session->set('publisher_file_description', Request::getString('item_file_description', '', 'POST'));
1136
        $session->set('publisher_file_status', Request::getInt('item_file_status', 1, 'POST'));
1137
        $session->set('publisher_file_uid', $uid);
1138
        $session->set('publisher_file_itemid', $itemId);
1139
1140
        if (!\is_object($itemObj) && 0 !== $itemId) {
1141
            $itemObj = $helper->getHandler('Item')->get($itemId);
1142
        }
1143
1144
        $fileObj = $helper->getHandler('File')->create();
1145
        $fileObj->setVar('name', Request::getString('item_file_name', '', 'POST'));
1146
        $fileObj->setVar('description', Request::getString('item_file_description', '', 'POST'));
1147
        $fileObj->setVar('status', Request::getInt('item_file_status', 1, 'POST'));
1148
        $fileObj->setVar('uid', $uid);
1149
        $fileObj->setVar('itemid', $itemObj->getVar('itemid'));
1150
        $fileObj->setVar('datesub', \time());
1151
1152
        // Get available mimetypes for file uploading
1153
        $allowedMimetypes = $helper->getHandler('Mimetype')->getArrayByType();
1154
        // TODO : display the available mimetypes to the user
1155
        $errors = [];
1156
        if ($helper->getConfig('perm_upload') && \is_uploaded_file($_FILES['item_upload_file']['tmp_name'])) {
1157
            if (!$ret = $fileObj->checkUpload('item_upload_file', $allowedMimetypes, $errors)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
Bug introduced by
The method checkUpload() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Publisher\Item or XoopsModules\Publisher\File or XoopsModules\Publisher\Category. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1157
            if (!$ret = $fileObj->/** @scrutinizer ignore-call */ checkUpload('item_upload_file', $allowedMimetypes, $errors)) {
Loading history...
1158
                $errorstxt = \implode('<br>', $errors);
1159
1160
                $message = \sprintf(\_CO_PUBLISHER_MESSAGE_FILE_ERROR, $errorstxt);
1161
                if ($withRedirect) {
1162
                    \redirect_header('file.php?op=mod&itemid=' . $itemId, 5, $message);
1163
                } else {
1164
                    return $message;
1165
                }
1166
            }
1167
        }
1168
1169
        // Storing the file
1170
        if (!$fileObj->store($allowedMimetypes)) {
0 ignored issues
show
Bug introduced by
The method store() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsComments or XoopsModules\Publisher\Item or XoopsModules\Publisher\File or XoopsModules\Publisher\Category. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1170
        if (!$fileObj->/** @scrutinizer ignore-call */ store($allowedMimetypes)) {
Loading history...
1171
            //        if ($withRedirect) {
1172
            //            redirect_header("file.php?op=mod&itemid=" . $fileObj->itemid(), 3, _CO_PUBLISHER_FILEUPLOAD_ERROR . static::formatErrors($fileObj->getErrors()));
1173
            //        }
1174
            try {
1175
                if ($withRedirect) {
1176
                    throw new \RuntimeException(\_CO_PUBLISHER_FILEUPLOAD_ERROR . static::formatErrors($fileObj->getErrors()));
1177
                }
1178
            } catch (\Throwable $e) {
1179
                $helper->addLog($e);
1180
                \redirect_header('file.php?op=mod&itemid=' . $fileObj->itemid(), 3, \_CO_PUBLISHER_FILEUPLOAD_ERROR . static::formatErrors($fileObj->getErrors()));
0 ignored issues
show
Bug introduced by
The method itemid() does not exist on XoopsObject. It seems like you code against a sub-type of XoopsObject such as XoopsModules\Publisher\Item or XoopsModules\Publisher\File or XoopsModules\Publisher\Category. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1180
                \redirect_header('file.php?op=mod&itemid=' . $fileObj->/** @scrutinizer ignore-call */ itemid(), 3, \_CO_PUBLISHER_FILEUPLOAD_ERROR . static::formatErrors($fileObj->getErrors()));
Loading history...
1181
            }
1182
            //    } else {
1183
            //        return _CO_PUBLISHER_FILEUPLOAD_ERROR . static::formatErrors($fileObj->getErrors());
1184
        }
1185
1186
        if ($withRedirect) {
1187
            $redirectPage = $another ? 'file.php' : 'item.php';
1188
            \redirect_header($redirectPage . '?op=mod&itemid=' . $fileObj->itemid(), 2, \_CO_PUBLISHER_FILEUPLOAD_SUCCESS);
1189
        } else {
1190
            return true;
1191
        }
1192
1193
        return null;
1194
    }
1195
1196
    /**
1197
     * @return string
1198
     */
1199
    public static function newFeatureTag()
1200
    {
1201
        $ret = '<span style="padding-right: 4px; font-weight: bold; color: #ff0000;">' . \_CO_PUBLISHER_NEW_FEATURE . '</span>';
1202
1203
        return $ret;
1204
    }
1205
1206
    /**
1207
     * Smarty truncate_tagsafe modifier plugin
1208
     *
1209
     * Type:     modifier<br>
1210
     * Name:     truncate_tagsafe<br>
1211
     * Purpose:  Truncate a string to a certain length if necessary,
1212
     *           optionally splitting in the middle of a word, and
1213
     *           appending the $etc string or inserting $etc into the middle.
1214
     *           Makes sure no tags are left half-open or half-closed
1215
     *           (e.g. "Banana in a <a...")
1216
     * @param mixed $string
1217
     * @param mixed $length
1218
     * @param mixed $etc
1219
     * @param mixed $breakWords
1220
     * @return string
1221
     * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
1222
     *           <amos dot robinson at gmail dot com>
1223
     */
1224
    public static function truncateTagSafe($string, $length = 80, $etc = '...', $breakWords = false)
1225
    {
1226
        if (0 == $length) {
1227
            return '';
1228
        }
1229
1230
        if (\mb_strlen($string) > $length) {
1231
            $length -= \mb_strlen($etc);
1232
            if (!$breakWords) {
1233
                $string = \preg_replace('/\s+?(\S+)?$/', '', \mb_substr($string, 0, $length + 1));
1234
                $string = \preg_replace('/<[^>]*$/', '', $string);
1235
                $string = static::closeTags($string);
1236
            }
1237
1238
            return $string . $etc;
1239
        }
1240
1241
        return $string;
1242
    }
1243
1244
    /**
1245
     * @param string $string
1246
     * @return string
1247
     * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
1248
     *           <amos dot robinson at gmail dot com>
1249
     */
1250
    public static function closeTags($string)
1251
    {
1252
        // match opened tags
1253
        if (\preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $startTags)) {
1254
            $startTags = $startTags[1];
1255
            // match closed tags
1256
            if (\preg_match_all('/<\/([a-z]+)>/', $string, $endTags)) {
1257
                $completeTags = [];
1258
                $endTags      = $endTags[1];
1259
1260
                foreach ($startTags as $key => $val) {
1261
                    $posb = \array_search($val, $endTags, true);
1262
                    if (\is_int($posb)) {
1263
                        unset($endTags[$posb]);
1264
                    } else {
1265
                        $completeTags[] = $val;
1266
                    }
1267
                }
1268
            } else {
1269
                $completeTags = $startTags;
1270
            }
1271
1272
            $completeTags = \array_reverse($completeTags);
1273
            $elementCount = \count($completeTags);
1274
            for ($i = 0; $i < $elementCount; ++$i) {
1275
                $string .= '</' . $completeTags[$i] . '>';
1276
            }
1277
        }
1278
1279
        return $string;
1280
    }
1281
1282
    /**
1283
     * Get the rating for 5 stars (the original rating)
1284
     * @param int $itemId
1285
     * @return string
1286
     */
1287
    public static function ratingBar($itemId)
1288
    {
1289
        $helper          = Helper::getInstance();
1290
        $ratingUnitWidth = 30;
1291
        $units           = 5;
1292
1293
        $criteria   = new \Criteria('itemid', $itemId);
1294
        $ratingObjs = $helper->getHandler('Rating')->getObjects($criteria);
1295
        unset($criteria);
1296
1297
        $uid           = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getVar('uid') : 0;
1298
        $count         = \count($ratingObjs);
1299
        $currentRating = 0;
1300
        $voted         = false;
1301
        $ip            = \getenv('REMOTE_ADDR');
1302
        $rating1       = $rating2 = $ratingWidth = 0;
1303
1304
        foreach ($ratingObjs as $ratingObj) {
1305
            $currentRating += $ratingObj->getVar('rate');
1306
            if ($ratingObj->getVar('ip') == $ip || ($uid > 0 && $uid == $ratingObj->getVar('uid'))) {
1307
                $voted = true;
1308
            }
1309
        }
1310
1311
        $tense = 1 == $count ? \_MD_PUBLISHER_VOTE_VOTE : \_MD_PUBLISHER_VOTE_VOTES; //plural form votes/vote
1312
1313
        // now draw the rating bar
1314
        if (0 != $count) {
1315
            $ratingWidth = \number_format($currentRating / $count, 2) * $ratingUnitWidth;
1316
            $rating1     = \number_format($currentRating / $count, 1);
1317
            $rating2     = \number_format($currentRating / $count, 2);
1318
        }
1319
        $groups = $GLOBALS['xoopsUser'] ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
1320
        /** @var GroupPermHandler $grouppermHandler */
1321
        $grouppermHandler = $helper->getHandler('GroupPerm');
1322
1323
        if (!$grouppermHandler->checkRight('global', Constants::PUBLISHER_RATE, $groups, $helper->getModule()->getVar('mid'))) {
1324
            $staticRater   = [];
1325
            $staticRater[] .= "\n" . '<div class="publisher_ratingblock">';
1326
            $staticRater[] .= '<div id="unit_long' . $itemId . '">';
1327
            $staticRater[] .= '<div id="unit_ul' . $itemId . '" class="publisher_unit-rating" style="width:' . $ratingUnitWidth * $units . 'px;">';
1328
            $staticRater[] .= '<div class="publisher_current-rating" style="width:' . $ratingWidth . 'px;">' . \_MD_PUBLISHER_VOTE_RATING . ' ' . $rating2 . '/' . $units . '</div>';
1329
            $staticRater[] .= '</div>';
1330
            $staticRater[] .= '<div class="publisher_static">' . \_MD_PUBLISHER_VOTE_RATING . ': <strong> ' . $rating1 . '</strong>/' . $units . ' (' . $count . ' ' . $tense . ') <br><em>' . \_MD_PUBLISHER_VOTE_DISABLE . '</em></div>';
1331
            $staticRater[] .= '</div>';
1332
            $staticRater[] .= '</div>' . "\n\n";
1333
1334
            return \implode("\n", $staticRater);
1335
        }
1336
        $rater = '';
1337
        $rater .= '<div class="publisher_ratingblock">';
1338
        $rater .= '<div id="unit_long' . $itemId . '">';
1339
        $rater .= '<div id="unit_ul' . $itemId . '" class="publisher_unit-rating" style="width:' . $ratingUnitWidth * $units . 'px;">';
1340
        $rater .= '<div class="publisher_current-rating" style="width:' . $ratingWidth . 'px;">' . \_MD_PUBLISHER_VOTE_RATING . ' ' . $rating2 . '/' . $units . '</div>';
1341
1342
        for ($ncount = 1; $ncount <= $units; ++$ncount) {
1343
            // loop from 1 to the number of units
1344
            if (!$voted) {
1345
                // if the user hasn't yet voted, draw the voting stars
1346
                $rater .= '<div><a href="' . PUBLISHER_URL . '/rate.php?itemid=' . $itemId . '&amp;rating=' . $ncount . '" title="' . $ncount . ' ' . \_MD_PUBLISHER_VOTE_OUTOF . ' ' . $units . '" class="publisher_r' . $ncount . '-unit rater" rel="nofollow">' . $ncount . '</a></div>';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1347
            }
1348
        }
1349
1350
        $ncount = 0; // resets the count
0 ignored issues
show
Unused Code introduced by
The assignment to $ncount is dead and can be removed.
Loading history...
1351
        $rater  .= '  </div>';
1352
        $rater  .= '  <div';
1353
1354
        if ($voted) {
1355
            $rater .= ' class="publisher_voted"';
1356
        }
1357
1358
        $rater .= '>' . \_MD_PUBLISHER_VOTE_RATING . ': <strong> ' . $rating1 . '</strong>/' . $units . ' (' . $count . ' ' . $tense . ')';
1359
        $rater .= '  </div>';
1360
        $rater .= '</div>';
1361
        $rater .= '</div>';
1362
1363
        return $rater;
1364
    }
1365
1366
    /**
1367
     * @param array|null $allowedEditors
1368
     * @return array
1369
     */
1370
    public static function getEditors($allowedEditors = null)
1371
    {
1372
        $ret    = [];
1373
        $nohtml = false;
1374
        \xoops_load('XoopsEditorHandler');
1375
        $editorHandler = \XoopsEditorHandler::getInstance();
1376
        //        $editors       = array_flip($editorHandler->getList()); //$editorHandler->getList($nohtml);
1377
        $editors = $editorHandler->getList($nohtml);
1378
        foreach ($editors as $name => $title) {
1379
            $key = static::stringToInt($name);
1380
            if (\is_array($allowedEditors)) {
1381
                //for submit page
1382
                if (\in_array($key, $allowedEditors, true)) {
1383
                    $ret[] = $name;
1384
                }
1385
            } else {
1386
                //for admin permissions page
1387
                $ret[$key]['name']  = $name;
1388
                $ret[$key]['title'] = $title;
1389
            }
1390
        }
1391
1392
        return $ret;
1393
    }
1394
1395
    /**
1396
     * @param string $string
1397
     * @param int    $length
1398
     * @return int
1399
     */
1400
    public static function stringToInt($string = '', $length = 5)
1401
    {
1402
        $final     = '';
1403
        $substring = \mb_substr(\md5($string), $length);
1404
        for ($i = 0; $i < $length; ++$i) {
1405
            $final .= (int)$substring[$i];
1406
        }
1407
1408
        return (int)$final;
1409
    }
1410
1411
    /**
1412
     * @param string $item
1413
     * @return string
1414
     */
1415
    public static function convertCharset($item)
1416
    {
1417
        if (_CHARSET !== 'windows-1256') {
0 ignored issues
show
introduced by
The condition XoopsModules\Publisher\_...RSET !== 'windows-1256' is always true.
Loading history...
1418
            return \utf8_encode($item);
1419
        }
1420
1421
        if (false !== ($unserialize = \unserialize($item))) {
1422
            foreach ($unserialize as $key => $value) {
1423
                $unserialize[$key] = @\iconv('windows-1256', 'UTF-8', $value);
1424
            }
1425
            $serialize = \serialize($unserialize);
1426
1427
            return $serialize;
1428
        }
1429
1430
        return @\iconv('windows-1256', 'UTF-8', $item);
1431
    }
1432
}
1433