Difference between revisions of "RSS API"

From MoodleDocs
(Created page with "==Overview== The Events API is a core system in Moodle to allow communication between modules. An '''event''' is when something "interesting" happens in Moodle that is worth ...")
 
(17 intermediate revisions by the same user not shown)
Line 1: Line 1:
==Overview==
+
{{Moodle 2.3}}==Overview==
  
The Events API is a core system in Moodle to allow communication between modules.
+
The RSS API is a core system in Moodle to allow you to create secure RSS feeds of data in your module.  
  
An '''event''' is when something "interesting" happens in Moodle that is worth alerting the system about.
+
These RSS feeds can then be syndicated by other websites or aggregated by a feed reader.
  
Any Moodle modules can '''trigger''' new events (with attached data), and other modules can elect to '''handle''' those events with custom functions that operate on the given data.
+
Any Moodle module can generate RSS feeds to allow secure access to it's data.
  
 +
==File Locations==
  
==Examples==
+
The primary functions for the RSS API is located in lib/rsslib.php
  
Let's look at an example of how events are used to implement Messaging in Moodle 2.0.  In the messaging system, textual messages are generated for users by different modules, and the user can decide how certain types of messages are displayed.
+
Additional functions and usage examples can be found in the following files:
  
===Triggering an event===
+
* blog/rsslib.php
 +
* mod/data/rsslib.php
 +
* mod/forum/rsslib.php
 +
* mod/glossary/rsslib.php
  
When a messaging event occurs, the module should trigger a "message_send" event.  In this example let's pretend someone just posted to a forum.
+
==Examples==
 
 
The forum module needs to create an object with the data that this event needs.  This may vary completely for different types of events, it's just a data object.
 
 
 
$eventdata = new object();
 
$eventdata->component        = 'mod/forum';    // path in Moodle
 
$eventdata->name              = 'posts';        // type of message from that module (as module defines it)
 
$eventdata->userfrom          = $userfrom;      // user object
 
$eventdata->userto            = $userto;        // user object
 
$eventdata->subject          = "Hi there";    // short one-line subject
 
$eventdata->fullmessage      = "Here is the full message";      // raw text
 
$eventdata->fullmessageformat = FORMAT_PLAIN;  // text format
 
$eventdata->fullmessagehtml  = "Here is the <b>full</b> message";    // html rendered version  (optional)
 
$eventdata->smallmessage      = "Here is the truncated message";      // useful for plugins like sms or twitter  (optional)
 
 
 
Then we post the object as an event and forget about it:
 
 
 
events_trigger('message_send', $eventdata);
 
 
 
===Handling an event===
 
 
 
Modules or core code can define an events.php in the db directory which defines events they want to be notified about, and describes which of their functions or class methods should be notified.  For this case, there is this definition of a handler in lib/db/events.php
 
 
 
$handlers = array (
 
    'message_send' => array (
 
          'handlerfile'      => '/lib/messagelib.php',
 
          'handlerfunction'  => 'message_send_handler',
 
          'schedule'        => 'instant'
 
      )
 
);
 
 
 
These events.php files are parsed during install / upgrade and stored in a simple database table.
 
 
 
Now, when a '''message_send''' event happens, all the registered handlers functions for that event will be called something like this (but with more error handling):
 
 
 
          include_once($CFG->dirroot.$handlers['message_send']['handlerfile']);
 
          call_user_func($handlers['message_send']['handlerfunction'], $eventdata);
 
 
 
Any code can hook into any events this way.
 
 
 
The handler function accepts one parameter (the event data object) and should return a boolean.  Returning false indicates that there was an error and the event will be left in the event queue.
 
 
 
    function message_send_handler($eventdata) {
 
        // handle event
 
        // ...
 
        return true;
 
    }
 
 
 
==Database structure==
 
 
 
There are 3 core tables for events. Note that if a handler is queued, and yet to be processed or processing failed, then all subsequent calls on that handler must be queued.
 
 
 
===events_handlers===
 
 
 
This table is for storing which components requests what type of event, and the location of the responsible handler functions.
 
 
 
These entries are created by parsing events.php files in all the modules, and can be rebuilt any time (during an upgrade, say).
 
 
 
{| border="1" cellpadding="2" cellspacing="0"
 
|'''Field'''
 
|'''Type'''
 
|'''Info'''
 
|-
 
|id
 
|int(10)
 
|auto increment identifier
 
|-
 
|eventname
 
|varchar(255)
 
|name of the event, e.g. 'message_send'
 
|-
 
|handlermodule
 
|varchar(255)
 
|e.g. moodle, mod/forum, block/rss_client
 
|-
 
|handlerfile
 
|varchar(255)
 
|path to the file of the function, eg /lib/messagelib.php
 
|-
 
|handlerfunction
 
|text
 
|serialized string or array describing function, suitable to be passed to '''call_user_func()'''
 
|-
 
|schedule
 
|varchar(255)
 
|'cron' or 'instant'.
 
|-
 
|status
 
|int(10)
 
|number of failed attempts to process this handler
 
|}
 
 
 
