Bblog::getRatingAverage()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 8
Ratio 88.89 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 8
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
//
3
// ------------------------------------------------------------------------ //
4
// This program is free software; you can redistribute it and/or modify     //
5
// it under the terms of the GNU General Public License as published by     //
6
// the Free Software Foundation; either version 2 of the License, or        //
7
// (at your option) any later version.                                      //
8
//                                                                          //
9
// You may not change or alter any portion of this comment or credits       //
10
// of supporting developers from this source code or any supporting         //
11
// source code which is considered copyrighted (c) material of the          //
12
// original comment or credit authors.                                      //
13
//                                                                          //
14
// This program is distributed in the hope that it will be useful,          //
15
// but WITHOUT ANY WARRANTY; without even the implied warranty of           //
16
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
17
// GNU General Public License for more details.                             //
18
//                                                                          //
19
// You should have received a copy of the GNU General Public License        //
20
// along with this program; if not, write to the Free Software              //
21
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
22
// ------------------------------------------------------------------------ //
23
// Author: phppp (D.J., [email protected])                                  //
24
// URL: https://xoops.org                         //
25
// Project: Article Project                                                 //
26
// ------------------------------------------------------------------------ //
27
/**
28
 * @package   module::blogline
29
 * @copyright copyright &copy; 2005 XoopsForge.com
30
 */
31
32
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
33
require_once __DIR__ . '/../include/vars.php';
34
//mod_loadFunctions('', $GLOBALS['moddirname']);
35
36
/**
37
 * Xtopic
38
 *
39
 * @author    D.J. (phppp)
40
 * @copyright copyright &copy; 2005 XoopsForge.com
41
 * @package   module::article
42
 *
43
 * {@link XoopsObject}
44
 **/
45
if (!class_exists('Bblog')):
46
47
    /**
48
     * Class Bblog
49
     */
50
    class Bblog extends XoopsObject
51
    {
52
        /**
53
         * Constructor
54
         */
55
        public function __construct()
56
        {
57
            //            parent:__construct();
58
            $this->table = planet_DB_prefix('blog');
59
            $this->initVar('blog_id', XOBJ_DTYPE_INT, null, false);
60
            $this->initVar('blog_title', XOBJ_DTYPE_TXTBOX, null, true);
61
            $this->initVar('blog_desc', XOBJ_DTYPE_TXTBOX, null);
62
            /* rss URI */
63
            $this->initVar('blog_feed', XOBJ_DTYPE_TXTBOX, null, true);
64
            $this->initVar('blog_language', XOBJ_DTYPE_TXTBOX, null);
65
            $this->initVar('blog_charset', XOBJ_DTYPE_TXTBOX, null);
66
            /* blog website */
67
            $this->initVar('blog_link', XOBJ_DTYPE_TXTBOX, null);
68
            $this->initVar('blog_image', XOBJ_DTYPE_TXTBOX, null);
69
70
            /* regexp for blog article trackback
71
             * From article url to article trackback URI
72
             *
73
             * For example: http://www.example.com/blog/111.html => http://www.example.com/blog/trackback/111.html
74
             * The input shall be: pattern[SPACE]replacement
75
             *                     (.*blog/)([\d]+\.html$) $1trackback/$2
76
             *
77
             * For example: http://www.example.com/modules/wordpress/?p=123 => http://www.example.com/modules/wordpress/wp-trackback.php?p=123
78
             * The input shall be: pattern[SPACE]replacement
79
             *                     (.*wordpress/)(index.php)?(\?p.*) $1wp-trackback/$3
80
             */
81
            $this->initVar('blog_trackback', XOBJ_DTYPE_TXTBOX, '');
82
83
            /* blog submitter: is_numeric - uid; is_string - IP */
84
            $this->initVar('blog_submitter', XOBJ_DTYPE_TXTBOX, '');
85
86
            /* blog status: 0 - pending; 1 - active; 2 - featured */
87
            $this->initVar('blog_status', XOBJ_DTYPE_INT, 1);
88
89
            /* key for blog content */
90
            $this->initVar('blog_key', XOBJ_DTYPE_TXTBOX, '');
91
92
            $this->initVar('blog_time', XOBJ_DTYPE_INT, 0);
93
            $this->initVar('blog_rating', XOBJ_DTYPE_INT, 0);
94
            $this->initVar('blog_rates', XOBJ_DTYPE_INT, 0);
95
            /* bookmark times */
96
            $this->initVar('blog_marks', XOBJ_DTYPE_INT, 0);
97
        }
98
99
        /**
100
         * get formatted publish time of the article
101
         *
102
         * {@link Config}
103
         *
104
         * @param  string $format format of time
105
         * @return string
106
         */
107
        public function getTime($format = '')
108
        {
109
            $time = PlanetUtility::planetFormatTimestamp($this->getVar('blog_time'), $format);
110
111
            return $time;
112
        }
113
114
        /**
115
         * get verified image url of the category
116
         *
117
         * @return string
118
         */
119
        public function getImage()
120
        {
121
            $image = $this->getVar('blog_image');
122
123
            return $image;
124
        }
125
126
        /**
127
         * get rating average of the article
128
         *
129
         * @param  int $decimals decimal length
130
         * @return numeric
131
         */
132 View Code Duplication
        public function getRatingAverage($decimals = 1)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
133
        {
134
            $ave = 3;
135
            if ($this->getVar('blog_rates')) {
136
                $ave = number_format($this->getVar('blog_rating') / $this->getVar('blog_rates'), $decimals);
137
            }
138
139
            return $ave;
140
        }
141
142
        /**
143
         * @return numeric
144
         */
145
        public function getStar()
146
        {
147
            return $this->getRatingAverage(0);
148
        }
149
    }
