|
|
|
|
|
|
| |
This package provides 2 different, but linked, tools. For both of them, PHP5 is mandatory, and PHP5.1 for the back-office.
- Class oLocale allows to manage the display of translations on a localized web application. It's based on an XML feed which structure is simple but must be respected. It needs the asked language, a default language (in both cases, if none is provided, English is set to default), and a path where to find localization files. Default path is 'locales/'. The folder structure must be kept.
If oLocale does not find a trabslation in the current language, it will automatically switch to default language for this translation. It allows you to change languages (current and default) in the same script.
A basic example is provided in the file 'oloc.example.php'. But anyway, its use if very easy :
2 methods are callable :
oLocale::getMsg() which fetches and returns a translation
oLocale::getLoc() which returns current language
And 2 settable/gettable properties:
oLocale::LOCALE which allows you to change current language
oLocale::DEFAULT which allows you to change default language
- a back-office application to manage your translations. It's launched via file 'back.office.php'. A basic but complete online help is available on the back-office. This application allows you to create translations for as many "sites" you need, to manage translation modules, and constants modules (each message, indeed). You can do this either manually or by uploading a file. This file must be based on the template file you'll find in the 'templates/' folder. It's an Excel file.
This back-office, right now, does support only this template, and a defined process : you MUST use this template, then you MUST open it with OpenOffice (version 2.3 for me, but you can try with another one, with no guarantee it will work however), then you MUST save this file as an HTML file (HTML, NOT XHTML), and it's THIS file you will upload in the back-office.
The parser classes are outside the back-office, so you can "easily" create your own templates. To do that, you have 2 files :
'class/class.genparser.php' which should not need to be modified. Ut manages upload and other small stuff.
'class/class.openoffice23htmlparser.php' which extends genparser. This one, you'll have to modify if you want to create your own template.
The back-office provides an example "site" which contains 2 modules and their translations in many languages (Bulgarian, Greek, Czech, English, German, French...); you can thus display these translations, modify them and do whatever you want to do! Well, test the application!
The GUI is full AJax (only not the upload part).
I used Protoype to help coding the javascript.
You will also find in the 'countries/' folder an XML file which provide the names of all the countries in the world in 7 languages, as well as their ISO 3166-1 alpha2 and alpha3 codes, and a function of my own which return these codes, given a country name.
Can be handy. It's used by genparser anyway.
This version (20071101) is not supported by IE. Ther's not much to do, but I did not find the easy way to make it work on that browser.
Tested on Firefox 2, Opera 9, Flock 1.
| <?php
/**
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Johan Barbier <johan.barbier@gmail.com>
* @version 20071031
* @desc Classe pour le back-office de localisation des applications web
*
* FRENCH :
* PRINCIPE : Ce back-office permet de générer les "locales" nécessaires à une application web localisée. La localisation obtenur se base sur la classe oLocale présente dans le répertoire class/ du back-office. Cette classe, si elle ne trouve pas de traduction pour une langue donnée utilisera la langue fixée en tant que langue par défaut à la place.
* Le répertoire de travail des "locales" pour la classe oLocale présente sur un site est "locales/"..
* Le répertoire de travail des "locales" pour le back-office est "websites/". La hiérarchie de ce répertoire est la suivante : websites/nom_site_web/locales/code_pays/modulex.xml
* Chaque racine de site (websites/nom_site_web/locales/) possède automatiquement un répertoire default (au même niveau que le répertoire code_pays) contenant la définition des modules et des constantes attribuées au module, sous forme de fichier xml. x modules = x fichiers.
* C'est ce répertoire "locales/" sous le "site" qu'il faut copier sur le serveur web, sous le site web de production désiré.
*
*
* Pour créer une localisation, il faut commencer par créer un site web (website). Puis le sélectionner dans la liste déroulante des sites web. Toute autre manipulation passe nécessairement par la sélection d'un site web dans la liste déroulante!
*
* Ensuite, en travaillant MANUELLEMENT :
* On y ajoute ensuite une langue. A ce moment là, la langue est présente dans les listes déroulantes des langues disponibles et des langues de référence disponibles.
* On y ajoute un module. De même, le module créé est alors disponible dans la liste déroulante des modules disponibles.
* On peut alors commencer à travailler :
* Pour modifier ou afficher une traduction, il faut absolument sélectionner un module, une langue de référence, et une langue de travail.
* Ceci fait, la liste des constantes avec les traductions dans les 2 langues sélectionnées s'affiche.
* Un champ de saisie permet de saisir une nouvelle constante. Attention à bien respecter les règles énoncées dans le paragraphe MODULES ci-dessous.
* Si la traduction d'une constante pour une des langues n'est pas disponible, s'affiche alors à la place "NO TRANSLATION FOUND".
* Les champs de traduction des 2 langues sont modifiables. Toute modification est répercutée sur le "blur" du champ (à la sortie du champ).
* NB : Toujours bien penser à vérifier que l'on est sur le bon site avant de faire quoi que ce soit!
*
* En travaillant par UPLOAD DE FICHIER :
* Il faut toujours créer un site, puis le sélectionner.
* Ceci fait, il faut prendre le fichier de traduction qui doit etre conforme au modèle présent dans le répertoire template/, et l'ouvrir avec Open Office. Là, l'enregistrer en tant que fichier HTML (et pas XHTML).
* Enfin, l'uploader dans le champ consacré du back-office. Le traitement peut-être long selon la taille du fichier.
* Une fois que le back-office a fini d'intégtrer ce fichier, il affichera un message "Fichier intégré avec succès".
* On peut alors aller afficher les modules, traductions créés.
*
*
* LANGUES : les langues seront préférablement utilisées avec le code ISO 3166-1 alpha 3 du pays. Lors de l'ajout de traductions via le fichier modèle, si les pays ne sont pas renseignés ainsi, la classe va tenter de retrouver ce code via la fonction countries/get.alpha.cn.php. S'il ne le trouve pas, il utilisera le nom présent dans le fichier. Attention à l'encodage en cas de caractères spécieux, dans ce cas! Le mieux étant de vérifier la bonne écriture des pays dans le fichier fourni.
*
* WEBSITES : un simple nom de répertoire valide suffira à la création d'un "website" dans le back-office
*
* MODULE : une chaîne alpha normale, sans caractère spéciaux et surtout pas d'underscore.
*
* CONSTANTES : les constantes doivent être préfixées par le nom du module auquel elles appartiennent, suivi d'un underscore, puis de n'importe quelle chaîne valide pour le nom d'un élément xml (éviter les caractères spéciaux, donc).
*
*
* ENGLISH :
* PURPOSE : This back-office allows you to generate localizations needed for a web application. The localization will be used by the oLocale class, see the given example on how to use this latter.
* Work folder for localization used by oLocale class is 'locales/'.
* Work folder for "locales" used by the back-office is 'websites/'. Structure of this folder is as follows : 'websites/website_name/locales/country_code/module_X.xml'
* Root of a given website (websites/website_name/locales/) is automatically given a 'default/' folder (same level as the 'country_code/' folders) in which you find the module's and constants' definition as an xml file. X modules = X xml files.
* It is THIS 'locales/' folder you'll have to copy to your localized website ('default/' is of no use on your website, however).
*
*
* To create a localization, you must first create a website. Then, you have to select it in the dedicated combo list. Every thing you do NEEDS a website to be selected first.
*
* Then, if working MANUALLY :
* You add a language. Thie language will then be available in the list of available base languages and reference languages.
* You add a module. Just as above, the new module will then be available in the list of available modules for this website.
* You can now start working :
* In order to display, modify or create a given translation, you must select a module, a base language, and a reference language.
* Once done, the list of constants and translations is displayed.
* An input allows you to create a new constant. Please respect the rules given in the chapter MODULE of this help.
* If a translation is not available, 'NO TRANSLATION FOUND' is displayed.
* Translations for both selected languages can be modify. Just click on the cell. Every modification is saved on the 'blur' event of the cell (when you click out of the cell).
* NOTE: Just be SURE you are on the correct website before doing anything!
*
* If working by UPLOADING A FILE :
* You still have to create your website, and then select it.
* Once done, take your translation file which must be compliant to the one given as an example in the 'templates/' folder. It's an Excel file. With this version of the back-office, it is the only available template (you can build your own, though, you'll find everything needed to do so in the 'class/class.genparser.php' and 'class/class.openoffice23htmlparser.php' files). You must open it in OpenOffice 2.3 and save it as an HTML file (I insist : HTML, not XHTML).
* Finally, upload this HTML file in the back-office. It can take a while, depending on the size of your file.
* When the back-office is done with the file, it will display a message "File successfully processed", so you will know.
* You can then display your uploaded translations.
*
*
* LANGUAGES : for languages name, you should use the ISO 3166-1 Alpha3 code, it's a good one! When you add translations via an uploaded file, if languages name does not use this format, the back-office will try to find it. It uses for that what you will find in the 'countries/' folder : an xml file and a function. If it cannot find it, it will use the name found in the file. In that case, be careful about special characters in the name, such as accents...it can be a problem while creating a folder with this name.
*
* WEBSITES : a simple valid folder name will be ok.
*
* MODULE : a normal string, again, without any underscores in it!
*
* CONSTANTES : constants must be prefixed by their module name followed by an underscore (as you will see in the example file in the 'templates/' folder). Then, any xml valid string for tagname.
*/
class backoffice {
/**
* Local website path
*
* @var string
*/
private $sPathLocale;
/**
* Stored available languages
*
* @var ArrayIterator
*/
private $oStoredLanguages;
/**
* Stored available modules
*
* @var ArrayIterator
*/
private $oStoredModules;
/**
* Stored available websites
* Not used at the time. Might be useful later.
*
* @var ArrayIterator
*/
private $oStoredWebsites;
/**
* @desc Constructor. Will initialize backoffice::$sPathLocale property
*
* @param string (optional) $sPathLocale
*/
public function __construct($sPathLocale = null) {
$this->oStoredWebsites = new ArrayIterator(self::getWebsites());
if(!is_null($sPathLocale)) {
$sPathLocale .= '/locales';
if(!is_dir(PATH_ROOT.'websites/'.$sPathLocale)) {
throw new boException(str_replace('__PATH__', $sPathLocale, boException::_MISSING_LOCALE_PATH_));
}
$this->sPathLocale = PATH_ROOT.'websites/'.$sPathLocale.'/';
if(!is_dir($this->sPathLocale.'default')) {
mkdir($this->sPathLocale.'default', 0755);
}
}
}
/**
* @desc Just creates the folder 'websites' if not present and returns its contents
*
* @return array : websites available
*/
public static function getWebsites() {
if(!is_dir(PATH_ROOT.'websites')) {
mkdir(PATH_ROOT.'websites', 0755);
}
return self::getDir(PATH_ROOT.'websites');
}
/**
* @desc Returns the contents of a directory
*
* @param string $sDir : directory to list
* @return array : contents of the directory
*/
private static function getDir($sDir) {
$aDir = scandir($sDir);
$aDir = array_diff($aDir, array('.', '..'));
return $aDir;
}
/**
* @desc Initializes available modules and languages
*
* @return void
*
*/
public function init() {
$this->getLanguages();
$this->getModules();
}
/**
* @desc Gets available languages
*
* @return ArrayIterator
*/
public function getLanguages() {
if(is_null($this->sPathLocale)) {
return new ArrayIterator();
}
$aDir = self::getDir($this->sPathLocale);
$aStoredLanguages = array();
foreach($aDir as $sDir) {
if($sDir !== 'default' && is_dir($this->sPathLocale.$sDir)) {
$aStoredLanguages[] = $sDir;
}
}
return $this->oStoredLanguages = new ArrayIterator($aStoredLanguages);
}
/**
* @desc Gets available modules
*
* @return ArrayIterator
*/
public function getModules() {
if(is_null($this->sPathLocale)) {
return new ArrayIterator();
}
$aDir = self::getDir($this->sPathLocale.'default');
$aStoredModules = array();
foreach($aDir as $sDir) {
$sDir = substr($sDir, 0, strrpos($sDir, '.'));
$aStoredModules[] = $sDir;
}
return $this->oStoredModules = new ArrayIterator($aStoredModules);
}
/**
* @desc Builder method for translations list
*
* @param string $sMod : mdoule asked for
* @param string $sLng : base language asked for
* @param string $sRef : reference language asked for
* @return array : the list of translations for this module, and these languages
*/
public function getTranslationsList($sMod = null, $sLng = null, $sRef = null) {
if((!$this->oStoredLanguages instanceof ArrayIterator) || (!$this->oStoredModules instanceof ArrayIterator)) {
$this->init();
}
$aMessages = array();
$aMessages['REF'] = $this->loopOnParameters($sMod, $sRef);
$aMessages['LNG'] = $this->loopOnParameters($sMod, $sLng);
return $aMessages;
}
/**
* @desc Loops on constants in module asked for, and languages
* I have made available the possibility to retrieve translations for several modules, even if I do not use it in the current backoffice. I have tried, but it is a bit confusing then. Easy to extend, so.
*
* @param string $sMod : module asked for
* @param string $sLng : current languages on which we loop
* @return array : list of translations for modules and languages asked for
*/
private function loopOnParameters($sMod, $sLng) {
$aMessages = array();
if(!is_null($sMod)) {
if(!is_null($sLng)) {
$aMessages[$sLng] = $this->getTranslationList($sMod, $sLng);
} else {
foreach($this->oStoredLanguages as $sLng) {
$aMessages[$sLng] = $this->getTranslationList($sMod, $sLng);
}
}
} else {
foreach($this->oStoredModules as $sMod) {
if(!is_null($sLng)) {
if(empty($aMessages[$sLng])) {
$aMessages[$sLng] = array();
}
$aMessages[$sLng] = array_merge($aMessages[$sLng], $this->getTranslationList($sMod, $sLng));
} else {
foreach($this->oStoredLanguages as $sLng) {
if(empty($aMessages[$sLng])) {
$aMessages[$sLng] = array();
}
$aMessages[$sLng] = array_merge($aMessages[$sLng], $this->getTranslationList($sMod, $sLng));
}
}
}
}
return $aMessages;
}
/**
* @desc Actually fetches list of translation, called by backoffice::loopOnParamaters
*
* @param string $sMod : current module
* @param string $sLng : current language
* @return array : list of translations for this module and this language
*/
private function getTranslationList ($sMod, $sLng) {
$aMessages = array();
$oDefaultXml = simplexml_load_file($this->sPathLocale.'default/'.$sMod.'.xml');
if(file_exists($this->sPathLocale.'/'.$sLng.'/'.$sMod.'.xml')) {
$oXml = simplexml_load_file($this->sPathLocale.'/'.$sLng.'/'.$sMod.'.xml');
} else {
$oXml = null;
}
foreach ($oDefaultXml as $clef => $val) {
if(!empty($oXml->$clef)) {
$aMessages[$sMod][$clef] = (string)$oXml->$clef;
} else {
$aMessages[$sMod][$clef] = '';
}
}
return $aMessages;
}
/**
* @desc : Adds a new module
* Please follow documentation
*
* @param string $sModule : new module name
*/
public function addModule($sModule) {
if(empty($sModule)) {
throw new boException(boException::_EMPTY_PARAMETER_);
}
if(file_exists($this->sPathLocale.'default/'.$sModule)) {
throw new boException(str_replace('__MOD__', $sModule, boException::_MODULE_ALREADY_EXISTS_));
}
if(false !== strpos($sModule, '_')) {
throw new boException(boException::_INVALID_UNDERSCORE_);
}
$sXml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<constants>
</constants>';
file_put_contents($this->sPathLocale.'default/'.$sModule.'.xml', $sXml);
}
/**
* @desc : Adds a new website
* Please follow documentation
*
* @param string $sWebsite : new website name
*/
public function addWebsite($sWebsite) {
if(empty($sWebsite)) {
throw new boException(boException::_EMPTY_PARAMETER_);
}
if(file_exists(PATH_ROOT.'websites/'.$sWebsite)) {
throw new boException(str_replace('__WEB__', $sWebsite, boException::_WEBSITE_ALREADY_EXISTS_));
}
mkdir(PATH_ROOT.'websites/'.$sWebsite);
mkdir(PATH_ROOT.'websites/'.$sWebsite.'/locales');
}
/**
* @desc : Adds a new language
* Please follow documentation
*
* @param string $sLanguage : new language name (best is alpha2 or alpha3)
*/
public function addLanguage($sLanguage) {
if(empty($sLanguage)) {
throw new boException(boException::_EMPTY_PARAMETER_);
}
if(is_dir($this->sPathLocale.$sLanguage)) {
throw new boException(str_replace('__LNG__', $sLanguage, boException::_LANGUAGE_ALREADY_EXISTS_));
}
mkdir($this->sPathLocale.$sLanguage, 0755);
if(!$this->oStoredModules instanceof ArrayIterator) {
$this->getModules();
}
$sXml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<translations>
</translations>';
foreach($this->oStoredModules as $sMod) {
file_put_contents($this->sPathLocale.'/'.$sLanguage.'/'.$sMod.'.xml', $sXml);
}
}
/**
* @desc Small method to parse the html elements ID in the list of translations
*
* @param string $sClef : html element id
* @return array : an array with the parsed ID (constant name, language name, and module name)
*/
private function parseInputId($sClef) {
$aProps = explode('@', $sClef);
$sConst = $aProps[0];
$sLng = $aProps[1];
$sMod = substr($sConst, 0, strpos($sConst, '_'));
return array($sConst, $sLng, $sMod);
}
/**
* @desc Adds a new constant
*
* @param string $sConst : new conatnts name
* @param string $sMod : module owning the new constant
*/
public function addNewConstant($sConst, $sMod) {
if(!file_exists($this->sPathLocale.'default/'.$sMod.'.xml')) {
throw new boException(str_replace('__MOD__', $sMod, boException::_DEFAULT_MOD_NOT_FOUND_));
}
if(substr($sConst, 0, strpos($sConst, '_')) !== $sMod) {
throw new boException(str_replace('__CONST__', $sConst, boException::_INVALID_CONST_));
}
$oXml = new DOMDocument();
$oXml->load($this->sPathLocale.'default/'.$sMod.'.xml');
$root = $oXml->firstChild;
$elem = $oXml->createElement($sConst);
$root->appendChild($elem);
$oXml->save($this->sPathLocale.'default/'.$sMod.'.xml');
}
/**
* @desc Updates a new translation value
*
* @param string $sClef : element ID
* @param string $sVal : new translation value
* @param boolean $bComesFromInput : if sets to true, $sClef does come from HTML, else it comes from uploaded file
* @param string $sLng : language of the new translation
* @param string $sMod : module of the new translation
*/
public function updateValue($sClef, $sVal, $bComesFromInput = true, $sLng = null, $sMod = null) {
if(true === $bComesFromInput) {
$aProps = $this->parseInputId($sClef);
$sConst = $aProps[0];
$sLng = $aProps[1];
$sMod = $aProps[2];
} else {
if(is_null($sLng) || is_null($sMod)) {
throw new boException(boException::_EMPTY_PARAMETER_);
}
$sConst = $sClef;
}
$oXml = new DOMDocument();
if(!file_exists($this->sPathLocale.'/'.$sLng.'/'.$sMod.'.xml')) {
$sXml = '<?xml version="1.0" encoding="ISO-8859-1"?>
<translations>
</translations>';
$oXml->loadXML($sXml);
} else {
$oXml->load($this->sPathLocale.'/'.$sLng.'/'.$sMod.'.xml');
}
$cdata = $oXml->createCDATASection($sVal);
$xpath = new DOMXPath($oXml);
$nodes = $xpath->query('//'.$sConst);
if($nodes->length !== 0) {
foreach($nodes as $oNode) {
$oNode->removeChild($oNode->firstChild);
$oNode->appendChild($cdata);
}
} else {
$elem = $oXml->createElement($sConst);
$elem->appendChild($cdata);
$root = $oXml->firstChild;
$root->appendChild($elem);
}
$oXml->save($this->sPathLocale.'/'.$sLng.'/'.$sMod.'.xml');
}
/**
* @desc Magical getter
*
* @param string $sProp : property asked for
* @return mixe : value of the property asked for
*/
public function __get($sProp) {
switch($sProp) {
case 'MODULES':
return $this->oStoredModules;
break;
case 'LANGUAGES':
return $this->oStoredLanguages;
break;
case 'WEBSITES':
return $this->oStoredWebsites;
break;
case 'LOCALE_PATH':
return $this->sPathLocale;
break;
default:
throw new boException(str_replace('__PROP__', $sLanguage, boException::_PROP_NOT_GETTABLE_));
break;
}
}
}
?> | | |
|
| Objects to XML Serializer/Unserializer Categories : PHP, PHP Classes, DOM XML, Serialize | | | XPath for PHP without the DOM XML extension Categories : DOM XML, XML, XSLT, PHP Classes, PHP | | | very simple ftp class Categories : PHP, PHP Classes, FTP | | | PHP Paypal IPN Integration Class v1.0.0 Categories : PHP, PHP Classes, Payment Gateways | | | Zephyr: AJAX Based Framework for PHP5 Developers Categories : PHP, AJAX, Frameworks, Java Script, Web Applications | | | A Timing Class Categories : PHP, PHP Classes, Date Time | | | The class to check load time of your script
VERY usefull for relatively slow applications, but not only.. Categories : PHP, PHP Classes, Debugging | | | Create HTML forms dynamicly using Javascript & PHP Categories : PHP, PHP Classes, Java Script | | | usercounter class Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables | | | RSS parser.
Parses RSS into an array. Quick and nasty but does the job.
No checking is done for correct Tags, only correct XML.
PHP4 needed to display result (uses print_r). Categories : PHP, XML, PHP Classes, Rich Site Summary (RSS) | | | These PHP Classes Check if a host is alive using various methods. Categories : PHP, PHP Classes, Sockets, CURL | | | an example of the cyberlib payment class Categories : PHP, PHP Classes, Ecommerce, Credit Cards | | | Power Form Validation Categories : PHP, PHP Classes, Data Validation | | | MySQL Handler Categories : PHP, Databases, MySQL, Classes and Objects, PHP Classes | | | pcCalendar class - Allows for the creation of calendars in HTML pages. All output functions can be easily overridden, refer to article 1471 for an example.
Categories : PHP, Date Time, Calendar, PHP Classes | |
|
|
|