===events_queue===
 
 
 
This table is for storing queued events. It stores only one copy of the eventdata here, and entries from this table are being references by the events_queue_handlers table.
 
 
 
{| border="1" cellpadding="2" cellspacing="0"
 
|'''Field'''
 
|'''Type'''
 
|'''Info'''
 
|-
 
|id
 
|int(10)
 
|auto increment identifier
 
|-
 
|eventdata
 
|longtext
 
|serialized version of the data object passed to the event handler.
 
|-
 
|stackdump
 
|text
 
|serialized debug_backtrace showing where the event was fired from
 
|-
 
|userid
 
|int(10)
 
|$USER->id when the event was fired
 
|-
 
|timecreated
 
|int(10)
 
|time stamp of the first time this was added
 
|}
 
 
 
===events_queue_handlers===
 
 
 
This is the list of queued handlers for processing. The event object is retrieved from the events_queue table. When no further reference is made to the events_queue table, the corresponding entry in the events_queue table should be deleted. Entry should get deleted (?) after a successful event processing by the specified handler.  The status field keeps track of failures, after it gets to a certain number (eg 10?) it should trigger an "event failed" event (that could result in admin being emailed etc, or perhaps even the originating module taking care of it or rolling something back etc).
 
 
 
{| border="1" cellpadding="2" cellspacing="0"
 
|'''Field'''
 
|'''Type'''
 
|'''Info'''
 
|-
 
|id
 
|int(10)
 
|auto increment identifier
 
|-
 
|queuedeventid
 
|int(10)
 
|foreign key id corresponding to the id of the event_queues table
 
|-
 
|handlerid
 
|int(10)
 
|foreign key id corresponding to the id of the event_handlers table
 
|-
 
|status
 
|int(10)
 
|number of failed attempts to process this handler
 
|-
 
|errormessage
 
|text
 
|if an error happened last time we tried to process this event, record it here.
 
|-
 
|timemodified
 
|int(10)
 
|time stamp of the last attempt to run this from the queue
 
|}
 
 
 
==Standards for naming events==
 
 
 
All event names should follow a consistent naming pattern, such as componentname_noun_verb  (See [[Frankenstyle]] about the component name)
 
 
 
If the event is being fired after the action has taken place (as in most cases) then use the past tense for the verb (created / deleted / updated / sent).
 
 
 
If the event '''is''' the action, then use the present tense (create / delete / update / send).
 
 
 
==Events which exist==
 
 
 
When we add new events to core we should always add them here too.
 
  
Under each event, list the data sent as part of the event.
+
Below you will find examples on how to use the RSS functions within your own modules.
  
===Users===
+
===Creating an RSS feed===
* user_created
 
** full new record from 'user' table
 
* user_deleted
 
** record from 'user' table before marked as deleted
 
* user_updated
 
** full new record from 'user' table
 
* user_enrolled
 
** full user enrolment record (TBC)
 
* user_logout
 
** params TBC
 
* user_unenrol_modified
 
** full user enrolment record (TBC)
 
* user_unenrolled
 
** full user enrolment record (TBC)
 
  
===Roles===
+
This example shows how you can create the content of an RSS Feed.
* role_assigned
 
** full new record from 'role_assignments' table
 
* role_unassigned
 
** record from 'role_assignments', course context only
 
  
===Courses===
+
<code>
* course_created
+
require_once("lib/rsslib.php");
** full course record
+
//create some entries (these would normally be pulled from the database table of the module you are creating an rss feed for).
* course_updated
+
for ($i=1; $i <= 10; $i++) {
** full course record
+
    $item = NULL;
* course_deleted
+
    $item->author = 'Joe Blogs';
** full course record
+
    $item->title = 'RSS Entry Number '.$i;
* course_category_deleted
+
    $item->pubdate = time();
** full category record
+
    $item->link = $CFG->wwwroot.'/entry/index.php?entryid='.$i;
* course_content_removed
+
    $item->description = 'Summary of the RSS Entry';
** full course record
+
    $items[] = $item;
 +
}
 +
$content = rss_add_items($items);  // Convert the array of items into the XML Content
 +
 +
$title = 'RSS Feed';
 +
$description = 'General RSS Feed full of ENTRIES';
 +
$header = rss_standard_header($title, $CFG->wwwroot.'/entry/index.php', $description);
 +
