Passed
Branch master (754f2c)
by Michael
03:14
created

Utility::getModuleStats()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 20
rs 9.9666
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() . "'>" . $icons->edit . "</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() . "'>" . $icons->edit . "</a>";
Loading history...
Comprehensibility Best Practice introduced by
The variable $icons seems to be never defined.
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() . "'>" . $icons->edit . "</a>";
Loading history...
184
        $delete = "<a href='category.php?op=del&amp;categoryid=" . $categoryObj->categoryid() . "'>" . $icons->delete . "</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
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...
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() . "'>" . $icons->edit . "</a>";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $icons seems to be never defined.
Loading history...
328
                    $delete = "<a href='category.php?op=del&amp;categoryid=" . $subcat->categoryid() . "'>" . $icons->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() . "'>" . $icons->edit . "</a>";
366
                    $delete      = "<a href='item.php?op=del&amp;itemid=" . $itemsObj[$i]->itemid() . "'>" . $icons->delete . "</a>";
367
                    echo '<tr>';
368
                    echo "<td class='head' align='center'>" . $itemsObj[$i]->itemid() . '</td>';
369
                    echo "<td class='even' align='left'>" . $categoryObj->name() . '</td>';
370
                    echo "<td class='even' align='left'>" . $itemsObj[$i]->getitemLink() . '</td>';
371
                    echo "<td class='even' align='center'>" . $itemsObj[$i]->getDatesub('s') . '</td>';
372
                    echo "<td class='even' align='center'> $modify $delete </td>";
373
                    echo '</tr>';
374
                }
375
            } else {
376
                $itemId = -1;
0 ignored issues
show
Unused Code introduced by
The assignment to $itemId is dead and can be removed.
Loading history...
377
                echo '<tr>';
378
                echo "<td class='head' align='center' colspan= '7'>" . \_AM_PUBLISHER_NOITEMS . '</td>';
379
                echo '</tr>';
380
            }
381
            echo "</table>\n";
382
            echo "<br>\n";
383
            $parentid         = Request::getInt('parentid', 0, 'GET');
384
            $pagenavExtraArgs = "op=mod&categoryid=$selCat&parentid=$parentid";
385
            \xoops_load('XoopsPageNav');
386
            $pagenav = new \XoopsPageNav($totalitems, $helper->getConfig('idxcat_perpage'), $startitem, 'startitem', $pagenavExtraArgs);
387
            echo '<div style="text-align:right;">' . $pagenav->renderNav() . '</div>';
388
            echo "<input type='button' name='button' onclick=\"location='item.php?op=mod&categoryid=" . $selCat . "'\" value='" . \_AM_PUBLISHER_CREATEITEM . "'>&nbsp;&nbsp;";
389
            echo '</div>';
390
        }
391
        //end of fx2024 code
392
    }
393
394
    //======================== FUNCTIONS =================================
395
396
    /**
397
     * Includes scripts in HTML header
398
     */
399
    public static function cpHeader()
400
    {
401
        \xoops_cp_header();
402
403
        //cannot use xoTheme, some conflit with admin gui
404
        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

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

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

978
        $selectedId  = \explode(',', /** @scrutinizer ignore-type */ $selectedId);
Loading history...
979
        $selectedId  = \array_map('\intval', $selectedId);
980
        $selMultiple = '';
981
        if ($multiple) {
982
            $selMultiple = " multiple='multiple'";
983
        }
984
        $ret = "<select name='" . $selectname . "[]'" . $selMultiple . " size='10'>";
985
        if ($allCatOption) {
986
            $ret .= "<option value='0'";
987
            if (\in_array(0, $selectedId, true)) {
988
                $ret .= ' selected';
989
            }
990
            $ret .= '>' . \_MB_PUBLISHER_ALLCAT . '</option>';
991
        }
992
993
        // Creating category objects
994
        $categoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $parentcategory);
