MDL-33514 - rss: also exclude suspended users feeds
[moodle.git] / lib / rsslib.php
CommitLineData
50fcb1d8 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * This file contains all the common stuff to be used in RSS System
20 *
13d1c9ed
JF
21 * @package core_rss
22 * @category rss
78bfb562
PS
23 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50fcb1d8 25 */
8adcb49f 26
78bfb562
PS
27defined('MOODLE_INTERNAL') || die();
28
13d1c9ed
JF
29/**
30 * Build the URL for the RSS feed and add it as a header
31 *
32 * @param stdClass $context The context under which the URL should be created
33 * @param string $componentname The name of the component for which the RSS feed exists
34 * @param stdClass $componentinstance The instance of the component
35 * @param string $title Name for the link to be added to the page header
36 */
37function rss_add_http_header($context, $componentname, $componentinstance, $title) {
9e86f2e7 38 global $PAGE, $USER;
e858c368
AD
39
40 $componentid = null;
41 if (is_object($componentinstance)) {
42 $componentid = $componentinstance->id;
43 } else {
44 $componentid = $componentinstance;
45 }
46
47 $rsspath = rss_get_url($context->id, $USER->id, $componentname, $componentid);
9e86f2e7
AD
48 $PAGE->add_alternate_version($title, $rsspath, 'application/rss+xml');
49 }
50
007b2f04 51/**
13d1c9ed 52 * Print the link for the RSS feed with the correct RSS icon
50fcb1d8 53 *
13d1c9ed
JF
54 * @param stdClass $contextid The id of the context under which the URL should be created
55 * @param int $userid The source of the RSS feed (site/course/group/user)
56 * @param string $componentname The name of the component for which the feed exists
57 * @param string $id The name by which to call the RSS File
58 * @param string $tooltiptext The tooltip to be displayed with the link
59 * @return string HTML output for the RSS link
007b2f04 60 */
43b92251 61function rss_get_link($contextid, $userid, $componentname, $id, $tooltiptext='') {
f2a1963c 62 global $OUTPUT;
8adcb49f 63
8adcb49f 64 static $rsspath = '';
65
43b92251 66 $rsspath = rss_get_url($contextid, $userid, $componentname, $id);
b5d0cafc 67 $rsspix = $OUTPUT->pix_url('i/rss');
d4706960 68
c46fce71 69 return '<a href="'. $rsspath .'"><img src="'. $rsspix .'" title="'. strip_tags($tooltiptext) .'" alt="'.get_string('rss').'" /></a>';
d4706960 70}
71
007b2f04 72/**
73 * This function returns the URL for the RSS XML file.
50fcb1d8 74 *
13d1c9ed
JF
75 * @param int $contextid the course id
76 * @param int $userid the current user id
77 * @param string $componentname the name of the current component. For example "forum"
e858c368 78 * @param string $additionalargs For modules, module instance id
13d1c9ed 79 * @return string the url of the RSS feed
007b2f04 80 */
e858c368 81function rss_get_url($contextid, $userid, $componentname, $additionalargs) {
d4706960 82 global $CFG;
5a254a29 83 require_once($CFG->libdir.'/filelib.php');
fcce139a 84 $usertoken = rss_get_token($userid);
e858c368 85 return get_file_url($contextid.'/'.$usertoken.'/'.$componentname.'/'.$additionalargs.'/rss.xml', null, 'rssfile');
8adcb49f 86}
87
007b2f04 88/**
13d1c9ed
JF
89 * Print the link for the RSS feed with the correct RSS icon (Theme based)
90 *
91 * @param stdClass $contextid The id of the context under which the URL should be created
92 * @param int $userid The source of the RSS feed (site/course/group/user)
93 * @param string $componentname The name of the component for which the feed exists
94 * @param string $id The name by which to call the RSS File
95 * @param string $tooltiptext The tooltip to be displayed with the link
007b2f04 96 */
43b92251
AD
97function rss_print_link($contextid, $userid, $componentname, $id, $tooltiptext='') {
98 print rss_get_link($contextid, $userid, $componentname, $id, $tooltiptext);
65f1df62 99
100}
8adcb49f 101
007b2f04 102/**
fcce139a 103 * Given an object, deletes all RSS files associated with it.
50fcb1d8 104 *
13d1c9ed
JF
105 * @param string $componentname the name of the module ie 'forum'. Used to construct the cache path.
106 * @param stdClass $instance An object with an id member variable ie $forum, $glossary.
007b2f04 107 */
43b92251 108function rss_delete_file($componentname, $instance) {
fcce139a 109 global $CFG;
29b71de6 110
365bec4c 111 $dirpath = "$CFG->cachedir/rss/$componentname";
a74bea12 112 if (is_dir($dirpath)) {
80c27aab 113 if (!$dh = opendir($dirpath)) {
7df271d9 114 error_log("Directory permission error. RSS directory store for component '{$componentname}' exists but cannot be opened.", DEBUG_DEVELOPER);
80c27aab
CF
115 return;
116 }
a74bea12
AD
117 while (false !== ($filename = readdir($dh))) {
118 if ($filename!='.' && $filename!='..') {
119 if (preg_match("/{$instance->id}_/", $filename)) {
43b92251 120 unlink("$dirpath/$filename");
a74bea12 121 }
fcce139a
AD
122 }
123 }
124 }
125}
8adcb49f 126
fcce139a
AD
127/**
128 * Are RSS feeds enabled for the supplied module instance?
13d1c9ed
JF
129 *
130 * @param string $modname The name of the module to be checked
131 * @param stdClass $instance An instance of an activity module ie $forum, $glossary.
132 * @param bool $hasrsstype Should there be a rsstype member variable?
133 * @param bool $hasrssarticles Should there be a rssarticles member variable?
134 * @return bool whether or not RSS is enabled for the module
fcce139a 135 */
43b92251 136function rss_enabled_for_mod($modname, $instance=null, $hasrsstype=true, $hasrssarticles=true) {
fcce139a
AD
137 if ($hasrsstype) {
138 if (empty($instance->rsstype) || $instance->rsstype==0) {
139 return false;
140 }
2f29ee13 141 }
142
fcce139a
AD
143 //have they set the RSS feed to return 0 results?
144 if ($hasrssarticles) {
145 if (empty($instance->rssarticles) || $instance->rssarticles==0) {
146 return false;
8adcb49f 147 }
148 }
fcce139a 149
43b92251 150 if (!empty($instance) && !instance_is_visible($modname,$instance)) {
fcce139a 151 return false;
8adcb49f 152 }
153
fcce139a 154 return true;
8adcb49f 155}
156
007b2f04 157/**
158 * This function saves to file the rss feed specified in the parameters
50fcb1d8 159 *
13d1c9ed
JF
160 * @param string $componentname the module name ie forum. Used to create a cache directory.
161 * @param string $filename the name of the file to be created ie "rss.xml"
162 * @param string $contents the data to be written to the file
163 * @param bool $expandfilename whether or not the fullname of the RSS file should be used
164 * @return bool whether the save was successful or not
007b2f04 165 */
e858c368 166function rss_save_file($componentname, $filename, $contents, $expandfilename=true) {
8adcb49f 167 global $CFG;
29b71de6 168
8adcb49f 169 $status = true;
170
8f6e5a8d 171 if (! $basedir = make_cache_directory ('rss/'. $componentname)) {
bc706aeb 172 //Cannot be created, so error
173 $status = false;
174 }
8adcb49f 175
176 if ($status) {
e858c368
AD
177 $fullfilename = $filename;
178 if ($expandfilename) {
179 $fullfilename = rss_get_file_full_name($componentname, $filename);
180 }
181
fcce139a 182 $rss_file = fopen($fullfilename, "w");
8adcb49f 183 if ($rss_file) {
e858c368 184 $status = fwrite ($rss_file, $contents);
8adcb49f 185 fclose($rss_file);
bc706aeb 186 } else {
187 $status = false;
8adcb49f 188 }
189 }
190 return $status;
191}
192
13d1c9ed
JF
193/**
194 * Retrieve the location and file name of a cached RSS feed
195 *
196 * @param string $componentname the name of the component the RSS feed is being created for
197 * @param string $filename the name of the RSS FEED
198 * @return string The full name and path of the RSS file
199 */
43b92251 200function rss_get_file_full_name($componentname, $filename) {
6069e206 201 global $CFG;
365bec4c 202 return "$CFG->cachedir/rss/$componentname/$filename.xml";
fcce139a 203}
6069e206 204
13d1c9ed
JF
205/**
206 * Construct the file name of the RSS File
207 *
208 * @param stdClass $instance the instance of the source of the RSS feed
209 * @param string $sql the SQL used to produce the RSS feed
210 * @return string the name of the RSS file
211 */
fcce139a
AD
212function rss_get_file_name($instance, $sql) {
213 return $instance->id.'_'.md5($sql);
6069e206 214}
215
007b2f04 216/**
217 * This function return all the common headers for every rss feed in the site
50fcb1d8 218 *
13d1c9ed
JF
219 * @param string $title the title for the RSS Feed
220 * @param string $link the link for the origin of the RSS feed
221 * @param string $description the description of the contents of the RSS feed
222 * @return bool|string the standard header for the RSS feed
007b2f04 223 */
8adcb49f 224function rss_standard_header($title = NULL, $link = NULL, $description = NULL) {
9598cecf 225 global $CFG, $USER, $OUTPUT;
8adcb49f 226
8adcb49f 227 $status = true;
228 $result = "";
229
2a250a0b 230 $site = get_site();
8adcb49f 231
232 if ($status) {
233
234 //Calculate title, link and description
235 if (empty($title)) {
268ddd50 236 $title = format_string($site->fullname);
8adcb49f 237 }
238 if (empty($link)) {
239 $link = $CFG->wwwroot;
240 }
241 if (empty($description)) {
242 $description = $site->summary;
243 }
244
245 //xml headers
246 $result .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
247 $result .= "<rss version=\"2.0\">\n";
248
249 //open the channel
48005861 250 $result .= rss_start_tag('channel', 1, true);
8adcb49f 251
252 //write channel info
75e8eaeb 253 $result .= rss_full_tag('title', 2, false, strip_tags($title));
48005861 254 $result .= rss_full_tag('link', 2, false, $link);
255 $result .= rss_full_tag('description', 2, false, $description);
410a24c0 256 $result .= rss_full_tag('generator', 2, false, 'Moodle');
ec6dc3f6 257 if (!empty($USER->lang)) {
48005861 258 $result .= rss_full_tag('language', 2, false, substr($USER->lang,0,2));
ec6dc3f6 259 }
8adcb49f 260 $today = getdate();
268ddd50 261 $result .= rss_full_tag('copyright', 2, false, '&#169; '. $today['year'] .' '. format_string($site->fullname));
95a86f75 262 /*
6b263129 263 if (!empty($USER->email)) {
91247b89 264 $result .= rss_full_tag('managingEditor', 2, false, fullname($USER));
265 $result .= rss_full_tag('webMaster', 2, false, fullname($USER));
ec6dc3f6 266 }
6b263129 267 */
8adcb49f 268
269 //write image info
b5d0cafc 270 $rsspix = $OUTPUT->pix_url('i/rsssitelogo');
8adcb49f 271
007b2f04 272 //write the info
48005861 273 $result .= rss_start_tag('image', 2, true);
274 $result .= rss_full_tag('url', 3, false, $rsspix);
275 $result .= rss_full_tag('title', 3, false, 'moodle');
276 $result .= rss_full_tag('link', 3, false, $CFG->wwwroot);
277 $result .= rss_full_tag('width', 3, false, '140');
278 $result .= rss_full_tag('height', 3, false, '35');
279 $result .= rss_end_tag('image', 2, true);
8adcb49f 280 }
281
282 if (!$status) {
283 return false;
284 } else {
285 return $result;
286 }
287}
288
13d1c9ed
JF
289
290/**
291 * Generates the rss XML code for every item passed in the array
292 *
293 * item->title: The title of the item
294 * item->author: The author of the item. Optional !!
295 * item->pubdate: The pubdate of the item
296 * item->link: The link url of the item
297 * item->description: The content of the item
298 *
299 * @param array $items an array of item objects
300 * @return bool|string the rss XML code for every item passed in the array
301 */
8adcb49f 302function rss_add_items($items) {
8adcb49f 303 global $CFG;
29b71de6 304
9d575747 305 $result = '';
8adcb49f 306
307 if (!empty($items)) {
308 foreach ($items as $item) {
9d575747 309 $result .= rss_start_tag('item',2,true);
6d6002a0 310 //Include the category if exists (some rss readers will use it to group items)
311 if (isset($item->category)) {
312 $result .= rss_full_tag('category',3,false,$item->category);
313 }
08577617 314 if (isset($item->tags)) {
315 $attributes = array();
316 if (isset($item->tagscheme)) {
5a84cc70 317 $attributes['domain'] = s($item->tagscheme);
08577617 318 }
319 foreach ($item->tags as $tag) {
320 $result .= rss_full_tag('category', 3, false, $tag, $attributes);
321 }
322 }
75e8eaeb 323 $result .= rss_full_tag('title',3,false,strip_tags($item->title));
9d575747 324 $result .= rss_full_tag('link',3,false,$item->link);
069b6daf 325 $result .= rss_add_enclosures($item);
babe6a0a 326 $result .= rss_full_tag('pubDate',3,false,gmdate('D, d M Y H:i:s',$item->pubdate).' GMT'); # MDL-12563
6f5e0852 327 //Include the author if exists
2b04c41c 328 if (isset($item->author) && !empty($item->author)) {
5744be47 329 //$result .= rss_full_tag('author',3,false,$item->author);
007b2f04 330 //We put it in the description instead because it's more important
5744be47 331 //for moodle than most other feeds, and most rss software seems to ignore
332 //the author field ...
1d5a7c4b 333 $item->description = get_string('byname','',$item->author).'. &nbsp;<p>'.$item->description.'</p>';
ca87cbe1 334 }
9d575747 335 $result .= rss_full_tag('description',3,false,$item->description);
1d5a7c4b 336 $result .= rss_full_tag('guid',3,false,$item->link,array('isPermaLink' => 'true'));
9d575747 337 $result .= rss_end_tag('item',2,true);
8adcb49f 338
339 }
340 } else {
341 $result = false;
342 }
343 return $result;
344}
345
007b2f04 346/**
347 * This function return all the common footers for every rss feed in the site
13d1c9ed
JF
348 *
349 * @param string $title Not used at all
350 * @param string $link Not used at all
351 * @param string $description Not used at all
352 * @todo MDL-31050 Fix/Remove this function
353 * @return string
007b2f04 354 */
8adcb49f 355function rss_standard_footer($title = NULL, $link = NULL, $description = NULL) {
8adcb49f 356 $status = true;
9d575747 357 $result = '';
8adcb49f 358
359 //Close the chanel
48005861 360 $result .= rss_end_tag('channel', 1, true);
8adcb49f 361 ////Close the rss tag
48005861 362 $result .= '</rss>';
8adcb49f 363
364 return $result;
365}
366
13d1c9ed 367
007b2f04 368/**
13d1c9ed
JF
369 * This function return an error xml file (string) to be sent when a rss is required (file.php) and something goes wrong
370 *
371 * @param string $errortype Type of error to send, default is rsserror
372 * @return stdClass returns a XML Feed with an error message in it
007b2f04 373 */
fcce139a 374function rss_geterrorxmlfile($errortype = 'rsserror') {
ec6dc3f6 375 global $CFG;
376
377 $return = '';
378
379 //XML Header
380 $return = rss_standard_header();
381
29b71de6 382 //XML item
ec6dc3f6 383 if ($return) {
365a5941 384 $item = new stdClass();
007b2f04 385 $item->title = "RSS Error";
386 $item->link = $CFG->wwwroot;
387 $item->pubdate = time();
fcce139a 388 $item->description = get_string($errortype);
ec6dc3f6 389 $return .= rss_add_items(array($item));
390 }
391
392 //XML Footer
393 if ($return) {
394 $return .= rss_standard_footer();
395 }
29b71de6 396
ec6dc3f6 397 return $return;
398}
399
13d1c9ed
JF
400/**
401 * Get the ID of the user from a given RSS Token
402 *
403 * @param string $token the RSS token you would like to use to find the user id
404 * @return int The user id
405 */
fcce139a
AD
406function rss_get_userid_from_token($token) {
407 global $DB;
6b4c491c
DP
408
409 $sql = 'SELECT u.id FROM {user} u
410 JOIN {user_private_key} k ON u.id = k.userid
411 WHERE u.deleted = 0 AND u.confirmed = 1
aacf3222 412 AND u.suspended = 0 AND k.value = ?';
6b4c491c 413 return $DB->get_field_sql($sql, array($token), IGNORE_MISSING);
fcce139a
AD
414}
415
13d1c9ed
JF
416/**
417 * Get the RSS Token from a given user id
418 *
419 * @param int $userid The user id
420 * @return string the RSS token for the user
421 */
fcce139a
AD
422function rss_get_token($userid) {
423 return get_user_key('rss', $userid);
424}
425
13d1c9ed
JF
426/**
427 * Removes the token for the given user from the DB
428 * @param int $userid The user id for the token you wish to delete
429 */
ffa3bfb3
AD
430function rss_delete_token($userid) {
431 delete_user_key('rss', $userid);
432}
fcce139a 433
007b2f04 434/**
435 * Return the xml start tag
13d1c9ed
JF
436 *
437 * @param string $tag the xml tag name
438 * @param int $level the indentation level
439 * @param bool $endline whether or not to start new tags on a new line
440 * @param array $attributes the attributes of the xml tag
441 * @return string the xml start tag
007b2f04 442 */
1d5a7c4b 443function rss_start_tag($tag,$level=0,$endline=false,$attributes=null) {
8adcb49f 444 if ($endline) {
445 $endchar = "\n";
446 } else {
447 $endchar = "";
448 }
1d5a7c4b 449 $attrstring = '';
450 if (!empty($attributes) && is_array($attributes)) {
451 foreach ($attributes as $key => $value) {
452 $attrstring .= " ".$key."=\"".$value."\"";
453 }
454 }
455 return str_repeat(" ",$level*2)."<".$tag.$attrstring.">".$endchar;
8adcb49f 456}
457
007b2f04 458/**
459 * Return the xml end tag
13d1c9ed
JF
460 * @param string $tag the xml tag name
461 * @param int $level the indentation level
462 * @param bool $endline whether or not to start new tags on a new line
463 * @return string the xml end tag
007b2f04 464 */
8adcb49f 465function rss_end_tag($tag,$level=0,$endline=true) {
466 if ($endline) {
467 $endchar = "\n";
468 } else {
469 $endchar = "";
470 }
471 return str_repeat(" ",$level*2)."</".$tag.">".$endchar;
472}
473
007b2f04 474/**
13d1c9ed
JF
475 * Return the while xml element, including content
476 *
477 * @param string $tag the xml tag name
478 * @param int $level the indentation level
479 * @param bool $endline whether or not to start new tags on a new line
480 * @param string $content the text to go inside the tag
481 * @param array $attributes the attributes of the xml tag
482 * @return string the whole xml element
007b2f04 483 */
1d5a7c4b 484function rss_full_tag($tag,$level=0,$endline=true,$content,$attributes=null) {
1d5a7c4b 485 $st = rss_start_tag($tag,$level,$endline,$attributes);
8adcb49f 486 $co="";
810944af 487 $co = preg_replace("/\r\n|\r/", "\n", htmlspecialchars($content));
8adcb49f 488 $et = rss_end_tag($tag,0,true);
1d5a7c4b 489
8adcb49f 490 return $st.$co.$et;
491}
492
410a24c0 493/**
770b7f6c 494 * Adds RSS Media Enclosures for "podcasting" by including attachments that
495 * are specified in the item->attachments field.
50fcb1d8 496 *
13d1c9ed
JF
497 * @param stdClass $item representing an RSS item
498 * @return string RSS enclosure tags
50fcb1d8 499 */
410a24c0 500function rss_add_enclosures($item){
6db0338e 501 global $CFG;
502
410a24c0 503 $returnstring = '';
29b71de6 504
410a24c0 505 // list of media file extensions and their respective mime types
6db0338e 506 include_once($CFG->libdir.'/filelib.php');
507 $mediafiletypes = get_mimetypes_array();
410a24c0 508
95a86f75 509 // take into account attachments (e.g. from forum) - with these, we are able to know the file size
510 if (isset($item->attachments) && is_array($item->attachments)) {
511 foreach ($item->attachments as $attachment){
909409b5 512 $extension = strtolower(substr($attachment->url, strrpos($attachment->url, '.')+1));
513 if (isset($mediafiletypes[$extension]['type'])) {
514 $type = $mediafiletypes[$extension]['type'];
515 } else {
516 $type = 'document/unknown';
517 }
069b6daf 518 $returnstring .= "\n<enclosure url=\"$attachment->url\" length=\"$attachment->length\" type=\"$type\" />\n";
95a86f75 519 }
520 }
29b71de6 521
410a24c0 522 return $returnstring;
523}