Passed
Branch master (7e303a)
by Michael
02:15
created

ItemHandler::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
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       The XUUPS Project http://sourceforge.net/projects/xuups/
17
 * @license         http://www.fsf.org/copyleft/gpl.html GNU public license
18
 * @package         Publisher
19
 * @since           1.0
20
 * @author          trabis <[email protected]>
21
 * @author          The SmartFactory <www.smartfactory.ca>
22
 */
23
24
use Xmf\Request;
25
use XoopsModules\Publisher;
26
use XoopsModules\Publisher\Constants;
27
28
//namespace Publisher;
29
30
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
31
require_once dirname(__DIR__) . '/include/common.php';
32
33
/**
34
 * Items handler class.
35
 * This class is responsible for providing data access mechanisms to the data source
36
 * of Q&A class objects.
37
 *
38
 * @author  marcan <[email protected]>
39
 * @package Publisher
40
 */
41
class ItemHandler extends \XoopsPersistableObjectHandler
42
{
43
    /**
44
     * @var Publisher\Helper
45
     */
46
    public $helper;
47
48
    protected $resultCatCounts = [];
49
50
    /**
51
     * @param null|\XoopsDatabase $db
52
     */
53
    public function __construct(\XoopsDatabase $db = null)
54
    {
55
        /** @var Publisher\Helper $this->helper */
56
        parent::__construct($db, 'publisher_items', Item::class, 'itemid', 'title');
57
        $this->helper = Publisher\Helper::getInstance();
58
    }
59
60
    /**
61
     * @param bool $isNew
62
     *
63
     * @return \XoopsObject
64
     */
65
    public function create($isNew = true)
66
    {
67
        $obj = parent::create($isNew);
68
        if ($isNew) {
69
            $obj->setDefaultPermissions();
0 ignored issues
show
Bug introduced by
The method setDefaultPermissions() 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

69
            $obj->/** @scrutinizer ignore-call */ 
70
                  setDefaultPermissions();
Loading history...
70
        }
71
72
        return $obj;
73
    }
74
75
    /**
76
     * retrieve an item
77
     *
78
     * @param int   $id     itemid of the user
79
     *
80
     * @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...
81
     * @return mixed reference to the <a href='psi_element://Item'>Item</a> object, FALSE if failed
82
     *                      object, FALSE if failed
83
     */
84
    public function get($id = null, $fields = null)
85
    {
86
        $obj = parent::get($id);
87
        if (is_object($obj)) {
88
            $obj->assignOtherProperties();
0 ignored issues
show
Bug introduced by
The method assignOtherProperties() 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

88
            $obj->/** @scrutinizer ignore-call */ 
89
                  assignOtherProperties();
Loading history...
89
        }
90
91
        return $obj;
92
    }
93
94
    /**
95
     * insert a new item in the database
96
     *
97
     * @param \XoopsObject $item reference to the {@link Item}
98
     *                           object
99
     * @param bool         $force
100
     *
101
     * @return bool FALSE if failed, TRUE if already present and unchanged or successful
102
     */
103
    public function insert(\XoopsObject $item, $force = false)  //insert(&$item, $force = false)
104
    {
105
        if (!$item->meta_keywords() || !$item->meta_description() || !$item->short_url()) {
0 ignored issues
show
Bug introduced by
The method short_url() 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

105
        if (!$item->meta_keywords() || !$item->meta_description() || !$item->/** @scrutinizer ignore-call */ short_url()) {
Loading history...
Bug introduced by
The method meta_keywords() 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

105
        if (!$item->/** @scrutinizer ignore-call */ meta_keywords() || !$item->meta_description() || !$item->short_url()) {
Loading history...
Bug introduced by
The method meta_description() 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

105
        if (!$item->meta_keywords() || !$item->/** @scrutinizer ignore-call */ meta_description() || !$item->short_url()) {
Loading history...
106
            $publisherMetagen = new Publisher\Metagen($item->getTitle(), $item->getVar('meta_keywords'), $item->getVar('summary'));
0 ignored issues
show
Bug introduced by
It seems like $item->getVar('summary') 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

106
            $publisherMetagen = new Publisher\Metagen($item->getTitle(), $item->getVar('meta_keywords'), /** @scrutinizer ignore-type */ $item->getVar('summary'));
Loading history...
Bug introduced by
The method getTitle() 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

106
            $publisherMetagen = new Publisher\Metagen($item->/** @scrutinizer ignore-call */ getTitle(), $item->getVar('meta_keywords'), $item->getVar('summary'));
Loading history...
Bug introduced by
It seems like $item->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

106
            $publisherMetagen = new Publisher\Metagen($item->getTitle(), /** @scrutinizer ignore-type */ $item->getVar('meta_keywords'), $item->getVar('summary'));
Loading history...
107
            // Auto create meta tags if empty
108
            if (!$item->meta_keywords()) {
109
                $item->setVar('meta_keywords', $publisherMetagen->keywords);
110
            }
111
            if (!$item->meta_description()) {
112
                $item->setVar('meta_description', $publisherMetagen->description);
113
            }
114
            // Auto create short_url if empty
115
            if (!$item->short_url()) {
116
                $item->setVar('short_url', mb_substr(Metagen::generateSeoTitle($item->getVar('title', 'n'), false), 0, 254));
117
            }
118
        }
119
        if (!parent::insert($item, $force)) {
120
            return false;
121
        }
122
        if (xoops_isActiveModule('tag')) {
123
            // Storing tags information
124
            $tagHandler = \XoopsModules\Tag\Helper::getInstance()->getHandler('Tag'); // xoops_getModuleHandler('tag', 'tag');
125
            $tagHandler->updateByItem($item->getVar('item_tag'), $item->getVar('itemid'), PUBLISHER_DIRNAME, 0);
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_DIRNAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
126
        }
127
128
        return true;
129
    }
130
131
    /**
132
     * delete an item from the database
133
     *
134
     * @param \XoopsObject $item reference to the ITEM to delete
135
     * @param bool         $force
136
     *
137
     * @return bool FALSE if failed.
138
     */
139
    public function delete(\XoopsObject $item, $force = false)
140
    {
141
        // Deleting the files
142
        if (!$this->helper->getHandler('File')->deleteItemFiles($item)) {
0 ignored issues
show
Bug introduced by
The method deleteItemFiles() does not exist on XoopsObjectHandler. Did you maybe mean delete()? ( Ignorable by Annotation )

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

142
        if (!$this->helper->getHandler('File')->/** @scrutinizer ignore-call */ deleteItemFiles($item)) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
143
            $item->setErrors(_AM_PUBLISHER_FILE_DELETE_ERROR);
144
        }
145
        if (!parent::delete($item, $force)) {
146
            $item->setErrors(_AM_PUBLISHER_ITEM_DELETE_ERROR);
147
148
            return false;
149
        }
150
        // Removing tags information
151
        if (xoops_isActiveModule('tag')) {
152
            $tagHandler = \XoopsModules\Tag\Helper::getInstance()->getHandler('Tag'); // xoops_getModuleHandler('tag', 'tag');
153
            $tagHandler->updateByItem('', $item->getVar('itemid'), PUBLISHER_DIRNAME, 0);
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Publisher\PUBLISHER_DIRNAME was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
154
        }
155
156
        return true;
157
    }
158
159
    /**
160
     * retrieve items from the database
161
     *
162
     * @param \CriteriaElement $criteria     {@link CriteriaElement}
163
     *                                       conditions to be met
164
     * @param  bool|string     $idKey        what shall we use as array key ? none, itemid, categoryid
165
     * @param  bool            $as_object
166
     * @param  string          $notNullFields
167
     * @return array           array of <a href='psi_element://Item'>Item</a> objects
168
     *                                       objects
169
     */
170
171
    public function &getObjects(\CriteriaElement $criteria = null, $idKey = 'none', $as_object = true, $notNullFields = null)
172
    {
173
        $limit         = $start = 0;
174
        $ret           = [];
175
        $notNullFields = (null !== $notNullFields) ?: '';
176
177
        $sql = 'SELECT * FROM ' . $this->db->prefix($this->helper->getDirname() . '_items');
178
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
179
            $whereClause = $criteria->renderWhere();
0 ignored issues
show
Bug introduced by
The method renderWhere() does not exist on CriteriaElement. Did you maybe mean render()? ( Ignorable by Annotation )

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

179
            /** @scrutinizer ignore-call */ 
180
            $whereClause = $criteria->renderWhere();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
180
            if ('WHERE ()' !== $whereClause) {
181
                $sql .= ' ' . $criteria->renderWhere();
182
                if (!empty($notNullFields)) {
183
                    $sql .= $this->notNullFieldClause($notNullFields, true);
0 ignored issues
show
Bug introduced by
It seems like $notNullFields can also be of type true; however, parameter $notNullFields of XoopsModules\Publisher\I...r::notNullFieldClause() does only seem to accept string|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

183
                    $sql .= $this->notNullFieldClause(/** @scrutinizer ignore-type */ $notNullFields, true);
Loading history...
184
                }
185
            } elseif (!empty($notNullFields)) {
186
                $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields);
187
            }
188
            if ('' != $criteria->getSort()) {
189
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
190
            }
191
            $limit = $criteria->getLimit();
192
            $start = $criteria->getStart();
193
        } elseif (!empty($notNullFields)) {
194
            $sql .= $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields);
195
        }
196
        $result = $this->db->query($sql, $limit, $start);
197
        if (!$result || 0 === $GLOBALS['xoopsDB']->getRowsNum($result)) {
198
            return $ret;
199
        }
200
        $theObjects = [];
201
        while (false !== ($myrow = $this->db->fetchArray($result))) {
202
            $item = new Item();
203
            $item->assignVars($myrow);
204
            $theObjects[$myrow['itemid']] = $item;
205
            unset($item);
206
        }
207
        foreach ($theObjects as $theObject) {
208
            if ('none' === $idKey) {
209
                $ret[] = $theObject;
210
            } elseif ('itemid' === $idKey) {
211
                $ret[$theObject->itemid()] = $theObject;
212
            } else {
213
                $ret[$theObject->getVar($idKey)][$theObject->itemid()] = $theObject;
214
            }
215
            unset($theObject);
216
        }
217
218
        return $ret;
219
    }
220
221
    /**
222
     * count items matching a condition
223
     *
224
     * @param \CriteriaElement $criteria {@link CriteriaElement}
225
     *                                   to match
226
     * @param string           $notNullFields
227
     *
228
     * @return int count of items
229
     */
230
    public function getCount(\CriteriaElement $criteria = null, $notNullFields = '')
231
    {
232
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix($this->helper->getDirname() . '_items');
233
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
234
            $whereClause = $criteria->renderWhere();
235
            if ('WHERE ()' !== $whereClause) {
236
                $sql .= ' ' . $criteria->renderWhere();
237
                if (!empty($notNullFields)) {
238
                    $sql .= $this->notNullFieldClause($notNullFields, true);
239
                }
240
            } elseif (!empty($notNullFields)) {
241
                $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields);
242
            }
243
        } elseif (!empty($notNullFields)) {
244
            $sql .= ' WHERE ' . $this->notNullFieldClause($notNullFields);
245
        }