995
996
        if (\count($categoriesObj) > 0) {
997
            foreach ($categoriesObj as $catId => $categoryObj) {
998
                $ret .= static::addCategoryOption($categoryObj, $selectedId);
999
            }
1000
        }
1001
        $ret .= '</select>';
1002
1003
        return $ret;
1004
    }
1005
1006
    /**
1007
     * @param int  $selectedId
1008
     * @param int  $parentcategory
1009
     * @param bool $allCatOption
1010
     * @return string
1011
     */
1012
    public static function createCategoryOptions($selectedId = 0, $parentcategory = 0, $allCatOption = true)
1013
    {
1014
        $helper = Helper::getInstance();
1015
1016
        $ret = '';
1017
        if ($allCatOption) {
1018
            $ret .= "<option value='0'";
1019
            $ret .= '>' . \_MB_PUBLISHER_ALLCAT . "</option>\n";
1020
        }
1021
1022
        // Creating category objects
1023
        $categoriesObj = $helper->getHandler('Category')->getCategories(0, 0, $parentcategory);
1024
        if (\count($categoriesObj) > 0) {
1025
            foreach ($categoriesObj as $catId => $categoryObj) {
1026
                $ret .= static::addCategoryOption($categoryObj, $selectedId);
1027
            }
1028
        }
1029
1030
        return $ret;
1031
    }
1032
1033
    /**
1034
     * @param array  $errArray
1035
     * @param string $reseturl
1036
     */
1037
    public static function renderErrors($errArray, $reseturl = '')
1038
    {
1039
        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...
1040
            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...
1041
1042
            echo '<h4 style="text-align:left;margin:0; padding-top:0;">' . \_AM_PUBLISHER_MSG_SUBMISSION_ERR;
1043
1044
            if ($reseturl) {
1045
                echo ' <a href="' . $reseturl . '">[' . \_AM_PUBLISHER_TEXT_SESSION_RESET . ']</a>';
1046
            }
1047
1048
            echo '</h4><ul>';
1049
1050
            foreach ($errArray as $key => $error) {
1051
                if (\is_array($error)) {
1052
                    foreach ($error as $err) {
1053
                        echo '<li><a href="#' . $key . '" onclick="var e = xoopsGetElementById(\'' . $key . '\'); e.focus();">' . \htmlspecialchars($err, \ENT_QUOTES | \ENT_HTML5) . '</a></li>';
1054
                    }
1055
                } else {
1056
                    echo '<li><a href="#' . $key . '" onclick="var e = xoopsGetElementById(\'' . $key . '\'); e.focus();">' . \htmlspecialchars($error, \ENT_QUOTES | \ENT_HTML5) . '</a></li>';
1057
                }
1058
            }
1059
            echo '</ul></div><br>';
1060
        }
1061
    }
1062
1063
    /**
1064
     * Generate publisher URL
1065
     *
1066
     * @param string $page
1067
     * @param array  $vars
1068
     * @param bool   $encodeAmp
1069
     * @return string
1070
     *
1071
     * @credit : xHelp module, developped by 3Dev
1072
     */
1073
    public static function makeUri($page, $vars = [], $encodeAmp = true)
1074
    {
1075
        $joinStr = '';
1076
1077
        $amp = ($encodeAmp ? '&amp;' : '&');
1078
1079
        if (!\count($vars)) {
1080
            return $page;
1081
        }
1082
1083
        $qs = '';
1084
        foreach ($vars as $key => $value) {
1085
            $qs      .= $joinStr . $key . '=' . $value;
1086
            $joinStr = $amp;
1087
        }
1088
1089
        return $page . '?' . $qs;
1090
    }
1091
1092
    /**
1093
     * @param string $subject
1094
     * @return string
1095
     */
1096
    public static function tellAFriend($subject = '')
1097
    {
1098
        if (false !== \mb_strpos($subject, '%')) {
1099
            $subject = \rawurldecode($subject);
1100
        }
1101
1102
        $targetUri = XOOPS_URL . Request::getString('REQUEST_URI', '', 'SERVER');
1103
1104
        return XOOPS_URL . '/modules/tellafriend/index.php?target_uri=' . \rawurlencode($targetUri) . '&amp;subject=' . \rawurlencode($subject);
1105
    }
