lib.php 13.1 KB
Newer Older
1
2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
4
 * Copyright (C) 2006-2008 Catalyst IT Ltd (http://www.catalyst.net.nz)
5
 *
Francois Marier's avatar
Francois Marier committed
6
7
8
9
 * This program 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.
10
 *
Francois Marier's avatar
Francois Marier committed
11
12
13
14
 * This program 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.
15
 *
Francois Marier's avatar
Francois Marier committed
16
17
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19
20
 *
 * @package    mahara
 * @subpackage blocktype-externalfeed
21
 * @author     Catalyst IT Ltd
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23
 * @copyright  (C) 2006-2008 Catalyst IT Ltd http://catalyst.net.nz
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 *
 */

defined('INTERNAL') || die();

class PluginBlocktypeExternalfeed extends SystemBlocktype {

    public static function get_title() {
        return get_string('title', 'blocktype.externalfeed');
    }

    public static function get_description() {
        return get_string('description', 'blocktype.externalfeed');
    }

    public static function get_categories() {
        return array('feeds');
    }

43
44
45
46
    public static function get_viewtypes() {
        return array('portfolio', 'profile');
    }

47
48
49
50
    public static function render_instance(BlockInstance $instance) {
        $configdata = $instance->get('configdata');
        if ($configdata['feedid']) {
            $data = get_record('blocktype_externalfeed_data', 'id', $configdata['feedid']);
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

            $data->content = unserialize($data->content);
            $data->image   = unserialize($data->image);

            // Attempt to fix relative URLs in the feeds
            if (!empty($data->image['link'])) {
                $data->description = preg_replace(
                    '/src="(\/[^"]+)"/',
                    'src="' . $data->image['link'] . '$1"',
                    $data->description
                );
                foreach ($data->content as &$entry) {
                    $entry->description = preg_replace(
                        '/src="(\/[^"]+)"/',
                        'src="' . $data->image['link'] . '$1"',
                        $entry->description
                    );
                }
            }

71
72
73
            $smarty = smarty_core();
            $smarty->assign('title', $data->title);
            $smarty->assign('description', $data->description);
74
            $smarty->assign('url', $data->url);
75
76
            // 'full' won't be set for feeds created before 'full' support was added
            $smarty->assign('full', isset($configdata['full']) ? $configdata['full'] : false); 
77
            $smarty->assign('link', $data->link);
78
79
            $smarty->assign('entries', $data->content);
            $smarty->assign('feedimage', self::make_feed_image_tag($data->image));
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
            $smarty->assign('lastupdated', get_string('lastupdatedon', 'blocktype.externalfeed', format_date(time($data->lastupdate))));
            return $smarty->fetch('blocktype:externalfeed:feed.tpl');
        }
        return '';
    }

    public static function has_instance_config() {
        return true;
    }

    public static function instance_config_form($instance) {
        $configdata = $instance->get('configdata');

        if (isset($configdata['feedid'])) {
            $url = get_field('blocktype_externalfeed_data', 'url', 'id', $configdata['feedid']);
        }
        else {
            $url = '';
        }

100
101
102
103
104
105
106
        if (isset($configdata['full'])) {
            $full = $configdata['full'];
        }
        else {
            $full = false;
        }

107
108
109
110
111
112
113
114
        return array(
            'url' => array(
                'type'  => 'text',
                'title' => get_string('feedlocation', 'blocktype.externalfeed'),
                'description' => get_string('feedlocationdesc', 'blocktype.externalfeed'),
                'width' => '90%',
                'defaultvalue' => $url,
                'rules' => array(
115
116
                    'required' => true,
                    'maxlength' => 255, // mysql hack, see install.xml for this plugin
117
118
                ),
            ),
119
120
121
122
123
124
            'full' => array(
                'type'         => 'checkbox',
                'title'        => get_string('showfeeditemsinfull', 'blocktype.externalfeed'),
                'description'  => get_string('showfeeditemsinfulldesc', 'blocktype.externalfeed'),
                'defaultvalue' => (bool)$full,
            ),
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
        );
    }

    /**
     * Optional method. If exists, allows this class to decide the title for 
     * all blockinstances of this type
     */
    public static function get_instance_title(BlockInstance $bi) {
        $configdata = $bi->get('configdata');

        if (!empty($configdata['feedid'])) {
            if ($title = get_field('blocktype_externalfeed_data', 'title', 'id', $configdata['feedid'])) {
                return $title;
            }
        }
        return '';
    }

    public static function instance_config_validate(Pieform $form, $values) {
        if (strpos($values['url'], '://') == false) {
            // try add on http://
            $values['url'] = 'http://' . $values['url'];
        }
        else {
            $proto = substr($values['url'], 0, strpos($values['url'], '://'));
            if (!in_array($proto, array('http', 'https'))) {
                $form->set_error('url', get_string('invalidurl', 'blocktype.externalfeed'));
            }
        }
154
155
156
157
158
159
160
161
        if (!$form->get_error('url') && !record_exists('blocktype_externalfeed_data', 'url', $values['url'])) {
            try {
                self::parse_feed($values['url']);
                return;
            }
            catch (XML_Feed_Parser_Exception $e) {
                $form->set_error('url', get_string('invalidfeed', 'blocktype.externalfeed',  $e->getMessage()));
            }
162
163
164
165
166
167
168
169
170
171
172
173
174
175
        }
    }

    public static function instance_config_save($values) {
        // we need to turn the feed url into an id in the feed_data table..
        if (strpos($values['url'], '://') == false) {
            // try add on http://
            $values['url'] = 'http://' . $values['url'];
        }
        if ($exists = get_record('blocktype_externalfeed_data', 'url', $values['url'])) {
            $values['feedid'] = $exists->id;
            unset($values['url']);
            return $values;
        }
176
177
        // We know this is safe because self::parse_feed caches its result and 
        // the validate method would have failed if the feed was invalid
178
179
        $data = self::parse_feed($values['url']);
        $data->content  = serialize($data->content);
180
        $data->image    = serialize($data->image);
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
        $data->lastupdate = db_format_timestamp(time());
        $id = ensure_record_exists('blocktype_externalfeed_data', array('url' => $values['url']), $data, 'id', true);
        $values['feedid'] = $id;
        unset($values['url']);
        return $values;

    }

    public static function get_cron() {
        $refresh = new StdClass;
        $refresh->callfunction = 'refresh_feeds';
        $refresh->hour = '*';
        $refresh->minute = '0';

        $cleanup = new StdClass;
        $cleanup->callfunction = 'cleanup_feeds';
        $cleanup->hour = '3';
        $cleanup->minute = '0';

        return array($refresh, $cleanup);

    }

    public static function refresh_feeds() {
        if (!$feeds = get_records_select_array('blocktype_externalfeed_data', 
            'lastupdate < ?', array(db_format_timestamp(strtotime('-30 minutes'))))) {
            return;
        }
        foreach ($feeds as $feed) {
210
211
212
213
214
            try {
                $data = self::parse_feed($feed->url);
                $data->id = $feed->id;
                $data->lastupdate = db_format_timestamp(time());
                $data->content = serialize($data->content);
215
                $data->image   = serialize($data->image);
216
217
218
219
220
221
222
                update_record('blocktype_externalfeed_data', $data);
            }
            catch (XML_Feed_Parser_Exception $e) {
                // The feed must have changed in such a way as to become 
                // invalid since it was added. We ignore this case in the hope 
                // the feed will become valid some time later
            }
223
224
225
226
227
228
229
230
        }
    }

    public static function cleanup_feeds() {
        $ids = array();
        if ($instances = get_records_array('block_instance', 'blocktype', 'externalfeed')) {
            foreach ($instances as $block) {
                $data = unserialize($block->configdata);
231
232
233
                if ($data['feedid']) {
                    $ids[$data['feedid']] = true;
                }
234
235
236
237
238
239
240
241
242
243
            }
        }
        if (count($ids) == 0) {
            delete_records('blocktype_externalfeed_data'); // just delete it all 
            return;
        }
        $usedids = implode(', ', array_map('db_quote', array_keys($ids)));
        delete_records_select('blocktype_externalfeed_data', 'id NOT IN ( ' . $usedids . ' )');
    }

244
245
246
247
248
249
250
    /**
     * Parses the RSS feed given by $source. Throws an exception if the feed 
     * isn't able to be parsed
     *
     * @param string $source The URI for the feed
     * @throws XML_Feed_Parser_Exception
     */
251
252
253
254
255
256
257
258
259
260
261
262
263
264
    public static function parse_feed($source) {

        static $cache;
        if (empty($cache)) {
            $cache = array();
        }
        if (array_key_exists($source, $cache)) {
            return $cache[$source];
        }

        require_once('XML/Feed/Parser.php');
        require_once('snoopy/Snoopy.class.php');

        $snoopy = new Snoopy();
265
        $snoopy->curl_path = '/usr/bin/curl'; // TODO: make configurable later. This is the default for debian
266

267
268
269
270
271
272
273
274
275
        // This is to disable warnings from snoopy while it performs its work. 
        // By all means, comment out while debugging any problems
        $oldlevel = error_reporting(0);
        $result = $snoopy->fetch($source);
        error_reporting($oldlevel);

        if (!$result) {
            $cache[$source] = new XML_Feed_Parser_Exception($snoopy->error);
            throw $cache[$source];
276
277
278
279
280
281
        }

        try {
            $feed = new XML_Feed_Parser($snoopy->results, false, true, false);
        }
        catch (XML_Feed_Parser_Exception $e) {
282
283
284
285
            $cache[$source] = $e;
            throw $e;
            // Don't catch other exceptions, they're an indication something 
            // really bad happened
286
        }
287

288
289
290
291
292
        $data = new StdClass;
        $data->title = $feed->title;
        $data->url = $source;
        $data->link = $feed->link;
        $data->description = $feed->description;
293
294
295
296
297
298
299
300

        // Work out the icon for the feed depending on whether it's RSS or ATOM
        $data->image = $feed->image;
        if (!$data->image) {
            // ATOM feed. These are simple strings
            $data->image = $feed->logo ? $feed->logo : null;
        }

301
302
        $data->content = array();
        foreach ($feed as $count => $item) {
303
            if ($count == 10) {
304
305
                break;
            }
306
307
308
309
310
311
            $description = $item->description;
            if (!$description && ($item->content || $item->summary)) {
                // ATOM feed
                $description = $item->content ? $item->content : ($item->summary ? $item->summary : null);
            }
            $data->content[] = (object)array('title' => $item->title, 'link' => $item->link, 'description' => $description);
312
313
314
315
        }
        $cache[$source] = $data;
        return $data;
    }
316
317
318
319
320
321
322
323

    /**
     * Returns the HTML for the feed icon (not the little RSS one, but the 
     * actual logo associated with the feed)
     */
    private static function make_feed_image_tag($image) {
        $result = '';

324
325
326
327
        if (!$image['url']) {
            return '';
        }

328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
        if (is_string($image)) {
            // Easy!
            return '<img src="' . hsc($image) . '">';
        }

        if (!empty($image['link'])) {
            $result .= '<a href="' . hsc($image['link']) . '">';
        }

        $url = $image['url'];
        // Try and fix URLs that aren't absolute. The standards all say URLs 
        // are supposed to be absolute in RSS feeds, yet still some people 
        // can't even get the basics right...
        if (substr($url, 0, 1) == '/' && !empty($image['link'])) {
            $url = $image['link'] . $image['url'];
        }

        $result .= '<img src="' . hsc($url) . '"';
        // Required by the specification, but we can't count on it...
        if (!empty($image['title'])) {
            $result .= ' alt="' . hsc($image['title']) . '"';
        }

        if (!empty($image['width']) || !empty($image['height'])) {
            $result .= ' style="';
            if (!empty($image['width'])) {
                $result .= 'width: ' . hsc($image['width']) . 'px;"';
            }
            if (!empty($image['height'])) {
                $result .= 'height: ' . hsc($image['height']) . 'px;"';
            }
            $result .= '"';
        }

        $result .= '>';

        if (!empty($image['link'])) {
            $result .= '</a>';
        }

        return $result;
    }
370
371
372
}

?>