Passed
Branch master (4e30dc)
by Michael
02:20
created

CategoryHandler::getObjects()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 21
nc 12
nop 2
1
<?php namespace XoopsModules\Smartfaq;
2
3
/**
4
 * Module: SmartFAQ
5
 * Author: The SmartFactory <www.smartfactory.ca>
6
 * Licence: GNU
7
 */
8
9
use \XoopsModules\Smartfaq;
10
11
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
12
13
14
/**
15
 * Categories handler class.
16
 * This class is responsible for providing data access mechanisms to the data source
17
 * of Category class objects.
18
 *
19
 * @author  marcan <[email protected]>
20
 * @package SmartFAQ
21
 */
22
class CategoryHandler extends \XoopsObjectHandler
0 ignored issues
show
Bug introduced by
The type XoopsObjectHandler was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
{
24
    /**
25
     * create a new category
26
     *
27
     * @param  bool $isNew flag the new objects as "new"?
28
     * @return object Smartfaq\Category
29
     */
30
    public function create($isNew = true)
31
    {
32
        $category = new Smartfaq\Category();
33
        if ($isNew) {
34
            $category->setNew();
35
        }
36
37
        return $category;
38
    }
39
40
    /**
41
     * retrieve a category
42
     *
43
     * @param  int $id categoryid of the category
44
     * @return mixed reference to the {@link Smartfaq\Category} object, FALSE if failed
45
     */
46
    public function get($id)
47
    {
48
        $false = false;
49
        if ((int)$id > 0) {
50
            $sql = 'SELECT * FROM ' . $this->db->prefix('smartfaq_categories') . ' WHERE categoryid=' . $id;
51
            if (!$result = $this->db->query($sql)) {
52
                return $false;
53
            }
54
55
            $numrows = $this->db->getRowsNum($result);
56
            if (1 == $numrows) {
57
                $category = new Smartfaq\Category();
58
                $category->assignVars($this->db->fetchArray($result));
59
60
                return $category;
61
            }
62
        }
63
64
        return $false;
65
    }
66
67
    /**
68
     * insert a new category in the database
69
     *
70
     * @param \XoopsObject $category reference to the {@link Smartfaq\Category}
71
     *                               object
72
     * @param  bool        $force
73
     * @return bool        FALSE if failed, TRUE if already present and unchanged or successful
74
     */
75
    public function insert(\XoopsObject $category, $force = false)
0 ignored issues
show
Bug introduced by
The type XoopsObject was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
76
    {
77
        if ('xoopsmodules\smartfaq\category' !== strtolower(get_class($category))) {
78
            return false;
79
        }
80
        if (!$category->isDirty()) {
81
            return true;
82
        }
83
        if (!$category->cleanVars()) {
84
            return false;
85
        }
86
87
        foreach ($category->cleanVars as $k => $v) {
88
            ${$k} = $v;
89
        }
90
91
        if ($category->isNew()) {
92
            $sql = sprintf(
93
                'INSERT INTO %s (parentid, name, description, total, weight, created) VALUES (%u, %s, %s, %u, %u, %u)',
94
                $this->db->prefix('smartfaq_categories'),
95
                           $parentid,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $parentid seems to be never defined.
Loading history...
96
                $this->db->quoteString($name),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $name seems to be never defined.
Loading history...
97
                $this->db->quoteString($description),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $description seems to be never defined.
Loading history...
98
                $total,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total seems to be never defined.
Loading history...
99
                $weight,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $weight seems to be never defined.
Loading history...
100
                time()
101
            );
102
        } else {
103
            $sql = sprintf(
104
                'UPDATE %s SET parentid = %u, name = %s, description = %s, total = %s, weight = %u, created = %u WHERE categoryid = %u',
105
                $this->db->prefix('smartfaq_categories'),
106
                $parentid,
107
                           $this->db->quoteString($name),
108
                $this->db->quoteString($description),
109
                $total,
110
                $weight,
111
                $created,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $created seems to be never defined.
Loading history...
112
                $categoryid
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $categoryid does not exist. Did you maybe mean $category?
Loading history...
113
            );
114
        }
115
        if (false !== $force) {
116
            $result = $this->db->queryF($sql);
117
        } else {
118
            $result = $this->db->query($sql);
119
        }
120
        if (!$result) {
121
            return false;
122
        }
123
        if ($category->isNew()) {
124
            $category->assignVar('categoryid', $this->db->getInsertId());
125
        } else {
126
            $category->assignVar('categoryid', $categoryid);
127
        }
128
129
        return true;
130
    }
131
132
    /**
133
     * delete a category from the database
134
     *
135
     * @param \XoopsObject $category reference to the category to delete
136
     * @param  bool        $force
137
     * @return bool        FALSE if failed.
138
     */
139
    public function delete(\XoopsObject $category, $force = false)
140
    {
141
        if ('xoopsmodules\smartfaq\category' !== strtolower(get_class($category))) {
142
            return false;
143
        }
144
145
        // Deleting the FAQs
146
        $faqHandler = new Smartfaq\FaqHandler($this->db);
147
        if (!$faqHandler->deleteAll(new \Criteria('categoryid', $category->categoryid()))) {
0 ignored issues
show
Bug introduced by
The type Criteria was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
148
            return false;
149
        }
150
151
        // Deleteing the sub categories
152
        $subcats =& $this->getCategories(0, 0, $category->categoryid());
153
        foreach ($subcats as $subcat) {
154
            $this->delete($subcat);
155
        }
156
157
        $sql = sprintf('DELETE FROM %s WHERE categoryid = %u', $this->db->prefix('smartfaq_categories'), $category->getVar('categoryid'));
158
159
        $smartModule = Smartfaq\Utility::getModuleInfo();
160
        $module_id   = $smartModule->getVar('mid');
161
162
        if (false !== $force) {
163
            $result = $this->db->queryF($sql);
164
        } else {
165
            $result = $this->db->query($sql);
166
        }
167
168
        xoops_groupperm_deletebymoditem($module_id, 'category_read', $category->categoryid());
0 ignored issues
show
Bug introduced by
The function xoops_groupperm_deletebymoditem was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

168
        /** @scrutinizer ignore-call */ 
169
        xoops_groupperm_deletebymoditem($module_id, 'category_read', $category->categoryid());
Loading history...
169
        //xoops_groupperm_deletebymoditem ($module_id, "category_admin", $categoryObj->categoryid());
170
171
        if (!$result) {
172
            return false;
173
        }
174
175
        return true;
176
    }
177
178
    /**
179
     * retrieve categories from the database
180
     *
181
     * @param  object $criteria  {@link CriteriaElement} conditions to be met
182
     * @param  bool   $id_as_key use the categoryid as key for the array?
183
     * @return array  array of {@link XoopsFaq} objects
184
     */
185
    public function getObjects($criteria = null, $id_as_key = false)
186
    {
187
        $ret   = [];
188
        $limit = $start = 0;
189
        $sql   = 'SELECT * FROM ' . $this->db->prefix('smartfaq_categories');
190
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
191
            $sql .= ' ' . $criteria->renderWhere();
192
            if ('' != $criteria->getSort()) {
193
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
194
            }
195
            $limit = $criteria->getLimit();
196
            $start = $criteria->getStart();
197
        }
198
        //echo "<br>" . $sql . "<br>";
199
        $result = $this->db->query($sql, $limit, $start);
200
        if (!$result) {
201
            return $ret;
202
        }
203
204
        while (false !== ($myrow = $this->db->fetchArray($result))) {
205
            $category = new Smartfaq\Category();
206
            $category->assignVars($myrow);
207
            if (!$id_as_key) {
208
                $ret[] = $category;
209
            } else {
210
                $ret[$myrow['categoryid']] = $category;
211
            }
212
            unset($category);
213
        }
214
215
        return $ret;
216
    }
