Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Tag API: Difference between revisions

From MoodleDocs
No edit summary
Line 34: Line 34:
);
);
</code>
</code>
You will also need to add  
You will also need to add language string, for the example above it will be '''$string['tagarea_wiki_pages'] = 'Wiki pages';'''


There are more options such as specifying the default value for "Standard tags", having a fixed collection or excluding from search. They can be found in comments in [[https://github.com/moodle/moodle/blob/master/lib/db/tag.php lib/db/tag.php]]
There are more options such as specifying the default value for "Standard tags", having a fixed collection or excluding from search. They can be found in comments in [[https://github.com/moodle/moodle/blob/master/lib/db/tag.php lib/db/tag.php]]

Revision as of 08:19, 6 June 2016

Moodle 3.1


Tag API overview

The Tag API allows you to assign labels to information in Moodle. This makes finding this information easier and also facilitates the grouping of similar information. The Tag API allows you to create, modify, delete and search tags in the Moodle system. The main tag related functions can be found in the tag/classes/tag.php file. For a through overview of all of the functions available for working with Tags please see methods in core_tag_tag, core_tag_collection and core_tag_area classes, however the following examples should give you a general understanding of how to get started with tags.

This page describes API in Moodle 3.1 and above, for earlier versions see Tag API before 3.1

Tag API usage

When user tags something a tag instance is created in the database linking the item to the actual tag. If tag did not exist before it is created automatically. Do not confuse these two entities - deleting the tag instance does not normally delete tag, however deleting tag deletes all tag instances associated with it.

Developers define tag areas the areas that can be tagged, examples are:

  • blog posts
  • courses
  • users (tags represent user interests)
  • activity modules
  • questions
  • wiki pages

Each tag area is identified by two attributes - component and itemtype. Itemtype must be a name of a table in the database. Component is the core component or plugin responsible for the tagging. This way the same DB table (for example 'user' or 'course') may be independently tagged by several components. Administrator or manager is able to manage the tag areas, collections and tags inside them on the Managing tags page. Users are able to search tags and view all items tagged with them that they have access to.

Defining a tag area

First, developer must define the tag areas in the file db/tag.php. This will usually look like: $tagareas = array(

   array(
       'itemtype' => 'wiki_pages',  // This must be a name of the database table (without prefix).
       'component' => 'mod_wiki', // This can be omitted for plugins since it can only be full frankenstyle name of the plugin.
       'callback' => 'mod_wiki_get_tagged_pages',
       'callbackfile' => '/mod/wiki/locallib.php',
   ),

); You will also need to add language string, for the example above it will be $string['tagarea_wiki_pages'] = 'Wiki pages';

There are more options such as specifying the default value for "Standard tags", having a fixed collection or excluding from search. They can be found in comments in [lib/db/tag.php]

After making changes to db/tag.php plugin developer must bump the plugin version in version.php and run upgrade script. This usually applies to any changes in the db/ folder.

Adding tags element to the editing form

After tag area is defined it should appear on "Manage tags" page. Now it is time to allow users to add/change tags when editing the item. Here is an example from Wiki module:

1. Add a 'tags' form element to the editing form: $mform->addElement('tags', 'tags', get_string('tags'), array('itemtype' => 'wiki_pages', 'component' => 'mod_wiki'));

This element will automatically check if the tag area is disabled by the manager and will not display anything in this case. However if you want to add a header you need to check if tag area is enabled add this: if (core_tag_tag::is_enabled('mod_wiki', 'wiki_pages')) {

   $mform->addElement('header', 'tagshdr', get_string('tags', 'tag'));

}

2. Save the form data if ($data = $form->get_data()) {

   // Do some other processing here, if this is a new page (item) you need to insert it in the DB and obtain id.
   // $pageid = $data->id;
   core_tag_tag::set_item_tags('mod_wiki', 'wiki_pages', $pageid, $modulecontext, $data->tags);

} It is important to specify the correct context in this function. Note that $data->tags will always be returned by the form, even if the area is disabled, however core_tag_tag::set_item_tags() will not change or reset tags if the tag area is disabled.

3. Populate the form with existing tags before calling $form->set_data($data): $data = $DB->get_record('wiki_pages', array('id' => $this->page->id)); // Well, it's more complicated than that of course.... $data->tags = core_tag_tag::get_item_tags_array('mod_wiki', 'wiki_pages', $this->page->id); $form->set_data($data);

Always test the code with tag area enabled and disabled.

Displaying tags next to the item

Example of displaying of the tags are user interests on the user profile page. User can see the list of interests, each of them is a link that leads to the page that shows all items tagged with this tag.

Here is the code used by Wiki module to display tags the page is tagged with:

echo $OUTPUT->tag_list(core_tag_tag::get_item_tags('mod_wiki', 'wiki_pages', $page->id), null, 'wiki-tags');

Deleting and clearing tags

Cron will automatically remove tag instances that point to non existing items, however it is a good habit to delete tags when the record is deleted. Also you might need to clear tags in the reset course callback:

  • core_tag_tag::remove_all_item_tags($component, $itemtype, $itemid, $tiuserid = 0) - removes all tag instances associated with an item
  • core_tag_tag::delete_instances($component, $itemtype = null, $contextid = null) - deletes tag instances in bulk. Here $component is mandatory in this method, either itemtype or contextid or neither or both can be specified.

Backup and restore

When you tag contents inside the course the plugin has to hook into backup and restore and process necessary tags. This is especially important for the contents inside activity modules, such as wiki pages or forum posts. Questions in the course question bank also backup and restore their tags.

Again, on the example of Wiki pages, include this in the backup_wiki_stepslib.php:

protected function define_structure() {

   // ...
   $tags = new backup_nested_element('tags');
   $tag = new backup_nested_element('tag', array('id'), array('rawname'));
   // ...
   $page->add_child($tags);
   $tags->add_child($tag);
   // ...
   $tag->set_source_sql('SELECT t.id, t.rawname
                       FROM {tag} t
                       JOIN {tag_instance} ti ON ti.tagid = t.id
                      WHERE ti.itemtype = ?
                        AND ti.component = ?
                        AND ti.itemid = ?', array(
                            backup_helper::is_sqlparam('wiki_pages'),
                            backup_helper::is_sqlparam('mod_wiki'),
                            backup::VAR_PARENTID));
   // ...

}

And this in the restore_wiki_stepslib.php:

protected function define_structure() {

   // ...
   $paths[] = new restore_path_element('wiki_tag', '/activity/wiki/subwikis/subwiki/pages/page/tags/tag');
   // ...

}

protected function process_wiki_tag($data) {

   $data = (object)$data;
   if (!core_tag_tag::is_enabled('mod_wiki', 'wiki_pages')) { // Tags disabled in server, nothing to process.
       return;
   }
   $tag = $data->rawname;
   $itemid = $this->get_new_parentid('wiki_page');
   $context = context_module::instance($this->task->get_moduleid());
   core_tag_tag::add_item_tag('mod_wiki', 'wiki_pages', $itemid, $context, $tag);

}

Search callback

This is the most difficult part of Tag API. When user searches for the items tagged with a specific tag only the items user has access to must be returned. Running access check on all items can be very costly. Class core_tag_index_builder can help with retrieving and caching records, especially inside the courses or activity modules.

function mod_wiki_get_tagged_pages($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {

   // Find items.
   // Please refer to existing callbacks in core for examples.
   // ...
   // Use core_tag_index_builder to build and filter the list of items. 
   // Notice how we search for 6 items when we need to display 5 - this way we will know that we need to display a link to the next page.
   $builder = new core_tag_index_builder('mod_wiki', 'wiki_pages', $query, $params, $page * $perpage, $perpage + 1);
   // ...
   $items = $builder->get_items();
   if (count($items) > $perpage) {
       $totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
       array_pop($items);
   }
   // Build the display contents.
   if ($items) {
       $tagfeed = new core_tag\output\tagfeed();
       foreach ($items as $item) {
           $tagfeed->add(...);
       }
       $content = $OUTPUT->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($OUTPUT));
       return new core_tag\output\tagindex($tag, 'mod_wiki', 'wiki_pages', $content,
               $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
   }

}

User-specific tags

It is possible that each tagged item can be tagged by each user independently. Before Moodle 3.0 this was how courses were tagged however from 3.0 tagging courses became more standard. The functionality remains in the API (argument $tiuser to the tagging functions). In this case both tag list and tag cloud will display all tag instances added by all users but each user will be able to edit only their own.

If developer chooses to implement it in the plugin, they need to also implement the UI when admin or other privileged user can remove or edit the instances of another user. Otherwise if teacher has tagged the course and later resigned there will be no way to change their tags. Also such tag instances need special treatment during backup and restore - they are now considered "user data" and user id mapping should be performed.

Advanced usages

Custom plugins may go beyond the standard tags handling and use them without mixing with regular course/user/wiki/blogs tags, hide them from the "Tag search" page and "Tags" block but instead have their own interface to search/categorise using tags. This can be achieved by defining tag collection, make it not searchable and specify a custom URL to link to when the tag is actually displayed. This all can be defined in db/tag.php, see the comments in lib/db/tag.php

  • tag_area::get_collection($component, $itemtype) - will return you the collection that your tag area is in
  • tag_collection::get_tag_cloud() - will return all tags in the collection. There are no API methods to get the tags used in the tag area - this is actually the purpose of tag collections.

See also