246
        $result = $this->db->query($sql);
247
        if (!$result) {
248
            return 0;
249
        }
250
        list($count) = $this->db->fetchRow($result);
251
252
        return $count;
253
    }
254
255
    /**
256
     * @param  int           $categoryid
257
     * @param  string|array  $status
258
     * @param  string        $notNullFields
259
     * @param                $criteriaPermissions
260
     * @return \CriteriaCompo
261
     */
262
    private function getItemsCriteria($categoryid = -1, $status = '', $notNullFields = '', $criteriaPermissions)
0 ignored issues
show
Unused Code introduced by
The parameter $notNullFields 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

262
    private function getItemsCriteria($categoryid = -1, $status = '', /** @scrutinizer ignore-unused */ $notNullFields = '', $criteriaPermissions)

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...
263
    {
264
        //        global $publisherIsAdmin;
265
        //        $ret = 0;
266
        //        if (!$publisherIsAdmin) {
267
        //            $criteriaPermissions = new \CriteriaCompo();
268
        //            // Categories for which user has access
269
        //            $categoriesGranted = $this->helper->getHandler('Permission')->getGrantedItems('category_read');
270
        //            if (!empty($categoriesGranted)) {
271
        //                $grantedCategories = new \Criteria('categoryid', "(" . implode(',', $categoriesGranted) . ")", 'IN');
272
        //                $criteriaPermissions->add($grantedCategories, 'AND');
273
        //            } else {
274
        //                return $ret;
275
        //            }
276
        //        }
277
        if (null !== $categoryid && -1 != $categoryid) {
278
            $criteriaCategory = new \Criteria('categoryid', $categoryid);
279
        }
280
        $criteriaStatus = new \CriteriaCompo();
281
        if (!empty($status) && is_array($status)) {
282
            foreach ($status as $v) {
283
                $criteriaStatus->add(new \Criteria('status', $v), 'OR');
284
            }
285
        } elseif (!empty($status) && -1 != $status) {
286
            $criteriaStatus->add(new \Criteria('status', $status), 'OR');
287
        }
288
        $criteria = new \CriteriaCompo();
289
        if (!empty($criteriaCategory)) {
290
            $criteria->add($criteriaCategory);
291
        }
292
        if (!empty($criteriaPermissions)) {
293
            $criteria->add($criteriaPermissions);
294
        }
295
        if (!empty($criteriaStatus)) {
296
            $criteria->add($criteriaStatus);
297
        }
298
299
        return $criteria;
300
    }
