summaryrefslogtreecommitdiffstats
path: root/fetcher/feedfetcher.php
blob: 0a0f295b9e5347a0ec69c285f11f9d305160def6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
<?php
/**
 * ownCloud - News
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Alessandro Cosentino <cosenal@gmail.com>
 * @author Bernhard Posselt <dev@bernhard-posselt.com>
 * @copyright Alessandro Cosentino 2012
 * @copyright Bernhard Posselt 2012, 2014
 */

namespace OCA\News\Fetcher;

use \OCA\News\Db\Item;
use \OCA\News\Db\Feed;
use \OCA\News\Utility\PicoFeedFaviconFactory;
use \OCA\News\Utility\PicoFeedReaderFactory;

class FeedFetcher implements IFeedFetcher {

    private $faviconFactory;
    private $readerFactory;
    private $time;

    public function __construct(PicoFeedReaderFactory $readerFactory,
                                PicoFeedFaviconFactory $faviconFactory,
                                $time){
        $this->faviconFactory = $faviconFactory;
        $this->readerFactory = $readerFactory;
        $this->time = $time;
    }


    /**
     * This fetcher handles all the remaining urls therefore always returns true
     */
    public function canHandle($url){
        return true;
    }


    /**
     * Fetch a feed from remote
     * @param string $url remote url of the feed
     * @param boolean $getFavicon if the favicon should also be fetched,
     * defaults to true
     * @param string $lastModified a last modified value from an http header
     * defaults to false. If lastModified matches the http header from the feed
     * no results are fetched
     * @param string $etag an etag from an http header.
     * If lastModified matches the http header from the feed
     * no results are fetched
     * @throws FetcherException if simple pie fails
     * @return array an array containing the new feed and its items, first
     * element being the Feed and second element being an array of Items
     */
    public function fetch($url, $getFavicon=true, $lastModified=null,
                          $etag=null) {
        $reader = $this->readerFactory->build();
        $resource = $reader->download($url, $lastModified, $etag);

        $modified = $resource->getLastModified();
        $etag = $resource->getEtag();

        if (!$resource->isModified()) {
            return [null, null];
        }

        try {
            $parser = $reader->getParser();

            if (!$parser) {
                throw new \Exception(
                    'Could not find a valid feed at url ' . $url
                );
            }
            $parsedFeed = $parser->execute();

            if (!$parsedFeed) {
                throw new \Exception(
                    'Could not parse feed ' . $url
                );
            }

            $items = [];

            $link = $parsedFeed->getUrl();
            foreach($parsedFeed->getItems() as $item) {
                $items[] = $this->buildItem($item);
            }

            $feed = $this->buildFeed(
                $parsedFeed, $url, $getFavicon, $modified, $etag
            );

            return [$feed, $items];

        } catch(\Exception $ex){
            throw new FetcherException($ex->getMessage());
        }

    }


    private function decodeTwice($string) {
        // behold! &apos; is not converted by PHP that's why we need to do it
        // manually (TM)
        return str_replace('&apos;', '\'',
                html_entity_decode(
                    html_entity_decode(
                        $string, ENT_QUOTES, 'UTF-8'
                    ),
                ENT_QUOTES, 'UTF-8'
            )
        );
    }


    protected function buildItem($parsedItem) {
        $item = new Item();
        $item->setStatus(0);
        $item->setUnread();
        $item->setUrl($parsedItem->getUrl());

        // unescape content because angularjs helps against XSS
        $item->setTitle($this->decodeTwice($parsedItem->getTitle()));
        $guid = $parsedItem->getId();
        $item->setGuid($guid);

        // purification is done in the service layer
        $body = $parsedItem->getContent();
        $body = mb_convert_encoding($body, 'HTML-ENTITIES',
            mb_detect_encoding($body));
        $item->setBody($body);

        // pubdate is not required. if not given use the current date
        $date = $parsedItem->getDate();

        $item->setPubDate($date);

        $item->setLastModified($this->time->getTime());

        $author = $parsedItem->getAuthor();
        $item->setAuthor($this->decodeTwice($author));

        // TODO: make it work for video files also
        $enclosureUrl = $parsedItem->getEnclosureUrl();
        if($enclosureUrl) {
            $enclosureType = $parsedItem->getEnclosureType();
            if(stripos($enclosureType, 'audio/') !== false ||
               stripos($enclosureType, 'video/') !== false) {
                $item->setEnclosureMime($enclosureType);
                $item->setEnclosureLink($enclosureUrl);
            }
        }

        return $item;
    }


    protected function buildFeed($parsedFeed, $url, $getFavicon, $modified,
                                 $etag) {
        $feed = new Feed();

        // unescape content because angularjs helps against XSS
        $title = strip_tags($this->decodeTwice($parsedFeed->getTitle()));

        // if there is no title use the url
        if(!$title) {
            $title = $url;
        }

        $feed->setTitle($title);
        $feed->setUrl($url);
        $feed->setLastModified($modified);
        $feed->setEtag($etag);

        $link = $parsedFeed->getUrl();
        if (!$link) {
            $link = $url;
        }
        $feed->setLink($link);

        $feed->setAdded($this->time->getTime());

        if ($getFavicon) {
            $faviconFetcher = $this->faviconFactory->build();
            $favicon = $faviconFetcher->find($feed->getLink());
            $feed->setFaviconLink($favicon);
        }

        return $feed;
    }

}