CategoryHandler::publishedItemsCount()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Publisher;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
15
/**
16
 * @copyright       XOOPS Project (https://xoops.org)
17
 * @license         https://www.fsf.org/copyleft/gpl.html GNU public license
18
 * @since           1.0
19
 * @author          trabis <[email protected]>
20
 * @author          The SmartFactory <www.smartfactory.ca>
21
 */
22
require_once \dirname(__DIR__) . '/include/common.php';
23
24
/**
25
 * Categories handler class.
26
 * This class is responsible for providing data access mechanisms to the data source
27
 * of Category class objects.
28
 *
29
 * @author  marcan <[email protected]>
30
 */
31
class CategoryHandler extends \XoopsPersistableObjectHandler
32
{
33
    private const TABLE      = 'publisher_categories';
34
    private const ENTITY     = Category::class;
35
    private const ENTITYNAME = 'Category';
36
    private const KEYNAME    = 'categoryid';
37
    private const IDENTIFIER = 'name';
38
    /**
39
     * @var Helper
40
     */
41
    public $helper;
42
    public $publisherIsAdmin;
43
44
    public function __construct(?\XoopsDatabase $db = null, ?Helper $helper = null)
45
    {
46
        /** @var Helper $this- >helper */
47
        $this->helper           = $helper ?? Helper::getInstance();
48
        $this->db               = $db;
49
        $this->publisherIsAdmin = $this->helper->isUserAdmin();
50
        parent::__construct($db, static::TABLE, static::ENTITY, static::KEYNAME, static::IDENTIFIER);
51
    }
52
53
    /**
54
     * @param bool $isNew
55
     *
56
     * @return \XoopsObject
57
     */
58
    public function create($isNew = true)
59
    {
60
        $obj = parent::create($isNew);
61
        //        if ($isNew) {
62
        //            $obj->setDefaultPermissions();
63
        //        }
64
        $obj->helper = $this->helper;
65
66
        return $obj;
67
    }
68
69
    /**
70
     * retrieve an item
71
     *
72
     * @param int|null $id  itemid of the user
73
     *
74
     * @param null     $fields
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $fields is correct as it would always require null to be passed?
Loading history...
75
     * @return mixed reference to the <a href='psi_element://Category'>Category</a> object, FALSE if failed
76
     *                      object, FALSE if failed
77
     */
78
    public function get($id = null, $fields = null)
79
    {
80
        static $cats;
81
        if (isset($cats[$id])) {
82
            return $cats[$id];
83
        }
84
        $obj       = parent::get($id);
85
        $cats[$id] = $obj;
86
87
        return $obj;
88
    }
89
90
    /**
91
     * insert a new category in the database
92
     *
93
     * @param \XoopsObject $category reference to the {@link Category}
94
     * @param bool         $force
95
     * @return bool        FALSE if failed, TRUE if already present and unchanged or successful
96
     */
97
    public function insert(\XoopsObject $category, $force = false) //insert(&$category, $force = false)
98
    {
99
        // Auto create meta tags if empty
100
        /** @var Category $category */
101
        if (!$category->meta_keywords || !$category->meta_description) {
102
            $publisherMetagen = new Metagen($category->name, $category->getVar('meta_keywords'), $category->getVar('description'));
0 ignored issues
show
Bug introduced by
It seems like $category->getVar('meta_keywords') can also be of type array and array; however, parameter $keywords of XoopsModules\Publisher\Metagen::__construct() 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

102
            $publisherMetagen = new Metagen($category->name, /** @scrutinizer ignore-type */ $category->getVar('meta_keywords'), $category->getVar('description'));
Loading history...
Bug introduced by
It seems like $category->getVar('description') can also be of type array and array; however, parameter $description of XoopsModules\Publisher\Metagen::__construct() 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

102
            $publisherMetagen = new Metagen($category->name, $category->getVar('meta_keywords'), /** @scrutinizer ignore-type */ $category->getVar('description'));
Loading history...
103
            if (!$category->meta_keywords) {
104
                $category->setVar('meta_keywords', $publisherMetagen->keywords);
105
            }
106
            if (!$category->meta_description) {
107
                $category->setVar('meta_description', $publisherMetagen->description);
108
            }
109
        }
110
        // Auto create short_url if empty
111
        if (!$category->short_url) {
112
            $category->setVar('short_url', Metagen::generateSeoTitle($category->name('n'), false));
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

112
            $category->setVar('short_url', Metagen::generateSeoTitle($category->/** @scrutinizer ignore-call */ name('n'), false));
Loading history...
113
        }
114
        $ret = parent::insert($category, $force);
115
116
        return $ret;
117
    }
118
119
    /**
120
     * delete a category from the database
121
     *
122
     * @param \XoopsObject $category reference to the category to delete
123
     * @param bool         $force
124
     *
125
     * @return bool FALSE if failed.
126
     */
127
    public function delete(\XoopsObject $category, $force = false) //delete(&$category, $force = false)
128
    {
129
        /** @var Category $category */
130
        // Deleting this category ITEMs
131
        $criteria = new \Criteria('categoryid', $category->categoryid());
0 ignored issues
show
Bug introduced by
It seems like $category->categoryid() can also be of type array and array; however, parameter $value of Criteria::__construct() 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

131
        $criteria = new \Criteria('categoryid', /** @scrutinizer ignore-type */ $category->categoryid());
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

131
        $criteria = new \Criteria('categoryid', $category->/** @scrutinizer ignore-call */ categoryid());
Loading history...
132
        $this->helper->getHandler('Item')
133
                     ->deleteAll($criteria);
134
        unset($criteria);
135
        // Deleting the sub categories
136
        $subcats = &$this->getCategories(0, 0, $category->categoryid());
137
        foreach ($subcats as $subcat) {
138
            $this->delete($subcat);
139
        }
140
        if (!parent::delete($category, $force)) {
141
            $category->setErrors('An error while deleting.');
142
143
            return false;
144
        }
145
        $moduleId = $this->helper->getModule()
146
                                 ->getVar('mid');
147
        \xoops_groupperm_deletebymoditem($moduleId, 'category_read', $category->categoryid());
148
        \xoops_groupperm_deletebymoditem($moduleId, 'item_submit', $category->categoryid());
149
        \xoops_groupperm_deletebymoditem($moduleId, 'category_moderation', $category->categoryid());
150
151
        return true;
152
    }
153
154
    /**
155
     * retrieve categories from the database
156
     *
157
     * @param \CriteriaElement|null $criteria {@link CriteriaElement} conditions to be met
158
     * @param bool                  $idAsKey  use the categoryid as key for the array?
159
     *
160
     * @param bool                  $as_object
161
     * @return array array of <a href='psi_element://XoopsItem'>XoopsItem</a> objects
162
     */
163
    public function &getObjects(?\CriteriaElement $criteria = null, $idAsKey = false, $as_object = true) //&getObjects($criteria = null, $idAsKey = false)
164
    {
165
        $ret        = [];
166
        $theObjects = parent::getObjects($criteria, true);
167
        foreach ($theObjects as $theObject) {
168
            if ($idAsKey) {
169
                $ret[$theObject->categoryid()] = $theObject;
170
            } else {
171
                $ret[] = $theObject;
172
            }
173
            unset($theObject);
174
        }
175
176
        return $ret;
177
    }
178
179
    /**
180
     * @param int    $limit
181
     * @param int    $start
182
     * @param int    $parentid
183
     * @param string $sort
184
     * @param string $order
185
     * @param bool   $idAsKey
186
     *
187
     * @return array
188
     */
189
    public function &getCategories($limit = 0, $start = 0, $parentid = 0, $sort = 'weight', $order = 'ASC', $idAsKey = true)
190
    {
191
        $ret      = [];
192
        $criteria = new \CriteriaCompo();
193
        $criteria->setSort($sort);
194
        $criteria->order = $order; // used to fix bug in setOrder() for XOOPS < 2.5.10
195
        if (-1 != $parentid) {
196
            $criteria->add(new \Criteria('parentid', (int)$parentid));
197
        }
198
        if (!$this->publisherIsAdmin) {
199
            $criteria2 = new \CriteriaCompo();
200
            /** @var PermissionHandler $permissionHandler */
201
            $permissionHandler = $this->helper->getHandler('Permission');
202
            $categoriesGranted = $permissionHandler->getGrantedItems('category_read');
203
            if (\count($categoriesGranted) > 0) {
204
                $criteria2->add(new \Criteria('categoryid', '(' . \implode(',', $categoriesGranted) . ')', 'IN'));
205
            } else {
206
                return $ret;
207
            }
208
            if (\is_object($GLOBALS['xoopsUser'])) {
209
                $criteria2->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR');
210
            }
211
            $criteria->add($criteria2);
212
        }
213
        $criteria->setStart($start);
214
        $criteria->setLimit($limit);
215
        $ret = $this->getObjects($criteria, $idAsKey);
216
217
        return $ret;
218
    }
219
220
    /**
221
     * @param $category
222
     * @param $level
223
     * @param $catArray
224
     * @param $catResult
225
     */
226
    public function getSubCatArray($category, $level, $catArray, $catResult): void
227
    {
228
        global $theresult;
229
        $spaces = '';
230
        for ($j = 0; $j < $level; ++$j) {
231
            $spaces .= '--';
232
        }
233
        $theresult[$category['categoryid']] = $spaces . $category['name'];
234
        if (isset($catArray[$category['categoryid']])) {
235
            ++$level;
236
            foreach ($catArray[$category['categoryid']] as $parentid => $cat) {
237
                $this->getSubCatArray($cat, $level, $catArray, $catResult);
238
            }
239
        }
240
    }
241
242
    /**
243
     * @return array
244
     */
245
    public function &getCategoriesForSubmit()
246
    {
247
        global $theresult;
248
        $ret      = [];
249
        $criteria = new \CriteriaCompo();
250
        $criteria->setSort('name');
251
        $criteria->order = 'ASC'; // patch for XOOPS <= 2.5.10, does not set order correctly using setOrder() method
252
        if (!$this->publisherIsAdmin) {
253
            $categoriesGranted = $this->helper->getHandler('Permission')
254
                                              ->getGrantedItems('item_submit');
255
            if (\count($categoriesGranted) > 0) {
256
                $criteria->add(new \Criteria('categoryid', '(' . \implode(',', $categoriesGranted) . ')', 'IN'));
257
            } else {
258
                return $ret;
259
            }
260
            if (\is_object($GLOBALS['xoopsUser'])) {
261
                $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR');
262
            }
263
        }
264
        $categories = $this->getAll($criteria, ['categoryid', 'parentid', 'name'], false, false);
265
        if (0 == \count($categories)) {
266
            return $ret;
267
        }
268
        $catArray = [];
269
        foreach ($categories as $cat) {
270
            $catArray[$cat['parentid']][$cat['categoryid']] = $cat;
271
        }
272
        // Needs to have permission on at least 1 top level category
273
        if (!isset($catArray[0])) {
274
            return $ret;
275
        }
276
        $catResult = [];
277
        foreach ($catArray[0] as $thecat) {
278
            $level = 0;
279
            $this->getSubCatArray($thecat, $level, $catArray, $catResult);
280
        }
281
282
        return $theresult; //this is a global
283
    }
284
285
    /**
286
     * @return array
287
     */
288
    public function getCategoriesForSearch()
289
    {
290
        global $theresult;
291
292
        $ret      = [];
293
        $criteria = new \CriteriaCompo();
294
        $criteria->setSort('name');
295
        $criteria->order = 'ASC'; // patch for XOOPS <= 2.5.10, does not set order correctly using setOrder() method
296
        if (!$this->publisherIsAdmin) {
297
            $categoriesGranted = $this->helper->getHandler('Permission')
298
                                              ->getGrantedItems('category_read');
299
            if (\count($categoriesGranted) > 0) {
300
                $criteria->add(new \Criteria('categoryid', '(' . \implode(',', $categoriesGranted) . ')', 'IN'));
301
            } else {
302
                return $ret;
303
            }
304
            if (\is_object($GLOBALS['xoopsUser'])) {
305
                $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR');
306
            }
307
        }
308
        $categories = $this->getAll($criteria, ['categoryid', 'parentid', 'name'], false, false);
309
        if (0 == \count($categories)) {
310
            return $ret;
311
        }
312
        $catArray = [];
313
        foreach ($categories as $cat) {
314
            $catArray[$cat['parentid']][$cat['categoryid']] = $cat;
315
        }
316
        // Needs to have permission on at least 1 top level category
317
        if (!isset($catArray[0])) {
318
            return $ret;
319
        }
320
        $catResult = [];
321
        foreach ($catArray[0] as $thecat) {
322
            $level = 0;
323
            $this->getSubCatArray($thecat, $level, $catArray, $catResult);
324
        }
325
326
        return $theresult; //this is a global
327
    }
328
329
    /**
330
     * @param int $parentid
331
     *
332
     * @return int
333
     */
334
    public function getCategoriesCount($parentid = 0)
335
    {
336
        if (-1 == $parentid) {
337
            return $this->getCount();
338
        }
339
        $criteria = new \CriteriaCompo();
340
        if (isset($parentid) && (-1 != $parentid)) {
341
            $criteria->add(new \Criteria('parentid', $parentid));
342
            if (!$this->publisherIsAdmin) {
343
                $categoriesGranted = $this->helper->getHandler('Permission')
344
                                                  ->getGrantedItems('category_read');
345
                if (\count($categoriesGranted) > 0) {
346
                    $criteria->add(new \Criteria('categoryid', '(' . \implode(',', $categoriesGranted) . ')', 'IN'));
347
                } else {
348
                    return 0;
349
                }
350
                if (\is_object($GLOBALS['xoopsUser'])) {
351
                    $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR');
352
                }
353
            }
354
        }
355
356
        return $this->getCount($criteria);
357
    }
358
359
    /**
360
     * Get all subcats and put them in an array indexed by parent id
361
     *
362
     * @param array $categories
363
     *
364
     * @return array
365
     */
366
    public function getSubCats($categories)
367
    {
368
        $criteria = new \CriteriaCompo(new \Criteria('parentid', '(' . \implode(',', \array_keys($categories)) . ')', 'IN'));
369
        $ret      = [];
370
        if (!$this->publisherIsAdmin) {
371
            $categoriesGranted = $this->helper->getHandler('Permission')
372
                                              ->getGrantedItems('category_read');
373
            if (\count($categoriesGranted) > 0) {
374
                $criteria->add(new \Criteria('categoryid', '(' . \implode(',', $categoriesGranted) . ')', 'IN'));
375
            } else {
376
                return $ret;
377
            }
378
379
            if (\is_object($GLOBALS['xoopsUser'])) {
380
                $criteria->add(new \Criteria('moderator', $GLOBALS['xoopsUser']->getVar('uid')), 'OR');
381
            }
382
        }
383
        $criteria->setSort('weight');
384
        $criteria->order = 'ASC'; // patch for XOOPS <= 2.5.10, does not set order correctly using setOrder() method
385
        $subcats         = $this->getObjects($criteria, true);
386
        /** @var Category $subcat */
387
        foreach ($subcats as $subcat) {
388
            $ret[(int)$subcat->getVar('parentid')][$subcat->getVar('categoryid')] = $subcat;
389
        }
390
391
        return $ret;
392
    }
393
394
    /**
395
     * delete categories matching a set of conditions
396
     *
397
     * @param \CriteriaElement|null $criteria {@link CriteriaElement}
398
     *
399
     * @param bool                  $force
400
     * @param bool                  $asObject
401
     * @return bool FALSE if deletion failed
402
     */
403
    public function deleteAll(?\CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null)
404
    {
405
        $categories = $this->getObjects($criteria);
406
        foreach ($categories as $category) {
407
            if (!$this->delete($category)) {
408
                return false;
409
            }
410
        }
411
412
        return true;
413
    }
414
415
    /**
416
     * @param int $catId
417
     *
418
     * @return mixed
419
     */
420
    public function publishedItemsCount($catId = 0)
421
    {
422
        $status = [Constants::PUBLISHER_STATUS_PUBLISHED];
423
424
        return $this->itemsCount($catId, $status);
425
    }
426
427
    /**
428
     * @param int   $catId
429
     * @param array $status
430
     *
431
     * @return mixed
432
     */
433
    public function itemsCount($catId = 0, $status = '')
434
    {
435
        /** @var ItemHandler $itemHandler */
436
        $itemHandler = $this->helper->getHandler('Item');
437
438
        return $itemHandler->getCountsByCat($catId, $status);
0 ignored issues
show
Bug introduced by
It seems like $status can also be of type string; however, parameter $status of XoopsModules\Publisher\I...ndler::getCountsByCat() does only seem to accept array, 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

438
        return $itemHandler->getCountsByCat($catId, /** @scrutinizer ignore-type */ $status);
Loading history...
439
    }
440
}
441