Toolserver Intuition

From Toolserver wiki
Revision as of 19:27, 6 February 2012 by Valhallasw (Talk | contribs)
Jump to: navigation, search
Toolserver Intuition
Author: Krinkle

Toolserver Intuition is a system to provide internationalization (i18n) for Toolserver hosted tools.

Intuition (INTUI-tion) stands for " Internationalization for Toolserver's User Interface".

The translation process is managed by and is nightly synced through SVN.



To Install

  1. include (require_once) /home/project/i/n/t/intuition/ToolserverI18N/ToolStart.php.
  2. Create an instance of the TsIntuition class in the $I18N variable.
  3. Use it!


require_once( '/home/project/i/n/t/intuition/ToolserverI18N/ToolStart.php' );
$opts = array(
  'domain' => 'mytoolname', // name of your main text-domain here
$I18N = new TsIntuition( $opts );
echo $I18N->msg( 'welcome' );

Note: If you need messages from multiple domains, you should not create multiple instances of this class. Instead use the second argument of msg(). This class is not a wrapper for one particular domain, it's a wrapper for the entire system and the domain option sets the default domain for msg requests.

Demo: Check a live working sandbox demo of the above script: demo1 (see also other Demos)

TsIntuition Class




  • $options (array or string): An array of options or if you just need to set the text-domain (basic usage) pass a string.
    domain (string): This will set the default domain for messages. Defaults to 'general' (first character is case-insensitive, the rest should be lowercase).
    lang (string): This will override the smart detection method (which uses cookies, parameter overrides etc.). Handy for debugging in a certain language.
    globalfunctions (bool): Set to false to disable the declaration of global functions like _()
    suppressfatal (bool): Prevent TsIntuition from showing fatal errors
    suppressnotice (bool): Prevent TsIntuition from showing notices
    suppressbrackets (bool): Suppress brackets, msg() will return "Messagekey" instead of "[messagekey]" for undefined messages.
    stayalive (bool): Allow a tool to prevent TsIntuition for exiting / dieing on fatal errors
    param (bool): If you use the userlang GET parameter for something else, you can set this to false to prevent TsIntuition from using. and thus it will not override the language set by the cookie.


// Basic example
$I18N = new TsIntuition( 'Mytool' );
// Advanced example. This is in case you already have the _() function for something else
$opts = array(
 'globalfunctions' => false,
 'domain' => 'mytool',
$I18N = new TsIntuition( $opts );

Message functions


msg() gets a message from the message blob. If passed a custom text-domain name it will load the domain on demand if not loaded already.


  • $key (string): Message key to retrieve a message for.
  • $options (array or string): A text-domain name or an array with one or more options:
    domain (string): overrides the currently selected text-domain, and if needed loads it from disk
    lang (string): overrides the currently selected language
    variables (array): numerical array to do variable replacements ($1> var[0], $2> var[1], etc.)
    raw-variables (bool): boolean to determine whether the variables should be escaped as well
    parsemag (bool): boolean to determine whether the message sould be transformed using magic phrases (PLURAL, etc.)
    escape (string): Optionally the return can be escaped. By default this takes place after variable replacement. Set 'raw-variables' to true if you just want the raw message to be escaped and have escaped the variables already.
    • 'plain'
    • 'html' (<>"& escaped)
    • 'htmlspecialchars' (alias of 'html')
    • 'htmlentities' (foreign/UTF-8 chars converted as well)


// Basic usage
echo $I18N->msg( 'message-key' );
// Get a message from the general domain
echo $I18N->msg( 'form-submit', 'general' );
// More advanced usage:
// Get a message, replace $1/$2 with $username/$lastvisit,
//  escape html in the msg (without touching html in $username/$lastvisit).
$username = '<strong>John</strong>';
$lastvisit = '<em>2010-12-31</em>'; 
$welcomeback = $I18N->msg( 'welcome-back', array(
  'variables' => array($username, $lastvisit),
  'escape' => 'html',
  'raw-variables' => true
) );
echo "<p>$welcomeback</p>";
// Now the support for magic words like {{PLURAL: ...}}
// Get a message, parse the magic word using the $1
$numberOfSeconds = 3;
$seconds = $I18N->msg( 'seconds', array('variables' => array( $numberOfSecond ), 'parsemag' => true ) );
echo "<p>$seconds</p>";


Check if a message exists at all. Returns boolean.



When debugging, it may be useful to sometimes simulate a message definition during experimentation. This function allows to add a message to the blob without having to actually define it in the message files or with


  • $key (string): Message-key
  • $message (string): Message itself
  • $domain (string; optional): Defaults to the active text domain
  • $lang (string; optional): Defaults to the currently selected language
_e( 'start-foobar' ); // Echoes [start-foobar] if that message doesn't exist
$I18N->setMsg( 'start-foobar', 'Click here to start Foobar' );
_e( 'start-foobar' ); // Echoes "Click here to start Foobar"


Same as #setMsg, but takes an array to set multiple messages.


  • $messagesByKeys (array): Array of message-keys and message values.
  • $domain (string; optional): Defaults to the active text domain
  • $lang (string; optional): Defaults to the currently selected language


$tmpMsgs = array(
 'awesome' => 'Awesome!',
 'lipsum' => 'Lorem ipsum.',
$I18N->setMsgs( $tmpMsgs );

Get / Set functions

get (variablename)

Returns the language code of the language currently used by the application as main language (the one determined by either the cookie, the userlang-param, override when object was constructed, or set later on via setLang()
Return the directionality (ltr or rtl) of the current language.
$html = "<html dir='{$I18N->getDir()}' lang='{$I18N->getLang()}'>";
Returns the currently selected text domain name.
Returns an array of preferences names and their cookie name keys, such as:
array( 'userlang' => 'TsIntuition_userlang' )
. These may change in the future, so be sure to use this (or the next function) instead of relying on the cookie names.
getCookieName( $name )
Returns only the name of the wanted cookie.
$cookie = $_COOKIES[ $I18N->getCookieName( 'userlang' ) ];
Currently the system uses only one variable (userlang), but for future reference this has been created in advance. Works the same as for cookies, but for variables
getParamName( $name )
See getCookieName.
Returns a boolean. False if using the userlang-parameter was disabled, true otherwise (default).

set (varablename)

setLang( $lang )
Override the currently selected language for messages with a different one. If possible, use the lang option during the construction of $I18N instead.
setDomain( $domain )
Override the currently text domain for messages with a different one. If possible, use the domain option during the construction of $I18N instead.
setUseRequestParam( $bool )
Disable/Enable usage of the userlang parameter. Note that if called after the construction, the language choice has already been initialized. If possible, use the param option during the construction of $I18N instead. Or use setUseRequestParam() function, but don't forget to call $I18N->refreshLang() for it to take effect. Note that calling refreshLang will undo anything setLang() has done, and a possible value for $_GET['userlang'] will now no longer be ignored.


isRTL( $langcode )
Returns true when the current language or (if set) $langcode is RTL.


Returns an array of common values for the current language for usage in PHP's setlocale.

// for 'en'
array( 'en', 'EN', 'en_EN', 'EN_en' );
// for 'zh-classical'
array( 'zh-classical', 'ZH-CLASSICAL' , 'zh_ZH', 'ZH_zh', 'zh', 'ZH' );


Get an array of all registered text domains.

Returns an array of textdomain keys (eg. "Svgtranslate") and as value the filename in which the textdomain is defined (eg. "Svgtranslate.i18n.php").

Lang functions


Return the fallback language for the given language (if available) returns 'en' otherwise.


  • $lang (string): Language code of language to get fallback for.
$I18N->getLangFallback( 'nds' ); // 'de'


Return the language name in the native language.


  • $lang (string): Language code of language to get fallback for.
$I18N->getLangName( 'de' ); // 'Deutsch'
$I18N->getLangName( 'blabla' ); // ''


Return all known languages.

$langs = $I18N->getLangNames();
$langs['af']; //'Afrikaans'	# Afrikaans
$langs['he']; // 'עברית'	# Hebrew

Textdomain functions


Cookie functions






This function checks wether the current visitor has cookies set already or if it's a user that is new to the tool (or hasn't set it yet / wiped it / old browser without cookies).


See for a live demo of these




  • helpTranslateDomain: Either TSINT_HELP_ALL, TSINT_HELP_CURRENT (default), TSINT_HELP_NONE or a string with a textdomain name

Other functions


Get a localized date. Pass a format, time or both. Defaults to the current timestamp in the language's default date format.


  • $format (string): Date format compatible with strftime
  • $timestamp (mixed): Timestamp (seconds since unix epoch) or string (ie. "2011-12-31")
  • $lang (string): Language code. Defaults to current language (through getLocale() )


// If the current user is French and today is 2011-03-28:
// Uses the 'date-only format' from the general textdomain 
$I18N->dateFormatted(); // "28 mars 2011"
// We use the native date+time format from PHP and force 'German' as language and use a parseable string as timestamp
$I18N->dateFormatted( '%c' ,'2011-04-01 5 AM', 'de' ); // "1. April 2011 05:00:00 UTC"
// Use the default 'date-only format' and the current language (say Dutch)
// And pass a unix timestamp from somewhere
$I18N->dateFormatted( 1302121820 ); // "06 april 2011"


In the construct the language choise will be initialized. It starts by checking if there were any hard overrides passed as an option, then it checks (if the param wasn't disabled) if userlang contains a usable value. And if no override is present it will get the userlang-cookie and use it as active language. If the visitor has never visited a tool translated by TsIntuition English will be presumed and used as default.

Calling refreshLang will drop the currently selected language, and re-do initialization.


By default four functions are declared. None of these are required, but they are provided as handy shortcuts for commonly used settings. If you don't need them or if they conflict with function names you have, you can disable them by setting 'globalfunctions' to false when initiating the $I18N object.

function _()

Return a message.


  • $key
  • $options

Shortcut for

$I18N->msg( $key, $options );

function _g()

Return a message from the "general" domain.


  • $key
  • $options

Shortcut for

$I18N->msg( $key, 'general' );

function _html()

Return a message escaped as html.


  • $key
  • $options

Shortcut for

echo $I18N->msg( $key, array( 'escape' => 'html' ) );

function _e()

Echo a message.


  • $key
  • $options

Shortcut for

echo $I18N->msg( $key, $options );

Debug and development

As the automated synchronization is not active yet, and when it will be there may be many requests and just whenever you feel like hacking locally. Follow the next few steps to add a text domain without having to register it anywhere other than in your own directory.

Register single messages locally

  • Initialiaze everything as usual, for example:
$I18N = new TsIntuition( 'Mydomain' );
  • Then you can add one message:
$I18N->setMsg( 'foo-bar', 'Foos and Bars are very imporant' );
  • .. or multiple ones:
$tmpMsgs = array(
  'foo-bar' => 'Foos and Bars are very imporant.',
  'click-bar' => 'To activate Foo, click Bar.',
$I18N->setMsgs( $tmpMsgs  );
// $I18N->msg( 'foo-bar' ) now works normally


There are a few demonstration pages to show you how this tool works. Check them out!

Register entire text-domain locally

  • In our example we'll be translating "FooBear Tool" at
  • Create an i18n file: Foolbear.i18n.php in the same directory (text-domain should only contain lowercase alphabetical and numerical characters starting with a capital letter)
  • Define the $messages array. Like the following;
 * Interface messages for johndoe's tool "Foobear".
$messages['en'] = array(
  'instructions' => 'Grab the tool at it lorems and hold it upside down. Accelerate from the Actions-menu.',
  'menu-actions' => 'Actions',
  'menu-views' => 'Views',
  'action-accelerate' => 'Accelerate',
  'action-reset' => 'Reset the tool',
  'view-bottomup' => 'Turn upside down',
  'view-topdown' => 'This is also upside down, silly.',
  'disclaimer' => 'No bears were harmed while making this tool. And bunnies are cute, even though they make typos!',
  • Load the file into the message memory of TsIntuition, and set it as default for messages from now on:
//$I18N = new TsIntuition( 'Foobear' ); // Since we're debugging, we load this file first and set the domain thereafter:
$I18N = new TsIntuition();
$I18N->loadTextdomainFromFile( __DIR__ . '/Foobear.i18n.php', 'Footool' );
$I18N->setDomain( 'Foobear' );
$I18N->msg( 'view-bottomup' ); // is "Turn upside down".
  • When all this is fine you can commit that file to SVN (if you have access) or request addition at


  • public function gender( $gender, $male, $female, $unknown )
    • Determined based on cookie, just like language is and managed from the settings page.

Tools translated by Toolserver Intuition

See Category:Tools translated by Toolserver Intuition
Personal tools