301
302
    /**
303
     * @param        $categoryid
304
     * @param string $status
305
     * @param string $notNullFields
306
     *
307
     * @return int
308
     */
309
    public function getItemsCount($categoryid = -1, $status = '', $notNullFields = '')
310
    {
311
312
        //        global $publisherIsAdmin;
313
        $criteriaPermissions = '';
314
        if (!$GLOBALS['publisherIsAdmin']) {
315
            $criteriaPermissions = new \CriteriaCompo();
316
            // Categories for which user has access
317
            $categoriesGranted = $this->helper->getHandler('Permission')->getGrantedItems('category_read');
0 ignored issues
show
Bug introduced by
The method getGrantedItems() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsPersistableObjectHandler or XoopsModules\Publisher\PermissionHandler. ( Ignorable by Annotation )

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

317
            $categoriesGranted = $this->helper->getHandler('Permission')->/** @scrutinizer ignore-call */ getGrantedItems('category_read');
Loading history...
318
            if (!empty($categoriesGranted)) {
319
                $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN');
320
                $criteriaPermissions->add($grantedCategories, 'AND');
321
            } else {
322
                return 0;
323
            }
324
        }
325
        //        $ret = array();
326
        $criteria = $this->getItemsCriteria($categoryid, $status, $notNullFields, $criteriaPermissions);
327
        /*
328
                if (isset($categoryid) && $categoryid != -1) {
329
                    $criteriaCategory = new \Criteria('categoryid', $categoryid);
330
                }
331
                $criteriaStatus = new \CriteriaCompo();
332
                if (!empty($status) && is_array($status)) {
333
                    foreach ($status as $v) {
334
                        $criteriaStatus->add(new \Criteria('status', $v), 'OR');
335
                    }
336
                } elseif (!empty($status) && $status != -1) {
337
                    $criteriaStatus->add(new \Criteria('status', $status), 'OR');
338
                }
339
                $criteria = new \CriteriaCompo();
340
                if (!empty($criteriaCategory)) {
341
                    $criteria->add($criteriaCategory);
342
                }
343
                if (!empty($criteriaPermissions)) {
344
                    $criteria->add($criteriaPermissions);
345
                }
346
                if (!empty($criteriaStatus)) {
347
                    $criteria->add($criteriaStatus);
348
                }
349
        */
350
        $ret = $this->getCount($criteria, $notNullFields);
351
352
        return $ret;
353
    }
