Completed
Push — master ( 15a86c...ff0242 )
by Michael
03:23
created

Bblog::__construct()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 42
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 18
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 42
rs 8.8571
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: http://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') || exit('XOOPS root path not defined');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
33
include_once dirname(__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
            //            parent:__construct();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

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