Note:

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

Output functions

From MoodleDocs
Revision as of 03:18, 14 June 2022 by Dev Docs Bot (talk | contribs) (Protected "Output functions": Developer Docs Migration ([Edit=Allow only administrators] (indefinite)))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Important:

This content of this page has been updated and migrated to the new Moodle Developer Resources. The information contained on the page should no longer be seen up-to-date.

Why not view this page on the new site and help us to migrate more content to the new site!

This page tries to explain a bit how dynamic data should be sent from Moodle to the browser in an organised and standard way. Obviously it's possible to have your own output methods but, thinking that you are going to share your code (yep, this is an OpenSource project!) and in the collaborative way we try to build and maintain the system every day, it would be really better to follow the basic guidelines explained below.

By using them you will be helping to have better, more secure and readable code. Spend some minutes trying to understand them, please!

Of course, these functions can be discussed, modified and new functions can arrive if there are some good reasons for it. Just discuss it in the General developer forum at moodle.org.

For each of the functions below we'll try to explain when they should be used, explaining the most important parameters supported and their meaning. Let's review them!

p() and s()

function s($var, $strip=false)
function p($var, $strip=false)

These functions share the same code so they will be explained together. The only difference is that s() returns the string while p() prints it directly.

These functions should be used to:

  • print all the values of form fields like <input> or <textarea> tags.
  • to show plain (non html) text that has been introduced by the user (search string, quiz responses...).
  • in general, all the dynamic data, not being html, that doesn't need to be cleaned nor processed by filters

It is important not to use these functions for strings that contain html markup.

The functions replace certain characters that would have special meaning in html ( <, >, ", ', and &) by html entities so that they are displayed as intended. Note that even though the value of form fields printed with p() will have these characters converted to html entities, the submitted values will contain the original characters again.

The key parameter for this function is:

  • strip: it decides if we want to strip slashes from the string or no. By default it's 'false' so no strip will be performed. We should set such parameter to 'true' only when data to be processed isn't coming from database but from http requests (forms, links...).

format_text()

function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseid_do_not_use = null) 

This function should be used to:

  • print any html/plain/markdown/moodle text, needing any of the features below. Mainly used for long strings like posts, answers, glossary items...
  • filter content through Moodle or 3rd party language filters for multi-language support. Not to be confused with get_string which is used to access localized strings in Moodle and its language packs. Together, these functions enable Moodle multi-language support .

Note that this function is really heavy because it supports cleaning of dangerous contents, delegates processing to enabled content filters, supports different formats of text (HTML, PLAIN, MARKDOWN, MOODLE) and performs a lot of automatic conversions like adding smilies, build links. Also, it includes a strong cache mechanism (DB based) that will alleviate the server from a lot of work processing the same texts time and again.

Some interesting parameters for this function are:

  • format: To tell the function about how the data has been entered. It defaults to FORMAT_MOODLE that is a cool format to process plain text because it features automatic link conversion, smilies and good conversion to html output. Other formats are FORMAT_HTML, FORMAT_PLAIN, FORMAT_MARKDOWN. See Formatting options.
  • options: Here we can specify how we want the process to be performed. You only need to define them if they are different from the default value assumed. Main options are:
    • options->noclean: To decide if we want to skip the clean-up of text, un-protecting us from attacks and other security flaws (defaults to false, so protection is enabled. You shouldn't set it to true ever unless you are 200% sure that only controlled users can edit it (mainly admins). Never use it for general text places (posts...) or you will be, sooner or later, attacked! Note that this option is ignored for FORMAT_PLAIN, the text is never cleaned.
    • options->trusted: Indicates that this content is trusted and does not need clean-up (but only if $CFG->enabletrusttext is true). This argument is ignored if 'noclean' is specified.
    • options->filter: To decide if you want to allow filters to process the text (defaults to true). This is ignored by FORMAT_PLAIN for which filters are never applied.
    • options->context: If text is filtered (and this happens by default), it is very important to specify context (id or object) for applying filters. If context is not specified it will be taken from $PAGE->context and may potentially result in displaying the same text differently on different pages. For example all module-related information should have module context even when it appears in course-level reports, all course-related information such as name and description should have course context even when they are displayed on front page or system pages.
    • options->para: To decide if you want every paragraph automatically enclosed between html paragraph tags (<p>...</p>) (defaults to true). This option only applies to FORMAT_MOODLE.
    • options->newlines: To decide if linefeeds in text should be converted to html newlines (<br />) (defaults to true). This option only applies to FORMAT_MOODLE.
    • options->nocache: If true the string will not be cached and will be formatted every call. Default false.
    • options->overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being returned. Default false.
    • options->allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default false.
    • options->blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified. Default false.
  • courseid_do_not_use: This parameter was earlier used to help applying filters but now is replaced with more precise $options->context, see above

format_string()

function format_string ($string, $striplinks = true, $options = null )

This function should be used to:

  • print short non-html strings that need filter processing (activity titles, post subjects, glossary concepts...). If the string contains HTML, it will be filtered out. If you want the HTML, use format_text() instead.
  • filter content through Moodle or 3rd party language filters for multi-language support. Not to be confused with get_string which is used to access localized strings in Moodle and its language packs. Together, these functions enable Moodle multi-language support .

All enabled heading filters will be applied to the string.

Please note that this function is basically one stripped version of the full format_text() function detailed above and it doesn't offer any of its options or protections. It simply filters the strings and returns the result, so we must ensure that text being processed has been properly cleaned at input time, using the proper xxx_param() functions.

Some interesting parameters for this function are:

  • striplinks: To decide if, after the text has been processed by filters, we must delete any link from the result text. Used when we want to show the text inside menus, page titles... (defaults to true).
  • options
    • options->context: Context (id or object) for applying filters. If context is not specified it will be taken from $PAGE->context and may potentially result in displaying the same text differently on different pages. For example all module-related information should have module context even when it appears in course-level reports, all course-related information such as name and description should have course context even when they are displayed on front page or system pages.
    • options->escape: To decide if you want to escape HTML entities. True by default.
    • options->filter: To decide if you want to allow filters to process the text (defaults to true). This is ignored by FORMAT_PLAIN for which filters are never applied.

Note: in earlier versions of Moodle the third argument was integer $courseid. It is still supported for legacy - if the third argument is an integer instead of array or object it is considered to be course id and is this course's context is passed to the filters being applied.