217
218
    /**
219
     * @param  int    $limit
220
     * @param  int    $start
221
     * @param  int    $parentid
222
     * @param  string $sort
223
     * @param  string $order
224
     * @param  bool   $id_as_key
225
     * @return array
226
     */
227
    public function &getCategories(
228
        $limit = 0,
229
        $start = 0,
230
        $parentid = 0,
231
        $sort = 'weight',
232
        $order = 'ASC',
233
        $id_as_key = true
234
    ) {
235
//        require_once XOOPS_ROOT_PATH . '/modules/smartfaq/include/functions.php';
236
237
        $criteria = new \CriteriaCompo();
0 ignored issues
show
Bug introduced by
The type CriteriaCompo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
238
239
        $criteria->setSort($sort);
240
        $criteria->setOrder($order);
241
242
        if (-1 != $parentid) {
243
            $criteria->add(new \Criteria('parentid', $parentid));
244
        }
245
        if (!Smartfaq\Utility::userIsAdmin()) {
246
            /** @var \XoopsModules\Smartfaq\PermissionHandler $smartPermHandler */
247
            $smartPermHandler = \XoopsModules\Smartfaq\Helper::getInstance()->getHandler('Permission');
248
249
            $categoriesGranted = $smartPermHandler->getPermissions('category');
250
            $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'));
251
        }
252
        $criteria->setStart($start);
253
        $criteria->setLimit($limit);
254
        $ret = $this->getObjects($criteria, $id_as_key);
255
256
        return $ret;
257
    }