354
355
    /**
356
     * @param int    $limit
357
     * @param int    $start
358
     * @param int    $categoryid
359
     * @param string $sort
360
     * @param string $order
361
     * @param string $notNullFields
362
     * @param bool   $asObject
363
     * @param string $idKey
364
     *
365
     * @return array
366
     */
367
    public function getAllPublished($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none')
368
    {
369
        $otherCriteria = new \Criteria('datesub', time(), '<=');
370
371
        return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_PUBLISHED], $categoryid, $sort, $order, $notNullFields, $asObject, $otherCriteria, $idKey);
372
    }
373
374
    /**
375
     * @param Item $obj
376
     *
377
     * @return bool
378
     */
379
    public function getPreviousPublished($obj)
380
    {
381
        $ret           = false;
382
        $otherCriteria = new \CriteriaCompo();
383
        $otherCriteria->add(new \Criteria('datesub', $obj->getVar('datesub'), '<'));
0 ignored issues
show
Bug introduced by
It seems like $obj->getVar('datesub') 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

383
        $otherCriteria->add(new \Criteria('datesub', /** @scrutinizer ignore-type */ $obj->getVar('datesub'), '<'));
Loading history...
384
        $objs = $this->getItems(1, 0, [Constants::PUBLISHER_STATUS_PUBLISHED], $obj->getVar('categoryid'), 'datesub', 'DESC', '', true, $otherCriteria, 'none');
385
        if (count($objs) > 0) {
386
            $ret = $objs[0];
387
        }
388
389
        return $ret;
390
    }
391
392
    /**
393
     * @param Item $obj
394
     *
395
     * @return bool
396
     */
397
    public function getNextPublished($obj)
398
    {
399
        $ret           = false;
400
        $otherCriteria = new \CriteriaCompo();
401
        $otherCriteria->add(new \Criteria('datesub', $obj->getVar('datesub'), '>'));
0 ignored issues
show
Bug introduced by
It seems like $obj->getVar('datesub') 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

401
        $otherCriteria->add(new \Criteria('datesub', /** @scrutinizer ignore-type */ $obj->getVar('datesub'), '>'));
Loading history...
402
        $otherCriteria->add(new \Criteria('datesub', time(), '<='));
403
        $objs = $this->getItems(1, 0, [Constants::PUBLISHER_STATUS_PUBLISHED], $obj->getVar('categoryid'), 'datesub', 'ASC', '', true, $otherCriteria, 'none');
404
        if (count($objs) > 0) {
405
            $ret = $objs[0];
406
        }
407
408
        return $ret;
409
    }
410
411
    /**
412
     * @param int    $limit
413
     * @param int    $start
414
     * @param int    $categoryid
415
     * @param string $sort
416
     * @param string $order
417
     * @param string $notNullFields
418
     * @param bool   $asObject
419
     * @param string $idKey
420
     *
421
     * @return array
422
     */
423
    public function getAllSubmitted($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none')
424
    {
425
        return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_SUBMITTED], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey);
426
    }
