1<?php
2/**
3 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
4 * @author     Andreas Gohr <gohr@cosmocode.de>
5 */
6
7use dokuwiki\plugin\blogtng\entities\Comment;
8
9/**
10 * Class helper_plugin_blogtng_linkback
11 */
12class helper_plugin_blogtng_linkback extends DokuWiki_Plugin {
13    /**
14     * @return bool
15     */
16    public function linkbackAllowed() {
17        $entry = $this->getPost();
18        return !plugin_isdisabled('blogtng') &&
19               $this->getConf('receive_linkbacks') &&
20               $entry['blog'] !== '' && $entry['blog'] !== null &&
21               $entry['commentstatus'] === 'enabled';
22    }
23
24    /**
25     * @return array|null
26     */
27    private function getPost() {
28        global $ID;
29        /** @var helper_plugin_blogtng_entry $ehelper */
30        $ehelper = plugin_load('helper', 'blogtng_entry');
31        $ehelper->load_by_pid(md5($ID));
32        return $ehelper->entry;
33    }
34
35    /**
36     * @param $type
37     * @param $title
38     * @param $sourceUri
39     * @param $excerpt
40     * @param $id
41     * @return bool
42     */
43    public function saveLinkback($type, $title, $sourceUri, $excerpt, $id) {
44        /** @var helper_plugin_blogtng_sqlite $sqlitehelper */
45        $sqlitehelper = plugin_load('helper', 'blogtng_sqlite');
46        if (!$sqlitehelper->ready()) return false;
47
48        $comment = new Comment();
49        $comment->setSource($type);
50        $comment->setName($title);
51        $comment->setWeb($sourceUri);
52        $comment->setText($excerpt);
53        $comment->setPid(md5($id));
54        $comment->setSubscribe(null);
55        $comment->setStatus('hidden');
56        $comment->setIp(clientIP(true));
57
58
59        $query = 'SELECT web, source
60                  FROM comments
61                  WHERE pid = ?';
62
63        $resid = $sqlitehelper->getDB()->query($query, $comment->getPid());
64        if ($resid === false) {
65            return false;
66        }
67
68        $comments = $sqlitehelper->getDB()->res2arr($resid);
69
70        foreach($comments as $c) {
71            if ($c['web'] === $comment->getWeb() && $c['source'] === $comment->getSource()) {
72                return false;
73            }
74        }
75
76        /** @var helper_plugin_blogtng_comments $chelper */
77        $chelper = plugin_load('helper', 'blogtng_comments');
78        $chelper->save($comment);
79        return true;
80    }
81}
82