258
259
    /**
260
     * @param  int    $limit
261
     * @param  int    $start
262
     * @param  int    $parentid
263
     * @param  string $sort
264
     * @param  string $order
265
     * @return array
266
     */
267
    public function &getCategoriesWithOpenQuestion(
268
        $limit = 0,
269
        $start = 0,
270
        $parentid = 0,
271
        $sort = 'weight',
272
        $order = 'ASC'
273
    ) {
274
//        require_once XOOPS_ROOT_PATH . '/modules/smartfaq/include/functions.php';
275
276
        $criteria = new \CriteriaCompo();
277
278
        $criteria->setSort($sort);
279
        $criteria->setOrder($order);
280
281
        if (-1 != $parentid) {
282
            $criteria->add(new \Criteria('c.parentid', $parentid));
283
        }
284
        if (!Smartfaq\Utility::userIsAdmin()) {
285
            /** @var \XoopsModules\Smartfaq\PermissionHandler $smartPermHandler */
286
            $smartPermHandler = \XoopsModules\Smartfaq\Helper::getInstance()->getHandler('Permission');
287
288
            $categoriesGranted = $smartPermHandler->getPermissions('category');
289
            $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'));
290
        }
291
292
        $criteria->add(new \Criteria('f.status', Constants::SF_STATUS_OPENED));
293
        $criteria->setStart($start);
294
        $criteria->setLimit($limit);
295
296
        $ret   = [];
297
        $limit = $start = 0;
298
        $sql   = 'SELECT DISTINCT c.categoryid, c.parentid, c.name, c.description, c.total, c.weight, c.created FROM ' . $this->db->prefix('smartfaq_categories') . ' AS c INNER JOIN ' . $this->db->prefix('smartfaq_faq') . ' AS f ON c.categoryid = f.categoryid';
299
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
300
            $sql .= ' ' . $criteria->renderWhere();
301
            if ('' != $criteria->getSort()) {
302
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
303
            }
304
            $limit = $criteria->getLimit();
305
            $start = $criteria->getStart();
306
        }
307
        //echo "<br>" . $sql . "<br>";
308
        $result = $this->db->query($sql, $limit, $start);
309
        if (!$result) {
310
            return $ret;
311
        }