427
428
    /**
429
     * @param int    $limit
430
     * @param int    $start
431
     * @param int    $categoryid
432
     * @param string $sort
433
     * @param string $order
434
     * @param string $notNullFields
435
     * @param bool   $asObject
436
     * @param string $idKey
437
     *
438
     * @return array
439
     */
440
    public function getAllOffline($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none')
441
    {
442
        return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_OFFLINE], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey);
443
    }
444
445
    /**
446
     * @param int    $limit
447
     * @param int    $start
448
     * @param int    $categoryid
449
     * @param string $sort
450
     * @param string $order
451
     * @param string $notNullFields
452
     * @param bool   $asObject
453
     * @param string $idKey
454
     *
455
     * @return array
456
     */
457
    public function getAllRejected($limit = 0, $start = 0, $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $idKey = 'none')
458
    {
459
        return $this->getItems($limit, $start, [Constants::PUBLISHER_STATUS_REJECTED], $categoryid, $sort, $order, $notNullFields, $asObject, null, $idKey);
460
    }
461
462
    /**
463
     * @param  int          $limit
464
     * @param  int          $start
465
     * @param  array|string $status
466
     * @param  int          $categoryid
467
     * @param  string       $sort
468
     * @param  string       $order
469
     * @param  string       $notNullFields
470
     * @param  bool         $asObject
471
     * @param  null         $otherCriteria
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $otherCriteria is correct as it would always require null to be passed?
Loading history...
472
     * @param  bool|string  $idKey
473
     * @return array
474
     * @internal param bool $asObject
475
     */
476
    public function getItems($limit = 0, $start = 0, $status = '', $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', $asObject = true, $otherCriteria = null, $idKey = 'none')
0 ignored issues
show
Unused Code introduced by
The parameter $asObject 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

476
    public function getItems($limit = 0, $start = 0, $status = '', $categoryid = -1, $sort = 'datesub', $order = 'DESC', $notNullFields = '', /** @scrutinizer ignore-unused */ $asObject = true, $otherCriteria = null, $idKey = 'none')

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...
477
    {
478
        //        global $publisherIsAdmin;
479
        $criteriaPermissions = '';
480
        if (!$GLOBALS['publisherIsAdmin']) {
481
            $criteriaPermissions = new \CriteriaCompo();
482
            // Categories for which user has access
483
            $categoriesGranted = $this->helper->getHandler('Permission')->getGrantedItems('category_read');
484
            if (!empty($categoriesGranted)) {
485
                $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN');
486
                $criteriaPermissions->add($grantedCategories, 'AND');
487
            } else {
488
                return [];
489
            }
490
        }
491
492
        $criteria = $this->getItemsCriteria($categoryid, $status, $notNullFields, $criteriaPermissions);
493
        /*
494
                if (isset($categoryid) && $categoryid != -1) {
495
                    $criteriaCategory = new \Criteria('categoryid', $categoryid);
496
                }
497
                $criteriaStatus = new \CriteriaCompo();
498
                if (!empty($status) && is_array($status)) {
499
                    foreach ($status as $v) {
500
                        $criteriaStatus->add(new \Criteria('status', $v), 'OR');
501
                    }
502
                } elseif (!empty($status) && $status != -1) {
503
                    $criteriaStatus->add(new \Criteria('status', $status), 'OR');
504
                }
505
                $criteria = new \CriteriaCompo();
506
                if (!empty($criteriaCategory)) {
507
                    $criteria->add($criteriaCategory);
508
                }
509
                if (!empty($criteriaPermissions)) {
510
                    $criteria->add($criteriaPermissions);
511
                }
512
                if (!empty($criteriaStatus)) {
513
                    $criteria->add($criteriaStatus);
514
                }
515
        */
516
        //        $ret = array();
517
518
        if (!empty($otherCriteria)) {
519
            $criteria->add($otherCriteria);
520
        }
521
        $criteria->setLimit($limit);
522
        $criteria->setStart($start);
523
        $criteria->setSort($sort);
524
        $criteria->setOrder($order);
525
        $ret = $this->getObjects($criteria, $idKey, $notNullFields);
0 ignored issues
show
Bug introduced by
$notNullFields of type string is incompatible with the type boolean expected by parameter $as_object of XoopsModules\Publisher\ItemHandler::getObjects(). ( Ignorable by Annotation )

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

525
        $ret = $this->getObjects($criteria, $idKey, /** @scrutinizer ignore-type */ $notNullFields);
Loading history...
526
527
        return $ret;
528
    }
529
530
    /**
531
     * @param string $field
532
     * @param string $status
533
     * @param int    $categoryId
534
     *
535
     * @return bool
536
     */
537
    public function getRandomItem($field = '', $status = '', $categoryId = -1)
538
    {
539
        $ret           = false;
540
        $notNullFields = $field;
541
        // Getting the number of published Items
542
        $totalItems = $this->getItemsCount($categoryId, $status, $notNullFields);
543
        if ($totalItems > 0) {
544
            --$totalItems;
545
            mt_srand((float)microtime() * 1000000);
0 ignored issues
show
Bug introduced by
(double)microtime() * 1000000 of type double is incompatible with the type integer expected by parameter $seed of mt_srand(). ( Ignorable by Annotation )

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

545
            mt_srand(/** @scrutinizer ignore-type */ (float)microtime() * 1000000);
Loading history...
546
            $entryNumber = mt_rand(0, $totalItems);
547
            $item        = $this->getItems(1, $entryNumber, $status, $categoryId, $sort = 'datesub', $order = 'DESC', $notNullFields);
548
            if ($item) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $item 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...
549
                $ret = $item[0];
550
            }
551
        }
552
553
        return $ret;
554
    }