$footer = rss_standard_footer();
 +
 +
$rssdata = $header.$content.$footer; // This is the complete RSS FEED
 +
</code>
  
===Groups===
+
===Caching an RSS feed===
* groups_member_added
 
** groupid, userid
 
* groups_member_removed
 
** groupid, userid
 
* groups_group_created
 
** id, courseid, name, description, timecreated, timemodified, picture
 
* groups_group_updated
 
** id, courseid, name, description, timecreated, timemodified, picture
 
* groups_group_deleted
 
** id, courseid, name, description, timecreated, timemodified, picture
 
* groups_grouping_created
 
** id, courseid, name, timecreated, timemodified
 
* groups_grouping_updated
 
** id, courseid, name, timecreated, timemodified
 
* groups_grouping_deleted
 
** id, courseid, name, timecreated, timemodified
 
* groups_members_removed ''(user deleted from all groups in a course)''
 
** courseid, userid
 
* groups_groupings_groups_removed ''(remove all groups from all groupings in a course)''
 
** courseid (as plain integer, not object)
 
* groups_groups_deleted ''(delete all groups in a course)''
 
** courseid (as plain integer, not object)
 
* groups_groupings_deleted ''(delete all groupings in a course)''
 
** courseid (as plain integer, not object)
 
  
===Cohorts===
+
Following on from the previous example:
  
===Messaging===
+
<code>
 +
  $filename = $CFG->cachedir .'/rss/entry/user/0/rss.xml';
 +
  rss_save_file('entry', $filename, $rssdata, true);
 +
</code>
  
===Portfolio===
+
===Linking to a RSS feed===
  
===Other===
+
This example shows how you can output a link to an RSS feed. (Example taken from blocks/news_items/block_news_items.php)
  
 +
<code>
 +
$cm = $modinfo->instances['forum'][$forum->id];
 +
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
 +
$forum = forum_get_course_forum($this->page->course->id, 'news');
 +
$userid = (!isloggedin()) ? 0 : $USER->id;
 +
$tooltiptext = get_string('rsssubscriberssposts','forum');
 +
echo rss_get_link($context->id, $userid, 'mod_forum', $forum->id, $tooltiptext);
 +
</code>
  
== See also ==
+
==See also==
  
 
* [[Core APIs]]
 
* [[Core APIs]]
  
 
[[Category:API]]
 
[[Category:API]]

Revision as of 07:22, 27 January 2012

Moodle 2.3

Overview

The RSS API is a core system in Moodle to allow you to create secure RSS feeds of data in your module.

These RSS feeds can then be syndicated by other websites or aggregated by a feed reader.

Any Moodle module can generate RSS feeds to allow secure access to it's data.

File Locations

The primary functions for the RSS API is located in lib/rsslib.php

Additional functions and usage examples can be found in the following files:

  • blog/rsslib.php
  • mod/data/rsslib.php
  • mod/forum/rsslib.php
  • mod/glossary/rsslib.php

Examples

Below you will find examples on how to use the RSS functions within your own modules.

Creating an RSS feed

This example shows how you can create the content of an RSS Feed.

require_once("lib/rsslib.php");
//create some entries (these would normally be pulled from the database table of the module you are creating an rss feed for).
for ($i=1; $i <= 10; $i++) {
    $item = NULL;
    $item->author = 'Joe Blogs';
    $item->title = 'RSS Entry Number '.$i;
    $item->pubdate = time();
    $item->link = $CFG->wwwroot.'/entry/index.php?entryid='.$i;
    $item->description = 'Summary of the RSS Entry';
    $items[] = $item;
}
$content = rss_add_items($items);   // Convert the array of items into the XML Content

$title = 'RSS Feed';
$description = 'General RSS Feed full of ENTRIES';
$header = rss_standard_header($title, $CFG->wwwroot.'/entry/index.php', $description);
$footer = rss_standard_footer();

$rssdata = $header.$content.$footer; // This is the complete RSS FEED

Caching an RSS feed

Following on from the previous example:

 $filename = $CFG->cachedir .'/rss/entry/user/0/rss.xml';
 rss_save_file('entry', $filename, $rssdata, true);

Linking to a RSS feed

This example shows how you can output a link to an RSS feed. (Example taken from blocks/news_items/block_news_items.php)

$cm = $modinfo->instances['forum'][$forum->id];
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$forum = forum_get_course_forum($this->page->course->id, 'news');
$userid = (!isloggedin()) ? 0 : $USER->id;
$tooltiptext = get_string('rsssubscriberssposts','forum');
echo rss_get_link($context->id, $userid, 'mod_forum', $forum->id, $tooltiptext);

See also