312
313
        while (false !== ($myrow = $this->db->fetchArray($result))) {
314
            $category = new Smartfaq\Category();
315
            $category->assignVars($myrow);
316
            $ret[] = $category;
317
            unset($category);
318
        }
319
320
        return $ret;
321
    }
322
323
    /**
324
     * count Categories matching a condition
325
     *
326
     * @param  object $criteria {@link CriteriaElement} to match
327
     * @return int    count of categories
328
     */
329
    public function getCount($criteria = null)
330
    {
331
        $sql = 'SELECT COUNT(*) FROM ' . $this->db->prefix('smartfaq_categories');
332
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
333
            $sql .= ' ' . $criteria->renderWhere();
334
        }
335
        $result = $this->db->query($sql);
336
        if (!$result) {
337
            return 0;
338
        }
339
        list($count) = $this->db->fetchRow($result);
340
341
        return $count;
342
    }
343
344
    /**
345
     * @param  int $parentid
346
     * @return int
347
     */
348
    public function getCategoriesCount($parentid = 0)
349
    {
350
        if (-1 == $parentid) {
351
            return $this->getCount();
352
        }
353
        $criteria = new \CriteriaCompo();
354
        if (isset($parentid) && (-1 != $parentid)) {
355
            $criteria->add(new \Criteria('parentid', $parentid));
356
            if (!Smartfaq\Utility::userIsAdmin()) {
357
                /** @var \XoopsModules\Smartfaq\PermissionHandler $smartPermHandler */
358
                $smartPermHandler = \XoopsModules\Smartfaq\Helper::getInstance()->getHandler('Permission');
359
360
                $categoriesGranted = $smartPermHandler->getPermissions('category');
361
                $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'));
362
            }
363
        }
364
365
        return $this->getCount($criteria);
366
    }
367
368
    /**
369
     * @param  int $parentid
370
     * @return int
371
     */
372
    public function getCategoriesWithOpenQuestionsCount($parentid = 0)
373
    {
374
        if (-1 == $parentid) {
375
            return $this->getCount();
376
        }
377
        $criteria = new \CriteriaCompo();
378
        if (isset($parentid) && (-1 != $parentid)) {
379
            $criteria->add(new \Criteria('parentid', $parentid));
380
            if (!Smartfaq\Utility::userIsAdmin()) {
381
                /** @var \XoopsModules\Smartfaq\PermissionHandler $smartPermHandler */
382
                $smartPermHandler = \XoopsModules\Smartfaq\Helper::getInstance()->getHandler('Permission');
383
384
                $categoriesGranted = $smartPermHandler->getPermissions('category');
385
                $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'));
386
            }
387
        }
388
389
        $criteria->add(new \Criteria('f.status', Constants::SF_STATUS_OPENED));
390
391
        $sql = 'SELECT COUNT(c.categoryid) FROM ' . $this->db->prefix('smartfaq_categories') . ' AS c INNER JOIN ' . $this->db->prefix('smartfaq_faq') . ' AS f ON c.categoryid = f.categoryid';
392
393
        if (isset($criteria) && is_subclass_of($criteria, 'CriteriaElement')) {
394
            $sql .= ' ' . $criteria->renderWhere();
395
        }
396
397
        $result = $this->db->query($sql);
398
        if (!$result) {
399
            return 0;
400
        }
401
        list($count) = $this->db->fetchRow($result);
402
403
        return $count;
404
    }
405
406
    /**
407
     * @param $categories
408
     * @return array
409
     */
410
    public function getSubCats($categories)