555
556
    /**
557
     * delete Items matching a set of conditions
558
     *
559
     * @param \CriteriaElement $criteria {@link CriteriaElement}
560
     *
561
     * @param  bool            $force
562
     * @param  bool            $asObject
563
     * @return bool FALSE if deletion failed
564
     */
565
    public function deleteAll(\CriteriaElement $criteria = null, $force = true, $asObject = false) //deleteAll($criteria = null)
566
    {
567
        //todo resource consuming, use get list instead?
568
        $items = $this->getObjects($criteria);
569
        foreach ($items as $item) {
570
            $this->delete($item);
571
        }
572
573
        return true;
574
    }
575
576
    /**
577
     * @param $itemid
578
     *
579
     * @return bool
580
     */
581
    public function updateCounter($itemid)
582
    {
583
        $sql = 'UPDATE ' . $this->db->prefix($this->helper->getDirname() . '_items') . ' SET counter=counter+1 WHERE itemid = ' . $itemid;
584
        if ($this->db->queryF($sql)) {
585
            return true;
586
        }
587
        return false;
588
    }
589
590
    /**
591
     * @param string|array $notNullFields
592
     * @param bool         $withAnd
593
     *
594
     * @return string
595
     */
596
    public function notNullFieldClause($notNullFields = '', $withAnd = false)
597
    {
598
        $ret = '';
599
        if ($withAnd) {
600
            $ret .= ' AND ';
601
        }
602
        if (!empty($notNullFields) && is_array($notNullFields)) {
603
            foreach ($notNullFields as $v) {
604
                $ret .= " ($v IS NOT NULL AND $v <> ' ' )";
605
            }
606
        } elseif (!empty($notNullFields)) {
607
            $ret .= " ($notNullFields IS NOT NULL AND $notNullFields <> ' ' )";
608
        }
609
610
        return $ret;
611
    }
612
613
    /**
614
     * @param array        $queryArray
615
     * @param string       $andor
616
     * @param int          $limit
617
     * @param int          $offset
618
     * @param int          $userid
619
     * @param array        $categories
620
     * @param int          $sortby
621
     * @param string|array $searchin
622
     * @param string       $extra
623
     *
624
     * @return array
625
     */
626
    public function getItemsFromSearch($queryArray = [], $andor = 'AND', $limit = 0, $offset = 0, $userid = 0, $categories = [], $sortby = 0, $searchin = '', $extra = '')
0 ignored issues
show
Unused Code introduced by
The parameter $extra 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

