Note:

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

Output functions: Difference between revisions

From MoodleDocs
m (Protected "Output functions": Developer Docs Migration ([Edit=Allow only administrators] (indefinite)))
 
(38 intermediate revisions by 17 users not shown)
Line 1: Line 1:
This page tries to explain a bit how dynamic data should be sent from Moodle to the browser in a 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.
{{Template:Migrated|newDocId=/docs/apis/subsystems/output#output-functions}}
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!
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, this functions can be discused, modified and new functions can arrive if there are some good reasons for it. Just discuss it in the [http://moodle.org/mod/forum/view.php?id=55 General developer forum] at [http://moodle.org moodle.org].
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 [http://moodle.org/mod/forum/view.php?id=55 General developer forum] at [http://moodle.org moodle.org].
 
For each of the functions below we'll try to explain when they should be used, commenting the most important parameters supported and their meaning. Let's review them!


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() ===
=== 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.


function s($var, $strip=false) and function p($var, $strip=false)
These functions should be used to:
 
This 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.
 
This functions should be used to:
 
* print all the '''values of form fields''' like <nowiki><input></nowiki> or <nowiki><textarea></nowiki> tags.
* print all the '''values of form fields''' like <nowiki><input></nowiki> or <nowiki><textarea></nowiki> tags.
* to '''show plain (non html) text''' that have been introduced by the user (search string, quiz responses...).
* 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
* 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:
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...).
* '''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() ===
=== format_text() ===
 
  function format_text($text, $format = FORMAT_MOODLE, $options = null, $courseid_do_not_use = null)  
  function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL )  
 
This function should be used to:
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...
* 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 [https://docs.moodle.org/dev/String_API#get_string.28.29 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 process to enabled '''filter'''s, supports different '''formats''' of text (HTML, PLAIN, MARKDOWN, MOODLE) and performs a lot of '''automatic conversions''' like adding smilies, build links, so it's a really heavy function. Also, it includes one strong '''cache mechanism''' (DB based) that will alleviate the server from a lot of work processing the same texts time and again.
Note that this function is really '''heavy''' because it supports '''cleaning''' of dangerous contents, delegates processing to enabled '''content filter'''s, 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:
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]].
* '''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_MARKDOW.


* '''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''': 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 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 never''' 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!  
**'''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->filter''': To decide if you want to allow filters to process the text (defaults to true).
**'''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->smiley''': To decide if we want automatic conversion of smilies to images (defaults to true).
**'''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->para''': To decide if you want every paragraph automatically enclosed between html paragraph tags (<nowiki><p>...</p></nowiki>) (defaults to true).
**'''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->newlines''': To decide if linefeeds in text should be converted to html newlines (<nowiki><br /></nowiki>) (defaults to true).
**'''options->para''': To decide if you want every paragraph automatically enclosed between html paragraph tags (<nowiki><p>...</p></nowiki>) (defaults to true). This option only applies to FORMAT_MOODLE.
* '''courseid''': This parameter should be passed always to help filters to know how they should work. This parameter will become less and less important Moodle was 100% of the current course using some session or global variable (it's one work in progress just now) but, for now, it's recommended to set it always in the function call.
**'''options->newlines''': To decide if linefeeds in text should be converted to html newlines (<nowiki><br /></nowiki>) (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() ===
=== format_string() ===
 
  function format_string ($string, $striplinks = true, $options = null )
  function format_string ($string, $striplinks = false, $courseid=NULL )
 
This function should be used to:
 
* print '''short strings (non html) that need filter processing''' (activity titles, post subjects, glossary concepts...).
 
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 it options nor protections'''. It simply filters the strings and return 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 test. Used when we want to show the text inside menus, page titles... (defaults to false).
* '''courseid''': This parameter should be passed always to help filters to know how they should work. This parameter will become less and less important Moodle was 100% of the current course using some session or global variable (it's one work in progress just now) but, for now, it's recommended to set it always in the function call.
 
=== print_textarea() ===
 
function print_textarea($usehtmleditor, $rows, $cols, $width,
                        $height, $name, $value='', $courseid=0, $return=false)
 
This function should be used to:
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 [https://docs.moodle.org/dev/String_API#get_string.28.29 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.


* display <nowiki><textarea></nowiki> fields, when we want to allow users (based in their preferences and browser capabilities) '''to use the visual HTML editor''' instead of one standard 'plain' area.
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:
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).
* '''usehtmleditor''': to decide if the HTML editor must be showed. The value of this parameter must be calculated by the can_use_html_editor() function.
* '''options'''
* '''rows, cols''': to be applied it the standard textarea is showed.
**'''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.
* '''width, height''': to be applied if the HTML editor is used.
**'''options->escape''': To decide if you want to escape HTML entities. True by default.
* '''name''': the name of the field that will contain the text once the form was submitted.
**'''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.
* '''value''': the initial value of the textarea.
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.
* '''courseid''': This parameter should be passed always to help the editor to know where it should work. This parameter will become less and less important Moodle was 100% of the current course using some session or global variable (it's one work in progress just now) but, for now, it's recommended to set it always in the function call.
* '''return''': to decide if the generated html code must be returned to the caller (true) or printed directly (false). Defaults to false.

Latest revision as of 03:18, 14 June 2022

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.