411
    {
412
        $criteria = new \CriteriaCompo(new \Criteria('parentid', '(' . implode(',', array_keys($categories)) . ')'), 'IN');
413
        $ret      = [];
414
        if (!Smartfaq\Utility::userIsAdmin()) {
415
            /** @var \XoopsModules\Smartfaq\PermissionHandler $smartPermHandler */
416
            $smartPermHandler = \XoopsModules\Smartfaq\Helper::getInstance()->getHandler('Permission');
417
418
            $categoriesGranted = $smartPermHandler->getPermissions('category');
419
            $criteria->add(new \Criteria('categoryid', '(' . implode(',', $categoriesGranted) . ')', 'IN'));
420
        }
421
        $subcats =& $this->getObjects($criteria, true);
422
        foreach ($subcats as $subcat_id => $subcat) {
423
            $ret[$subcat->getVar('parentid')][$subcat->getVar('categoryid')] = $subcat;
424
        }
425
426
        return $ret;
427
    }
428
429
    /**
430
     * delete categories matching a set of conditions
431
     *
432
     * @param  object $criteria {@link CriteriaElement}
433
     * @return bool   FALSE if deletion failed
434
     */
435
    public function deleteAll($criteria = null)
436
    {
437
        $sql = 'DELETE FROM ' . $this->db->prefix('smartfaq_categories');
438
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
439
            $sql .= ' ' . $criteria->renderWhere();
440
        }
441
        if (!$this->db->query($sql)) {
442
            return false;
443
            // TODO : Also delete the permissions related to each FAQ
444
            // TODO : What about sub-categories???
445
        }
446
447
        return true;
448
    }
449
450
    /**
451
     * Change a value for categories with a certain criteria
452
     *
453
     * @param string          $fieldname  Name of the field
454
     * @param string          $fieldvalue Value to write
455
     * @param \CriteriaElement $criteria   {@link CriteriaElement}
456
     *
457
     * @return bool
458
     **/
459
    public function updateAll($fieldname, $fieldvalue, \CriteriaElement $criteria = null)
0 ignored issues
show
Bug introduced by
The type CriteriaElement was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
460
    {
461
        $set_clause = is_numeric($fieldvalue) ? $fieldname . ' = ' . $fieldvalue : $fieldname . ' = ' . $this->db->quoteString($fieldvalue);
462
        $sql        = 'UPDATE ' . $this->db->prefix('smartfaq_categories') . ' SET ' . $set_clause;
463
        if (null !== $criteria && is_subclass_of($criteria, 'CriteriaElement')) {
464
            $sql .= ' ' . $criteria->renderWhere();
465
        }
466
        if (!$this->db->queryF($sql)) {
467
            return false;
468
        }
469
470
        return true;
471
    }
472
473
    /**
474
     * @param  int $cat_id
475
     * @return mixed
476
     */
477
    public function publishedFaqsCount($cat_id = 0)
478
    {
479
        return $this->faqsCount($cat_id, $status = [Constants::SF_STATUS_PUBLISHED, Constants::SF_STATUS_NEW_ANSWER]);
0 ignored issues
show
Bug introduced by
$status = array(XoopsMod...::SF_STATUS_NEW_ANSWER) of type array<integer,integer> is incompatible with the type string expected by parameter $status of XoopsModules\Smartfaq\CategoryHandler::faqsCount(). ( Ignorable by Annotation )

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

479
        return $this->faqsCount($cat_id, /** @scrutinizer ignore-type */ $status = [Constants::SF_STATUS_PUBLISHED, Constants::SF_STATUS_NEW_ANSWER]);
Loading history...
480
    }
481
482
    /**
483
     * @param  int    $cat_id
484
     * @param  string $status
485
     * @return mixed
486
     */
487
    public function faqsCount($cat_id = 0, $status = '')
488
    {
489
        global $xoopsUser;
490
//        require_once XOOPS_ROOT_PATH . '/modules/smartfaq/include/functions.php';
491
492
        /** @var Smartfaq\FaqHandler $faqHandler */
493
        $faqHandler = Smartfaq\Helper::getInstance()->getHandler('Faq');
494
495
        return $faqHandler->getCountsByCat($cat_id, $status);
496
    }
497
}
498