150
endif;
151
/**
152
 * Topic object handler class.
153
 * @package   module::article
154
 *
155
 * @author    D.J. (phppp)
156
 * @copyright copyright &copy; 2005 XOOPS Project
157
 *
158
 * {@link XoopsPersistableObjectHandler}
159
 *
160
 * @param CLASS_PREFIX variable prefix for the class name
161
 */
162
163
PlanetUtility::planetParseClass('
164
class [CLASS_PREFIX]BlogHandler extends XoopsPersistableObjectHandler
165
{
166
    /**
167
     * Constructor
168
     *
169
     * @param object $db reference to the {@link XoopsDatabase} object
170
     **/
171
    public function __construct(\XoopsDatabase $db) {
172
        parent::__construct($db, planet_DB_prefix("blog", true), "Bblog", "blog_id", "blog_title");
173
    }
174
175
    /**
176
     * Fetch blog info by parsing given feed
177
     *
178
     * @param  object $criteria {@link CriteriaElement} to match
179
     * @param  array  $tags     variables to fetch
180
     * @param  bool   $asObject flag indicating as object, otherwise as array
181
     * @return array  of blogs {@link Bblog}
182
     */
183
    function &fetch($feed)
184
    {
185
        $feed = formatURL($feed);
186
        $blog = $this->create();
187
        $content = PlanetUtility::planetGetRemoteContent($feed);
188
        if (empty($content)) {
189
            return $blog;
190
        }
191
        if (preg_match("/<\?xml.*encoding=[\'\"](.*?)[\'\"].*\?>/m", $content, $match)) {
192
            $charset = strtoupper($match[1]);
193
        } else {
194
            $charset = "UTF-8";
195
        }
196
        $res = $this->parse($content, $charset, array("channel", "image"));
197
198
        $blog->setVar("blog_feed", $feed);
199
        $blog->setVar("blog_charset", $charset);
200
        $blog->setVar("blog_language", @$res["channel"]["language"]);
201
        $blog->setVar("blog_title", $res["channel"]["title"]);
202
        $blog->setVar("blog_desc", $res["channel"]["description"]);
203
        $blog->setVar("blog_link", $res["channel"]["link"]);
204
        $blog->setVar("blog_image", @$res["image"]["url"]);
205
206
        return $blog;
207
    }
208
209
    /**
210
     * check if content has been updated according to a stored key (md5)
211
     *
212
     * @param  object $blog
213
     * @param  string $content fetched content
214
     * @param  bool   $update  update articles
215
     * @return mixed  key or updated article count
216
     */
217
    function do_update(&$blog, $update = true)
218
    {
219
        $content = PlanetUtility::planetGetRemoteContent($blog->getVar("blog_feed"));
220
        if (empty($content)) {
221
            PlanetUtility::planetDisplayMessage("Empty content");
222
223
            return false;
224
        }
225
226
        /* quick fetch items */
227
        $is_rss = true;
228
        if ( !$pos_end = PlanetUtility::planetStrrPos($content, "</item>") ) {
229
            if (!$pos_end = PlanetUtility::planetStrrPos($content, "</entry>")) {
230
                PlanetUtility::planetDisplayMessage("blog ID ".$blog->getVar("blog_id").": No item/entry found!");
231
232
                return false;
233
            }
234
            $is_rss = false;
235
        }
236
        if (!empty($is_rss)) {
237
            if (!$pos_start = strpos($content, "<item>")) {
238
                if (!$pos_start = strpos($content, "<item ")) {
239
                    PlanetUtility::planetDisplayMessage("blog ID ".$blog->getVar("blog_id").": No item found!");
240
241
                    return false;
242
                }
243
            }
244
        } elseif ((!$pos_start = strpos($content, "<entry>")) && (!$pos_start = strpos($content, "<entry "))) {
245
            PlanetUtility::planetDisplayMessage("blog ID ".$blog->getVar("blog_id").": No entry found!");
246
247
            return false;
248
        }
249
250
        /* check if content has changed */
251
        $key = md5(substr($pos_start, $pos_end, $content));
252
        if ($key == $blog->getVar("blog_key")) {
253
            PlanetUtility::planetDisplayMessage("key identical!");
254
255
            return false;
256
        }
257
        if(empty($update)) return $key;
258
259
260
        /* parse items */
261
        $res = $this->parse($content, $blog->getVar("blog_charset"), array("items"));
262
        //xoops_message($res);
263
        $items = $res["items"];
264
        //xoops_message($items);
265
        $blog_time = 0;
266
        $crit = $blog->getVar("blog_time");
267
        $articles = array();
268
        $times = array();
269
        foreach ($items as $item) {
270
            if(is_numeric($item["date_timestamp"]) && $item["date_timestamp"] <= $crit) continue;
271
            if (is_numeric($item["date_timestamp"]) && $item["date_timestamp"] > $blog_time) {
272
                $blog_time = $item["date_timestamp"];
273
            }
274
            $_article = array(
275
                "blog_id"       => $blog->getVar("blog_id"),
276
                "art_link"      => $item["link"],
277
                "art_time"      => $item["date_timestamp"],
278
                "art_title"     => $item["title"],
279
                "art_content"   => empty($item["content"]["encoded"]) ? @$item["description"] : $item["content"]["encoded"]
280
                );
281
            if (!empty($item["author"])) {
282
                $_article["art_author"] = $item["author"];
283
            } elseif (!empty($item["author"]["name"])) {
284
                $_article["art_author"] = $item["author"]["name"];
285
            } elseif (!empty($item["author_name"])) {
286
                $_article["art_author"] = $item["author_name"];
287
            } elseif (!empty($item["dc"]["creator"])) {
288
                $_article["art_author"] = $item["dc"]["creator"];
289
            } else {
290
                $_article["art_author"] = "";
291
            }
292
            $articles[] = $_article;
293
            $times[] = $item["date_timestamp"];
294
        }
295
        array_multisort($articles, $times, SORT_ASC, SORT_NUMERIC);
296
297
        //xoops_message($articles);
298
299
        /* set blog last article time */
300
        if ($blog_time>0) {
301
            $blog->setVar("blog_time", $blog_time, true);
302
            $this->insert($blog, true);
303
        }
304
305
        /* update articles */
306
        $articleHandler = xoops_getModuleHandler("article", $GLOBALS["moddirname"]);
307
        $count = $articleHandler->do_update($articles);
308
309
        if ($count>0 && !empty($GLOBALS["xoopsModuleConfig"]["notification_enabled"])) {
310
            $notificationHandler = xoops_getHandler("notification");
311
            $tags = array();
312
            $tags["BLOG_TITLE"] = $blog->getVar("blog_title");
313
            $tags["BLOG_URL"] = XOOPS_URL . "/modules/" . $GLOBALS["moddirname"] . "/index.php".URL_DELIMITER."b" .$blog->getVar("blog_id");
314
            $notificationHandler->triggerEvent("blog", $blog->getVar("blog_id"), "blog_update", $tags);
315
        }
316
317
        return $count;
318
    }
319
320
    /**
321
     * parse articles
322
     *
323
     * @param  object $criteria {@link CriteriaElement} to match
324
     * @param  array  $tags     variables to fetch
325
     * @param  bool   $asObject flag indicating as object, otherwise as array
326
     * @return array  of blogs {@link Bblog}
327
     */
328
    function &parse(&$content, $charset = "UTF-8", $tags = array())
329
    {
330
        $res = array();
331
        if (empty($content)) {
332
            return $res;
333
        }
334
        require_once XOOPS_ROOT_PATH."/modules/".$GLOBALS["moddirname"]."/class/xmlparser.php";
335
336
        $parser = new XmlParser( $content, $charset, _CHARSET, $tags );
337
        if (!$parser) {
338
            return $res;
339
        }
340
        //xoops_message($parser);
341
        foreach ($tags as $tag) {
342
            $res[$tag] = $parser->{$tag};
343
        }
344
345
        return $res;
346
    }
347
348
    /**
349
     * get a list of blogs matching a condition of a category
350
     *
351
     * @param  object $criteria {@link CriteriaElement} to match
352
     * @param  array  $tags     variables to fetch
353
     * @param  bool   $asObject flag indicating as object, otherwise as array
354
     * @return array  of blogs {@link Bblog}
355
     */
356
       function &getByCategory($criteria = null, $tags = null, $asObject=true)
357
    {
358
        if (is_array($tags) && count($tags)>0) {
359
            if(!in_array($this->keyName, $tags)) $tags[] = "b.".$this->keyName;
360
            $select = implode(",", $tags);
361
        } else $select = "*";
362
        $limit = null;
363
        $start = null;
364
        $sql = "SELECT $select".
365
                " FROM " . $this->table. " AS b".
366
                " LEFT JOIN ".planet_DB_prefix("blogcat")." AS bc ON b.blog_id = bc.blog_id";
367
                //" LEFT JOIN (SELECT blog_id,  FROM ".planet_DB_prefix("blogcat").") AS bc ON blog_id = bc.blog_id";
368
        if (isset($criteria) && is_subclass_of($criteria, "criteriaelement")) {
369
            $sql .= " ".$criteria->renderWhere();
370
            if ($criteria->getSort() != "") {
371
                $sql .= " ORDER BY ".$criteria->getSort()." ".$criteria->getOrder();
372
                $orderSet = true;
373
            }
374
            $limit = $criteria->getLimit();
375
            $start = $criteria->getStart();
376
        }
377
        if(empty($orderSet)) $sql .= " ORDER BY b.".$this->keyName." DESC";
378
        $result = $this->db->query($sql, $limit, $start);
379
        $ret = array();
380
       while (false !== ($myrow = $this->db->fetchArray($result))) {
381
            $object = $this->create(false);
382
            $object->assignVars($myrow);
383
            if ($asObject) {
384
                $ret[$myrow[$this->keyName]] = $object;
385
            } else {
386
                foreach ($myrow as $key=>$val) {
387
                    $ret[$myrow[$this->keyName]][$key] = ($object->vars[$key]["changed"])?$object->getVar($key):$val;
388
                }
389
            }
390
            unset($object);
391
        }
392
393
        return $ret;
394
    }
395
396
    /**
397
     * count blogs matching a condition of a category (categories)
398
     *
399
     * @param  object $criteria {@link CriteriaElement} to match
400
     * @return int    count of blogs
401
     */
402
       function getCountByCategory($criteria = null)
403
    {
404
        $sql = "SELECT COUNT(*) AS count".
405
                " FROM " . $this->table. " AS b".
406
                " LEFT JOIN ".planet_DB_prefix("blogcat")." AS bc ON b.blog_id = bc.blog_id";
407
        if (isset($criteria) && is_subclass_of($criteria, "criteriaelement")) {
408
            $sql .= " ".$criteria->renderWhere();
409
        }
410
        if (!$result = $this->db->query($sql)) {
411
            return false;
412
        }
413
        $myrow = $this->db->fetchArray($result);
414
415
        return (int)($myrow["count"]);
416
    }
417
418
       function getCountsByCategory($criteria = null)
419
    {
420
        $sql = "SELECT cat_id, COUNT(*)".
421
                " FROM ".planet_DB_prefix("blogcat");
422
        if (isset($criteria) && is_subclass_of($criteria, "criteriaelement")) {
423
            $sql .= " ".$criteria->renderWhere();
424
        }
425
        $sql .= " GROUP BY cat_id";
426
        if (!$result = $this->db->query($sql)) {
427
            return false;
428
        }
429
        $ret = array();
430
        while (false !== (list($id, $count) = $this->db->fetchRow($result))) {
431
            $ret[$id] = $count;
432
        }
433
434
        return $ret;
435
    }
436
437
    /**
438
     * get a list of blogs matching a condition of user bookmark
439
     *
440
     * @param  object $criteria {@link CriteriaElement} to match
441
     * @param  array  $tags     variables to fetch
442
     * @param  bool   $asObject flag indicating as object, otherwise as array
443
     * @return array  of blogs {@link Bblog}
444
     */
445
       function &getByBookmark($criteria = null, $tags = null, $asObject = true)
446
    {
447
        if (is_array($tags) && count($tags)>0) {
448
            if(!in_array($this->keyName, $tags)) $tags[] = "b.".$this->keyName;
449
            $select = implode(",", $tags);
450
        } else $select = "*";
451
        $limit = null;
452
        $start = null;
453
        $sql = "SELECT $select".
454
                " FROM " . $this->table. " AS b".
455
                " LEFT JOIN ".planet_DB_prefix("bookmark")." AS bm ON b.blog_id = bm.blog_id";
456
                //" LEFT JOIN (SELECT blog_id,  FROM ".planet_DB_prefix("blogcat").") AS bc ON blog_id = bc.blog_id";
457
        if (isset($criteria) && is_subclass_of($criteria, "criteriaelement")) {
458
            $sql .= " ".$criteria->renderWhere();
459
            if ($criteria->getSort() != "") {
460
                $sql .= " ORDER BY ".$criteria->getSort()." ".$criteria->getOrder();
461
                $orderSet = true;
462
            }
463
            $limit = $criteria->getLimit();
464
            $start = $criteria->getStart();
465
        }
466
        if(empty($orderSet)) $sql .= " ORDER BY b.".$this->keyName." DESC";
467
        $result = $this->db->query($sql, $limit, $start);
468
        $ret = array();
469
       while (false !== ($myrow = $this->db->fetchArray($result))) {
470
            $object = $this->create(false);
471
            $object->assignVars($myrow);
472
            if ($asObject) {
473
                $ret[$myrow[$this->keyName]] = $object;
474
            } else {
475
                foreach ($myrow as $key=>$val) {
476
                    $ret[$myrow[$this->keyName]][$key] = ($object->vars[$key]["changed"])?$object->getVar($key):$val;
477
                }
478
            }
479
            unset($object);
480
        }
481
482
        return $ret;
483
    }
484
485
    /**
486
     * count blogs matching a condition of user bookmark
487
     *
488
     * @param  object $criteria {@link CriteriaElement} to match
489
     * @return int    count of blogs
490
     */
491
       function getCountByBookmark($criteria = null)
492
    {
493
        $sql = "SELECT COUNT(*) AS count".
494
                " FROM " . $this->table. " AS b".
495
                " LEFT JOIN ".planet_DB_prefix("bookmark")." AS bm ON b.blog_id = bm.blog_id";
496
        if (isset($criteria) && is_subclass_of($criteria, "criteriaelement")) {
497
            $sql .= " ".$criteria->renderWhere();
498
        }
499
        if (!$result = $this->db->query($sql)) {
500
            return false;
501
        }
502
        $myrow = $this->db->fetchArray($result);
503
504
        return (int)($myrow["count"]);
505
    }
506
507
    function delete(\XoopsObject $blog, $force=false)
508
    {
509
        $queryFunc = empty($force)?"query":"queryF";
510
511
        /* remove bookmarks */
512
        $bookmarkHandler = xoops_getModuleHandler("bookmark", $GLOBALS["moddirname"]);
513
        $bookmarkHandler->deleteAll(new \Criteria("blog_id", $blog->getVar("blog_id")));
514
515
        /* remove category-blog links */
516
        $sql = "DELETE FROM ".planet_DB_prefix("blogcat")." WHERE blog_id = ".$blog->getVar("blog_id");
517
        if (!$result = $this->db->{$queryFunc}($sql)) {
518
        }
519
520
        /* remove articles */
521
        $articleHandler = xoops_getModuleHandler("article", $GLOBALS["moddirname"]);
522
        $arts_obj = $articleHandler->getAll(new \Criteria("blog_id", $blog->getVar("blog_id")));
523
        foreach (array_keys($arts_obj) as $id) {
524
            $articleHandler->delete($arts_obj[$id]);
525
        }
526
527
        xoops_notification_deletebyitem($GLOBALS["xoopsModule"]->getVar("mid"), "blog", $blog->getVar("blog_id"));
528
529
        /* Remove cat-blog links */
530
        parent::delete($blog, $force);
531
    }
532
533
    function do_empty(&$blog)
534
    {
535
        /* remove articles */
536
        $articleHandler = xoops_getModuleHandler("article", $GLOBALS["moddirname"]);
537
        $arts_obj = $articleHandler->getAll(new \Criteria("blog_id", $blog->getVar("blog_id")));
538
        foreach (array_keys($arts_obj) as $id) {
539
            $articleHandler->delete($arts_obj[$id]);
540
        }
541
        $blog->setVar("blog_time", 0);
542
        $blog->setVar("blog_key", "");
543
        $this->insert($blog, true);
544
545
        return true;
546
    }
547
548
    /**
549
     * get categories of a blog
550
     *
551
     * @param  int   $blog       blog ID
552
     * @param  array $categories array of category IDs
553
     * @return bool
554
     */
555
       function setCategories($blog, $categories)
556
    {
557
        $categoryHandler = xoops_getModuleHandler("category", $GLOBALS["moddirname"]);
558
        $crit = new \Criteria("bc.blog_id", $blog);
559
        $cats = array_keys($categoryHandler->getByBlog($crit));
560
        $cats_add = array_diff($categories, $cats);
561
        $cats_rmv = array_diff($cats, $categories);
562
        if (count($cats_add)>0) {
563
            $_values = array();
564
            foreach ($cats_add as $cat) {
565
                $_values[] = "(".(int)($blog).", ".(int)($cat).")";
566
            }
567
            $values = implode(",",$_values);
568
            $sql = "INSERT INTO ".planet_DB_prefix("blogcat")." (blog_id, cat_id) VALUES ". $values;
569
            if (!$result = $this->db->queryF($sql)) {
570
                PlanetUtility::planetDisplayMessage("Insert blog-cat error:" . $sql);
571
            }
572
          }
573
        if (count($cats_rmv)>0) {
574
            $sql = "DELETE FROM ".planet_DB_prefix("blogcat")." WHERE ( blog_id=".(int)($blog)." AND cat_id IN (".implode(",", $cats_rmv).") )";
575
            if (!$result = $this->db->queryF($sql)) {
576
                PlanetUtility::planetDisplayMessage("remove blog-cat error:" . $sql);
577
            }
578
          }
579
580
        return count($cats_add);
581
    }
582
}
583
');
584