block_rss_client.php 13.9 KB
Newer Older
1
<?php
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16

17
18
19
20
21
22
23
/**
 * Contains block_rss_client
 * @package    block_rss_client
 * @copyright  Daryl Hawes
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 */

dhawes's avatar
dhawes committed
24
/**
25
26
 * A block which displays Remote feeds
 *
27
 * @package   block_rss_client
28
29
 * @copyright  Daryl Hawes
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
dhawes's avatar
dhawes committed
30
 */
31

dhawes's avatar
dhawes committed
32
 class block_rss_client extends block_base {
33
34
    /** The maximum time in seconds that cron will wait between attempts to retry failing RSS feeds. */
    const CLIENT_MAX_SKIPTIME = 43200; // 60 * 60 * 12 seconds.
35

36
37
38
    /** @var bool track whether any of the output feeds have recorded failures */
    private $hasfailedfeeds = false;

39
    function init() {
40
        $this->title = get_string('pluginname', 'block_rss_client');
41
42
    }

43
    function applicable_formats() {
44
        return array('all' => true, 'tag' => false);   // Needs work to make it work on tags MDL-11960
45
46
    }

47
    function specialization() {
48
        // After the block has been loaded we customize the block's title display
49
        if (!empty($this->config) && !empty($this->config->title)) {
50
            // There is a customized block title, display it
51
            $this->title = $this->config->title;
52
53
        } else {
            // No customized block title, use localized remote news feed string
54
            $this->title = get_string('remotenewsfeed', 'block_rss_client');
55
56
        }
    }
dhawes's avatar
dhawes committed
57

58
59
60
61
62
63
64
    /**
     * Gets the footer, which is the channel link of the last feed in our list of feeds
     *
     * @param array $feedrecords The feed records from the database.
     * @return block_rss_client\output\footer|null The renderable footer or null if none should be displayed.
     */
    protected function get_footer($feedrecords) {
65
        global $PAGE;
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        $footer = null;

        if ($this->config->block_rss_client_show_channel_link) {
            global $CFG;
            require_once($CFG->libdir.'/simplepie/moodle_simplepie.php');

            $feedrecord     = array_pop($feedrecords);
            $feed           = new moodle_simplepie($feedrecord->url);
            $channellink    = new moodle_url($feed->get_link());

            if (!empty($channellink)) {
                $footer = new block_rss_client\output\footer($channellink);
            }
        }

81
82
83
84
85
86
87
88
89
90
        if ($this->hasfailedfeeds) {
            if (has_any_capability(['block/rss_client:manageownfeeds', 'block/rss_client:manageanyfeeds'], $this->context)) {
                if ($footer === null) {
                    $footer = new block_rss_client\output\footer();
                }
                $manageurl = new moodle_url('/blocks/rss_client/managefeeds.php', ['courseid' => $PAGE->course->id]);
                $footer->set_failed($manageurl);
            }
        }

91
92
93
        return $footer;
    }

94
    function get_content() {
95
        global $CFG, $DB;
moodler's avatar
moodler committed
96

97
        if ($this->content !== NULL) {
98
99
100
            return $this->content;
        }

101
        // initalise block content object
102
        $this->content = new stdClass;
defacer's avatar
   
defacer committed
103
104
105
        $this->content->text   = '';
        $this->content->footer = '';

moodler's avatar
moodler committed
106
        if (empty($this->instance)) {
107
108
109
            return $this->content;
        }

110
111
112
113
114
115
116
        if (!isset($this->config)) {
            // The block has yet to be configured - just display configure message in
            // the block if user has permission to configure it

            if (has_capability('block/rss_client:manageanyfeeds', $this->context)) {
                $this->content->text = get_string('feedsconfigurenewinstance2', 'block_rss_client');
            }
117

118
            return $this->content;
119
        }
120

121
122
123
124
125
126
127
128
129
130
131
132
        // How many feed items should we display?
        $maxentries = 5;
        if ( !empty($this->config->shownumentries) ) {
            $maxentries = intval($this->config->shownumentries);
        }elseif( isset($CFG->block_rss_client_num_entries) ) {
            $maxentries = intval($CFG->block_rss_client_num_entries);
        }

        /* ---------------------------------
         * Begin Normal Display of Block Content
         * --------------------------------- */

133
134
        $renderer = $this->page->get_renderer('block_rss_client');
        $block = new \block_rss_client\output\block();
135

136
        if (!empty($this->config->rssid)) {
137
138
139
140
141
142
143
144
145
            list($rssidssql, $params) = $DB->get_in_or_equal($this->config->rssid);
            $rssfeeds = $DB->get_records_select('block_rss_client', "id $rssidssql", $params);

            if (!empty($rssfeeds)) {
                $showtitle = false;
                if (count($rssfeeds) > 1) {
                    // When many feeds show the title for each feed.
                    $showtitle = true;
                }
146

147
148
149
150
151
                foreach ($rssfeeds as $feed) {
                    if ($renderablefeed = $this->get_feed($feed, $maxentries, $showtitle)) {
                        $block->add_feed($renderablefeed);
                    }
                }
152

153
                $footer = $this->get_footer($rssfeeds);
dhawes's avatar
dhawes committed
154
            }
155
        }
dhawes's avatar
dhawes committed
156

157
158
159
160
        $this->content->text = $renderer->render_block($block);
        if (isset($footer)) {
            $this->content->footer = $renderer->render_footer($footer);
        }
161

162
163
        return $this->content;
    }
dhawes's avatar
dhawes committed
164

165

166
167
168
169
170
171
172
173
174
175
176
    function instance_allow_multiple() {
        return true;
    }

    function has_config() {
        return true;
    }

    function instance_allow_config() {
        return true;
    }
dhawes's avatar
dhawes committed
177

178
    /**
179
180
181
182
183
     * Returns the html of a feed to be displaed in the block
     *
     * @param mixed feedrecord The feed record from the database
     * @param int maxentries The maximum number of entries to be displayed
     * @param boolean showtitle Should the feed title be displayed in html
184
     * @return block_rss_client\output\feed|null The renderable feed or null of there is an error
185
     */
186
    public function get_feed($feedrecord, $maxentries, $showtitle) {
187
188
        global $CFG;
        require_once($CFG->libdir.'/simplepie/moodle_simplepie.php');
189

190
191
        if ($feedrecord->skipuntil) {
            // Last attempt to gather this feed via cron failed - do not try to fetch it now.
192
            $this->hasfailedfeeds = true;
193
194
195
            return null;
        }

196
        $simplepiefeed = new moodle_simplepie($feedrecord->url);
moodler's avatar
moodler committed
197

198
        if(isset($CFG->block_rss_client_timeout)){
199
            $simplepiefeed->set_cache_duration($CFG->block_rss_client_timeout * 60);
200
        }
201

202
203
204
        if ($simplepiefeed->error()) {
            debugging($feedrecord->url .' Failed with code: '.$simplepiefeed->error());
            return null;
205
        }
206

207
        if(empty($feedrecord->preferredtitle)){
208
            $feedtitle = $this->format_title($simplepiefeed->get_title());
209
210
211
        }else{
            $feedtitle = $this->format_title($feedrecord->preferredtitle);
        }
212

213
214
215
216
217
        if (empty($this->config->title)){
            //NOTE: this means the 'last feed' displayed wins the block title - but
            //this is exiting behaviour..
            $this->title = strip_tags($feedtitle);
        }
218

219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
        $feed = new \block_rss_client\output\feed($feedtitle, $showtitle, $this->config->block_rss_client_show_channel_image);

        if ($simplepieitems = $simplepiefeed->get_items(0, $maxentries)) {
            foreach ($simplepieitems as $simplepieitem) {
                try {
                    $item = new \block_rss_client\output\item(
                        $simplepieitem->get_id(),
                        new moodle_url($simplepieitem->get_link()),
                        $simplepieitem->get_title(),
                        $simplepieitem->get_description(),
                        new moodle_url($simplepieitem->get_permalink()),
                        $simplepieitem->get_date('U'),
                        $this->config->display_description
                    );

                    $feed->add_item($item);
                } catch (moodle_exception $e) {
                    // If there is an error with the RSS item, we don't
                    // want to crash the page. Specifically, moodle_url can
                    // throw an exception of the param is an extremely
                    // malformed url.
                    debugging($e->getMessage());
                }
            }
243
244
        }

245
246
        // Feed image.
        if ($imageurl = $simplepiefeed->get_image_url()) {
247
            try {
248
249
250
251
252
253
254
                $image = new \block_rss_client\output\channel_image(
                    new moodle_url($imageurl),
                    $simplepiefeed->get_image_title(),
                    new moodle_url($simplepiefeed->get_image_link())
                );

                $feed->set_image($image);
255
            } catch (moodle_exception $e) {
256
257
258
259
                // If there is an error with the RSS image, we don'twant to
                // crash the page. Specifically, moodle_url can throw an
                // exception if the param is an extremely malformed url.
                debugging($e->getMessage());
260
            }
261
        }
262

263
        return $feed;
264
    }
265

266
267
268
269
270
271
272
    /**
     * Strips a large title to size and adds ... if title too long
     *
     * @param string title to shorten
     * @param int max character length of title
     * @return string title s() quoted and shortened if necessary
     */
273
274
    function format_title($title,$max=64) {

275
        if (core_text::strlen($title) <= $max) {
276
277
            return s($title);
        } else {
278
            return s(core_text::substr($title,0,$max-3).'...');
279
280
281
        }
    }

282
    /**
283
284
285
286
     * cron - goes through all the feeds. If the feed has a skipuntil value
     * that is less than the current time cron will attempt to retrieve it
     * with the cache duration set to 0 in order to force the retrieval of
     * the item and refresh the cache.
287
     *
288
289
290
291
292
293
294
295
296
297
298
299
     * If a feed fails then the skipuntil time of that feed is set to be
     * later than the next expected cron time. The amount of time will
     * increase each time the fetch fails until the maximum is reached.
     *
     * If a feed that has been failing is successfully retrieved it will
     * go back to being handled as though it had never failed.
     *
     * CRON should therefor process requests for permanently broken RSS
     * feeds infrequently, and temporarily unavailable feeds will be tried
     * less often until they become available again.
     *
     * @return boolean Always returns true
300
     */
301
    function cron() {
skodak's avatar
skodak committed
302
        global $CFG, $DB;
303
        require_once($CFG->libdir.'/simplepie/moodle_simplepie.php');
304

305
306
307
308
        // Get the legacy cron time, strangely the cron property of block_base
        // does not seem to get set. This means we must retrive it here.
        $this->cron = $DB->get_field('block', 'cron', array('name' => 'rss_client'));

309
        // We are going to measure execution times
310
        $starttime =  microtime();
311
        $starttimesec = time();
312

313
        // Fetch all site feeds.
skodak's avatar
skodak committed
314
        $rs = $DB->get_recordset('block_rss_client');
315
316
        $counter = 0;
        mtrace('');
skodak's avatar
skodak committed
317
        foreach ($rs as $rec) {
318
            mtrace('    ' . $rec->url . ' ', '');
319
320
321
322
323
324
325

            // Skip feed if it failed recently.
            if ($starttimesec < $rec->skipuntil) {
                mtrace('skipping until ' . userdate($rec->skipuntil));
                continue;
            }

326
327
            // Fetch the rss feed, using standard simplepie caching
            // so feeds will be renewed only if cache has expired
328
            core_php_time_limit::raise(60);
329
330

            $feed =  new moodle_simplepie();
331
            // set timeout for longer than normal to be agressive at
332
333
            // fetching feeds if possible..
            $feed->set_timeout(40);
334
335
336
337
338
            $feed->set_cache_duration(0);
            $feed->set_feed_url($rec->url);
            $feed->init();

            if ($feed->error()) {
339
340
341
342
343
                // Skip this feed (for an ever-increasing time if it keeps failing).
                $rec->skiptime = $this->calculate_skiptime($rec->skiptime);
                $rec->skipuntil = time() + $rec->skiptime;
                $DB->update_record('block_rss_client', $rec);
                mtrace("Error: could not load/find the RSS feed - skipping for {$rec->skiptime} seconds.");
344
345
            } else {
                mtrace ('ok');
346
347
348
349
350
351
352
353
                // It worked this time, so reset the skiptime.
                if ($rec->skiptime > 0) {
                    $rec->skiptime = 0;
                    $rec->skipuntil = 0;
                    $DB->update_record('block_rss_client', $rec);
                }
                // Only increase the counter when a feed is sucesfully refreshed.
                $counter ++;
354
355
            }
        }
skodak's avatar
skodak committed
356
        $rs->close();
357

358
        // Show times
359
360
        mtrace($counter . ' feeds refreshed (took ' . microtime_diff($starttime, microtime()) . ' seconds)');

361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        return true;
    }

    /**
     * Calculates a new skip time for a record based on the current skip time.
     *
     * @param int $currentskip The curreent skip time of a record.
     * @return int A new skip time that should be set.
     */
    protected function calculate_skiptime($currentskip) {
        // The default time to skiptime.
        $newskiptime = $this->cron * 1.1;
        if ($currentskip > 0) {
            // Double the last time.
            $newskiptime = $currentskip * 2;
        }
        if ($newskiptime > self::CLIENT_MAX_SKIPTIME) {
            // Do not allow the skip time to increase indefinatly.
            $newskiptime = self::CLIENT_MAX_SKIPTIME;
        }
        return $newskiptime;
382
    }
383
}