Note:

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

String API

From MoodleDocs
Revision as of 10:19, 26 April 2017 by David Knuplesch (talk | contribs) (→‎get_string(): using different identifiers for the two examples to help users to distinguish between them)
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Overview

The String API is how you get language text strings to use in the user interface. It handles internationalisation issues, and will use a number of settings and environment variables to present the best text to every user. Moodle has a mechanism that allows a number of places to be searched (in order) to find language strings. This enables language strings to be packaged with plugins and avoids the step of having to copy the language files over to the language directory when a plugin is installed.

Moodle also provide general string functions like substr, strlen etc. for multibyte safe, string operations. It uses mbstring or iconv for UTF-8 strings and falls back to typo3.

Basic concepts

When it is required to lookup a string, two basic items of information are required.

  1. Name of the plugin language file in which it can be found.
  2. Name of the string. For example, get_string('editingquiz', 'quiz') returns "Editing quiz" in the current language.

Adding language file to plugin

Language support for plugin(s) is added by creating a lang subdirectory in the plugin directory. The structure of the lang directory is then the same as the "main" language directory.

Plugin language file name needs to start with the generic type for the plugin. For example all questiontype plugins must be prefixed qtype_, all authentication plugins auth_. Moodle uses this prefix to identify the language search path.

Example for adding language support file for Drag & Drop optional question type

   Description: Drag & Drop optional question type
   Module type: qtype_
   Module name: qtype_dragdrop
   Language file location (English): contrib/plugins/question/type/dragdrop/lang/en/qtype_dragdrop.php

Note:

  • Module names cannot have numbers in them (only A-Z, a-z and underscore). This might be an issue to consider if you are moving from an existing architecture.

Adding name of string in language file

Name of the string is added to a pre-defined array $string. If you want to a string "Editing Quiz" with string name "editingquiz" in Drag & Drop plugin then add the following in qtype_dragdrop.php language file.

<?php
//string name added for 'Editing Quiz'
$string['editingquiz'] = 'Editing Quiz';
//Help string for 'Editing Quiz' (optional)
$string['editingquiz_help'] = 'Help for editing quiz';
?>

Note:

  • Help string name should be suffixed with _help. Look at Help strings for more details.

Files

String functions are defined in

  1. lib/moodlelib.php - locale related functions
  2. lib/textlib.class.php - general string functions (substr, strlen etc.)

Functions and examples

There are three main functions, used in moodle for getting/displaying the localised string, based on user preferred language.

get_string()

Returns a localised string for current user.

Example for displaying string "This is my plug-in" in any language that supports on your site, then you need to use the following identifier in language file (located in appropriate lang directory)

  $string['plugintitle'] = 'This is my plug-in';

If you want to display this string in any supported language, then you would use this function.

  echo get_string('plugintitle', 'module_pluginlangfilename');

If you want to substitute value in the language string then use {$a} for substituting value. $a is an object, string or number that can be used within translation strings. The variable has to be $a, and it has to be in single quotes. For example, if you want to display answer number in Drag & drop plugin then add

  $string['answerno1'] = 'Answer {$a}'; //Substituting string/integer
  $string['answerno2'] = 'Answer {$a->name}'; //Substituting object member

in qtype_dragdrop.php (Drag & Drop language file). And call it using

  //Get string by substituting integer. 
  get_string('answerno1', 'qtype_dragdrop', $number);
  //Get string by substituting object member integer
  $user->number = 10;
  get_string('answerno2', 'qtype_dragdrop', $user);

In Moodle 2.3 there is a new argument to this function $lazyload. Setting $lazyload to true causes get_string to return a lang_string object rather than the string itself.

  $stringobject = get_string('answerno', 'qtype_dragdrop', $number, true);

The fetching of the string is then put off until the string object is first used. The object can be used by calling it's out method or by casting the object to a string, either directly e.g.

  (string)$stringobject 

or indirectly by using the string within another string or echoing it out e.g.

  echo $stringobject;

return "

{$stringobject}

";

Note: using $lazyload and attempting to use the string as an array key will cause a fatal error as objects cannot be used as array keys.

get_strings()

Converts an array of string names to localised strings for a specific plugin. lazy loading is not supported in this function.

  $txt = get_strings(array('enable', 'disable', 'up', 'down', 'none'), 'qtype_dragdrop');
  echo $txt->up;  //Display localised string for up
  echo $txt->down //Display localised string for down

print_string()

Prints out a translated string by using get_string() function