1106
1107
    /**
1108
     * @param bool $another
1109
     * @param bool $withRedirect
1110
     * @param Item|null $itemObj
1111
     * @return bool|string|null
1112
     */
1113
    public static function uploadFile($another, $withRedirect, &$itemObj=null)
1114
    {
1115
        \xoops_load('XoopsMediaUploader');
1116
        //        require_once PUBLISHER_ROOT_PATH . '/class/uploader.php';
1117
1118
        //    global $publisherIsAdmin;
1119
        $helper = Helper::getInstance();
1120
1121
        $itemId  = Request::getInt('itemid', 0, 'POST');
1122
        $uid     = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->uid() : 0;
1123
        $session = Session::getInstance();
1124
        $session->set('publisher_file_filename', Request::getString('item_file_name', '', 'POST'));
1125
        $session->set('publisher_file_description', Request::getString('item_file_description', '', 'POST'));
1126
        $session->set('publisher_file_status', Request::getInt('item_file_status', 1, 'POST'));
1127
        $session->set('publisher_file_uid', $uid);
1128
        $session->set('publisher_file_itemid', $itemId);
1129
1130
        if (!\is_object($itemObj) && 0 !== $itemId) {
1131
            $itemObj = $helper->getHandler('Item')->get($itemId);
1132
        }
1133
1134
        $fileObj = $helper->getHandler('File')->create();
1135
        $fileObj->setVar('name', Request::getString('item_file_name', '', 'POST'));
1136
        $fileObj->setVar('description', Request::getString('item_file_description', '', 'POST'));
1137
        $fileObj->setVar('status', Request::getInt('item_file_status', 1, 'POST'));
1138
        $fileObj->setVar('uid', $uid);
1139
        $fileObj->setVar('itemid', $itemObj->getVar('itemid'));
1140
        $fileObj->setVar('datesub', \time());
1141
1142
        // Get available mimetypes for file uploading
1143
        $allowedMimetypes = $helper->getHandler('Mimetype')->getArrayByType();
1144
        // TODO : display the available mimetypes to the user
1145
        $errors = [];
1146
        if ($helper->getConfig('perm_upload') && \is_uploaded_file($_FILES['item_upload_file']['tmp_name'])) {
1147
            if (!$ret = $fileObj->checkUpload('item_upload_file', $allowedMimetypes, $errors)) {
0 ignored issues
show
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

1147
            if (!$ret = $fileObj->/** @scrutinizer ignore-call */ checkUpload('item_upload_file', $allowedMimetypes, $errors)) {
Loading history...
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
1148
                $errorstxt = \implode('<br>', $errors);
1149
1150
                $message = \sprintf(\_CO_PUBLISHER_MESSAGE_FILE_ERROR, $errorstxt);
1151
                if ($withRedirect) {
1152
                    \redirect_header('file.php?op=mod&itemid=' . $itemId, 5, $message);
1153
                } else {
1154
                    return $message;
1155
                }
1156
            }
1157
        }
1158
1159
        // Storing the file
1160
        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

1160
        if (!$fileObj->/** @scrutinizer ignore-call */ store($allowedMimetypes)) {
Loading history...
1161
            //        if ($withRedirect) {
1162
            //            redirect_header("file.php?op=mod&itemid=" . $fileObj->itemid(), 3, _CO_PUBLISHER_FILEUPLOAD_ERROR . static::formatErrors($fileObj->getErrors()));
1163
            //        }
1164
            try {
1165
                if ($withRedirect) {
1166
                    throw new \RuntimeException(\_CO_PUBLISHER_FILEUPLOAD_ERROR . static::formatErrors($fileObj->getErrors()));
1167
                }
1168
            } catch (\Throwable $e) {
1169
                $helper->addLog($e);
1170
                \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

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