626
    public function getItemsFromSearch($queryArray = [], $andor = 'AND', $limit = 0, $offset = 0, $userid = 0, $categories = [], $sortby = 0, $searchin = '', /** @scrutinizer ignore-unused */ $extra = '')

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...
627
    {
628
        //        global $publisherIsAdmin;
629
        $ret = [];
630
        /* @var  $grouppermHandler \XoopsGroupPermHandler */
631
        $grouppermHandler = xoops_getHandler('groupperm');
632
        $groups           = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
633
        $searchin         = empty($searchin) ? ['title', 'body', 'summary'] : (is_array($searchin) ? $searchin : [$searchin]);
634
        if (in_array('all', $searchin) || 0 == count($searchin)) {
635
            $searchin = ['title', 'subtitle', 'body', 'summary', 'meta_keywords'];
636
        }
637
        if (is_array($userid) && count($userid) > 0) {
0 ignored issues
show
introduced by
The condition is_array($userid) is always false.
Loading history...
638
            $userid       = array_map('intval', $userid);
639
            $criteriaUser = new \CriteriaCompo();
640
            $criteriaUser->add(new \Criteria('uid', '(' . implode(',', $userid) . ')', 'IN'), 'OR');
641
        } elseif (is_numeric($userid) && $userid > 0) {
642
            $criteriaUser = new \CriteriaCompo();
643
            $criteriaUser->add(new \Criteria('uid', $userid), 'OR');
644
        }
645
        $count = 0;
646
        if (is_array($queryArray)) {
0 ignored issues
show
introduced by
The condition is_array($queryArray) is always true.
Loading history...
647
            $count = count($queryArray);
648
        }
649
        if (is_array($queryArray) && $count > 0) {
650
            $criteriaKeywords = new \CriteriaCompo();
651
            $elementCount     = count($queryArray);
0 ignored issues
show
Unused Code introduced by
The assignment to $elementCount is dead and can be removed.
Loading history...
652
            foreach ($queryArray as $iValue) {
653
                $criteriaKeyword = new \CriteriaCompo();
654
                if (in_array('title', $searchin)) {
655
                    $criteriaKeyword->add(new \Criteria('title', '%' . $iValue . '%', 'LIKE'), 'OR');
656
                }
657
                if (in_array('subtitle', $searchin)) {
658
                    $criteriaKeyword->add(new \Criteria('subtitle', '%' . $iValue . '%', 'LIKE'), 'OR');
659
                }
660
                if (in_array('body', $searchin)) {
661
                    $criteriaKeyword->add(new \Criteria('body', '%' . $iValue . '%', 'LIKE'), 'OR');
662
                }
663
                if (in_array('summary', $searchin)) {
664
                    $criteriaKeyword->add(new \Criteria('summary', '%' . $iValue . '%', 'LIKE'), 'OR');
665
                }
666
                if (in_array('meta_keywords', $searchin)) {
667
                    $criteriaKeyword->add(new \Criteria('meta_keywords', '%' . $iValue . '%', 'LIKE'), 'OR');
668
                }
669
                $criteriaKeywords->add($criteriaKeyword, $andor);
670
                unset($criteriaKeyword);
671
            }
672
        }
673
        if (!$GLOBALS['publisherIsAdmin'] && (count($categories) > 0)) {
674
            $criteriaPermissions = new \CriteriaCompo();
675
            // Categories for which user has access
676
            $categoriesGranted = $grouppermHandler->getItemIds('category_read', $groups, $this->helper->getModule()->getVar('mid'));
677
            if (count($categories) > 0) {
678
                $categoriesGranted = array_intersect($categoriesGranted, $categories);
679
            }
680
            if (0 == count($categoriesGranted)) {
681
                return $ret;
682
            }
683
            $grantedCategories = new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN');
684
            $criteriaPermissions->add($grantedCategories, 'AND');
685
        } elseif (count($categories) > 0) {
686
            $criteriaPermissions = new \CriteriaCompo();
687
            $grantedCategories   = new \Criteria('categoryid', '(' . implode(',', $categories) . ')', 'IN');
688
            $criteriaPermissions->add($grantedCategories, 'AND');
689
        }
690
        $criteriaItemsStatus = new \CriteriaCompo();
691
        $criteriaItemsStatus->add(new \Criteria('status', Constants::PUBLISHER_STATUS_PUBLISHED));
692
        $criteria = new \CriteriaCompo();
693
        if (!empty($criteriaUser)) {
694
            $criteria->add($criteriaUser, 'AND');
695
        }
696
        if (!empty($criteriaKeywords)) {
697
            $criteria->add($criteriaKeywords, 'AND');
698
        }
699
        if (!empty($criteriaPermissions)) {
700
            $criteria->add($criteriaPermissions);
701
        }
702
        if (!empty($criteriaItemsStatus)) {
703
            $criteria->add($criteriaItemsStatus, 'AND');
704
        }
705
        $criteria->setLimit($limit);
706
        $criteria->setStart($offset);
707
        if (empty($sortby)) {
708
            $sortby = 'datesub';
709
        }
710
        $criteria->setSort($sortby);
711
        $order = 'ASC';
712
        if ('datesub' === $sortby) {
713
            $order = 'DESC';
714
        }
715
        $criteria->setOrder($order);
716
        $ret = $this->getObjects($criteria);
717
718
        return $ret;
719
    }
720
721
    /**
722
     * @param array $categoriesObj
723
     * @param array $status
724
     *
725
     * @return array
726
     */
727
    public function getLastPublishedByCat($categoriesObj, $status = [Constants::PUBLISHER_STATUS_PUBLISHED])