lang_string class

In Moodle 2.3 a special class (lang_string) is used to create an object representation of a string request. In this case string processing doesn't occur until the object is first used. The class was created especially to aid performance in areas where strings were required to be generated but were not necessarily used. As an example the admin navigation tree when generated uses over 1500 strings, of which normally only 1/3 are ever actually printed at any time. The performance advantage is achieved by not actually processing strings that aren't being used, as such reducing the processing required for the page.

lang_string class can be used in two ways

  1. Setting $lazyload (forth argument of the get_string function), to true.
  $string = get_string('yes', 'qtype_dragdrop', null, true);
  1. Direct instantiation
  $string = new lang_string('yes', 'qtype_dragdrop', null, 'en');

String manager

Most of function listed above are just handful wrappers for the methods provided by the string manager class. Some strings related functionality is available only via directly calling the manager's methods.

$stringman = get_string_manager();

The factory function get_string_manager() returns singleton instance of core_string_manager_install in early stages of the site installation, or instance of core_string_manager_standard in all normal situations. These managers implement interface core_string_manager. Methods provided by the interface are

get_string()
Returns the given component string localised in the given language. Can be used to obtain the translation of the string in the other language than the current user's language.
string_exists()
Does the given string actually exist? This is typically checked by a code like

if (get_string_manager()->string_exists('stringidentifier', 'component_name')) {

   // Do something.

}

string_deprecated()
Has the string been deprecated? See String deprecation for details.
get_list_of_countries()
Returns a localised list of all country names, sorted by country keys.
get_list_of_languages()
Returns a localised list of languages, sorted by code keys.
translation_exists()
Checks if the translation exists for the given language.
get_list_of_translations()
Returns localised list of installed language packs.
get_list_of_currencies()
Returns localised list of known currencies.
load_component_strings()
Loads all strings for one component.
reset_caches()
Invalidates all caches, should the manager use some.
get_revision()
Returns string revision counter.

Custom string managers

Moodle 2.9 Plugins can provide custom implementation of the string manager. This is supposed to be used in experimental and/or development scenarios only, not in typical production environment. See MDL-49361 for use cases and implementation details. An example of such an implementation can be found at moodle-local_stringman.git repository.

// Custom string manager class can be defined in the main config.php file. $CFG->customstringmanager = '\local_stringman\dummy_string_manager';

textlib (core_text) class

textlib class provide pool of safe functions to operate on UTF-8 text. textlib provide set of static functions to operate on strings and gets included in setup.php

Moodle 2.6 In Moodle 2.6 the textlib class was renamed to core_text.

asort()

Locale aware sorting, the key associations are kept, values are sorted alphabetically.

code2utf8

Returns the utf8 string corresponding to the unicode value

convert

Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter, fall back to typo3

encode_mimeheader

Generate a correct base64 encoded header to be used in MIME mail messages.

entities_to_utf8

Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8

specialtoascii

Converts upper unicode characters to plain ascii, the returned string may contain unconverted unicode characters.

strlen

Multibyte safe strlen() function, uses iconv for utf-8, falls back to typo3.

strpos

Find the position of the first occurrence of a substring in a string. UTF-8 ONLY safe strpos(), uses iconv.

strrpos

Find the position of the last occurrence of a substring in a string. UTF-8 ONLY safe strrpos(), uses iconv.

strtolower

Multibyte safe strtolower() function, uses mbstring, falls back to typo3.

strtotitle

Makes first letter of each word capital - words must be separated by spaces.

strtoupper

Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.

substr

Multibyte safe substr() function, uses iconv for utf-8, falls back to typo3.

trim_utf8_bom

Removes the BOM from unicode string. more info

utf8_to_entities

Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;

FAQ

When should I use a lang_string object?

The lang_string object is designed to be used in any situation where a string may not be needed, but needs to be generated. The admin navigation tree is a good example of where lang_string objects should be used. A more practical example would be any class that requries strings that may not be printed (after all classes get renderer by renderers and who knows what they will do ;))

When should I not use a lang_string object?

Don't use lang_strings when you are going to use a string immediately. There is no need as it will be processed immediately and there will be no advantage, and in fact perhaps a negative hit as a class has to be instantiated for a lang_string object, however get_string won't require that.

Limitation of lang_string

lang_string object cannot be used as an array offset. Doing so will result in PHP throwing an error. (You can use it as an object property!)

How to compare strings properties in two object

collatorlib_property_comparison class can be used to compare properties of two objects


See also