728
    {
729
        $ret    = [];
730
        $catIds = [];
731
        foreach ($categoriesObj as $parentid) {
732
            foreach ($parentid as $category) {
733
                $catId          = $category->getVar('categoryid');
734
                $catIds[$catId] = $catId;
735
            }
736
        }
737
        if (empty($catIds)) {
738
            return $ret;
739
        }
740
        /*$cat = array();
741
742
        $sql = "SELECT categoryid, MAX(datesub) as date FROM " . $this->db->prefix($this->helper->getDirname() . '_items') . " WHERE status IN (" . implode(',', $status) . ") GROUP BY categoryid";
743
        $result = $this->db->query($sql);
744
        while (false !== ($row = $this->db->fetchArray($result))) {
745
            $cat[$row['categoryid']] = $row['date'];
746
        }
747
        if (count($cat) == 0) return $ret;
748
        $sql = "SELECT categoryid, itemid, title, short_url, uid, datesub FROM " . $this->db->prefix($this->helper->getDirname() . '_items');
749
        $criteriaBig = new \CriteriaCompo();
750
        foreach ($cat as $id => $date) {
751
            $criteria = new \CriteriaCompo(new \Criteria('categoryid', $id));
752
            $criteria->add(new \Criteria('datesub', $date));
753
            $criteriaBig->add($criteria, 'OR');
754
            unset($criteria);
755
        }
756
        $sql .= " " . $criteriaBig->renderWhere();
757
        $result = $this->db->query($sql);
758
        while (false !== ($row = $this->db->fetchArray($result))) {
759
            $item = new Item();
760
            $item->assignVars($row);
761
            $ret[$row['categoryid']] = $item;
762
            unset($item);
763
        }
764
        */
765
        $sql    = 'SELECT mi.categoryid, mi.itemid, mi.title, mi.short_url, mi.uid, mi.datesub';
766
        $sql    .= ' FROM (SELECT categoryid, MAX(datesub) AS date FROM ' . $this->db->prefix($this->helper->getDirname() . '_items');
767
        $sql    .= ' WHERE status IN (' . implode(',', $status) . ')';
768
        $sql    .= ' AND categoryid IN (' . implode(',', $catIds) . ')';
769
        $sql    .= ' GROUP BY categoryid)mo';
770
        $sql    .= ' JOIN ' . $this->db->prefix($this->helper->getDirname() . '_items') . ' mi ON mi.datesub = mo.date';
771
        $result = $this->db->query($sql);
772
        while (false !== ($row = $this->db->fetchArray($result))) {
773
            $item = new Item();
774
            $item->assignVars($row);
775
            $ret[$row['categoryid']] = $item;
776
            unset($item);
777
        }
778
779
        return $ret;
780
    }
781
782
    /**
783
     * @param         $parentid
784
     * @param         $catsCount
785
     * @param  string $spaces
786
     * @return int
787
     */
788
    public function countArticlesByCat($parentid, $catsCount, $spaces = '')
789
    {
790
        //        global $resultCatCounts;
791
        $newspaces = $spaces . '--';
792
        $thecount  = 0;
793
        foreach ($catsCount[$parentid] as $subCatId => $count) {
794
            $thecount                         += $count;
795
            $this->resultCatCounts[$subCatId] = $count;
796
            if (isset($catsCount[$subCatId])) {
797
                $thecount                         += $this->countArticlesByCat($subCatId, $catsCount, $newspaces);
798
                $this->resultCatCounts[$subCatId] = $thecount;
799
            }
800
        }
801
802
        return $thecount;
803
    }
804
805
    /**
806
     * @param int   $catId
807
     * @param array $status
808
     * @param bool  $inSubCat
809
     *
810
     * @return array
811
     */
812
    public function getCountsByCat($catId = 0, $status, $inSubCat = false)
813
    {
814
        //        global $resultCatCounts;
815
816
        $ret       = [];
817
        $catsCount = [];
818
        $sql       = 'SELECT c.parentid, i.categoryid, COUNT(*) AS count FROM ' . $this->db->prefix($this->helper->getDirname() . '_items') . ' AS i INNER JOIN ' . $this->db->prefix($this->helper->getDirname() . '_categories') . ' AS c ON i.categoryid=c.categoryid';
819
        if ((int)$catId > 0) {
820
            $sql .= ' WHERE i.categoryid = ' . (int)$catId;
821
            $sql .= ' AND i.status IN (' . implode(',', $status) . ')';
822
        } else {
823
            $sql .= ' WHERE i.status IN (' . implode(',', $status) . ')';
824
        }
825
        $sql    .= ' GROUP BY i.categoryid ORDER BY c.parentid ASC, i.categoryid ASC';
826
        $result = $this->db->query($sql);
827
        if (!$result) {
828
            return $ret;
829
        }
830
        if (!$inSubCat) {
831
            while (false !== ($row = $this->db->fetchArray($result))) {
832
                $catsCount[$row['categoryid']] = $row['count'];
833
            }
834
835
            return $catsCount;
836
        }
837
        //        while (false !== ($row = $this->db->fetchArray($result))) {
838
        while (false !== ($row = $this->db->fetchArray($result))) {
839
            $catsCount[$row['parentid']][$row['categoryid']] = $row['count'];
840
        }
841
        //        $resultCatCounts = array();
842
        foreach ($catsCount[0] as $subCatId => $count) {
843
            $this->resultCatCounts[$subCatId] = $count;
844
            if (isset($catsCount[$subCatId])) {
845
                $this->resultCatCounts[$subCatId] += $this->countArticlesByCat($subCatId, $catsCount, '');
846
            }
847
        }
848
849
        return $this->resultCatCounts;
850
    }
851
}
852