1<?php
2/**
3 * pfci18n.class.php
4 *
5 * Copyright � 2006 Stephane Gully <stephane.gully@gmail.com>
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, 51 Franklin St, Fifth Floor,
20 * Boston, MA  02110-1301  USA
21 */
22
23require_once(dirname(__FILE__)."/pfctools.php");
24
25function _pfc()
26{
27  $args = func_get_args();
28  $serverid = isset($GLOBALS['serverid']) ? $GLOBALS['serverid'] : 0; // serverid is used to avoid conflicts with external code using same 'i18n' key
29  $args[0] = isset($GLOBALS[$serverid]["i18n"][$args[0]]) && $GLOBALS[$serverid]["i18n"][$args[0]] != "" ?
30    ($GLOBALS["output_encoding"] == "UTF-8" ?
31       $GLOBALS[$serverid]["i18n"][$args[0]] :
32       iconv("UTF-8", $GLOBALS["output_encoding"], $GLOBALS[$serverid]["i18n"][$args[0]])) :
33    "_".$args[0]."_";
34  return call_user_func_array('sprintf', $args);
35}
36/**
37 * Just like _pfc but just return the raw translated string, keeping the %s into it
38 * (used by the javascript resources (i18n) class)
39 */
40function _pfc2()
41{
42  $args = func_get_args();
43  $serverid = isset($GLOBALS['serverid']) ? $GLOBALS['serverid'] : 0; // serverid is used to avoid conflicts with external code using same 'i18n' key
44  $args[0] = isset($GLOBALS[$serverid]["i18n"][$args[0]]) && $GLOBALS[$serverid]["i18n"][$args[0]] != "" ?
45    ($GLOBALS["output_encoding"] == "UTF-8" ?
46       $GLOBALS[$serverid]["i18n"][$args[0]] :
47       iconv("UTF-8", $GLOBALS["output_encoding"], $GLOBALS[$serverid]["i18n"][$args[0]])) :
48    "_".$args[0]."_";
49  return $args[0];
50}
51
52class pfcI18N
53{
54  function Init($language,$type="main")
55  {
56    if ($type=="admin")
57      if (!in_array($language, pfcI18N::GetAcceptedLanguage("admin")))
58        $language = pfcI18N::GetDefaultLanguage();
59    if (!in_array($language, pfcI18N::GetAcceptedLanguage()))
60      $language = pfcI18N::GetDefaultLanguage();
61
62    if ($type=="admin")
63      require_once(dirname(__FILE__)."/../i18n/".$language."/admin.php");
64    else
65      require_once(dirname(__FILE__)."/../i18n/".$language."/main.php");
66
67    $serverid = isset($GLOBALS['serverid']) ? $GLOBALS['serverid'] : 0; // serverid is used to avoid conflicts with external code using same 'i18n' key
68    $GLOBALS[$serverid]['i18n'] = $GLOBALS['i18n']; // do not pass by reference because $GLOBALS['i18n'] is maybe used by unknown external code
69
70    $GLOBALS["output_encoding"] = "UTF-8"; // by default client/server communication is utf8 encoded
71  }
72
73  /**
74   * Switch output encoding in order to write the right characteres in the web page
75   */
76  function SwitchOutputEncoding($oe = "")
77  {
78    if ($oe == "")
79    {
80      $GLOBALS["output_encoding"]     = $GLOBALS["old_output_encoding"];
81      unset($GLOBALS["old_output_encoding"]);
82    }
83    else
84    {
85      if (isset($GLOBALS["old_output_encoding"]))
86        die("old_output_encoding must be empty (".$GLOBALS["old_output_encoding"].")");
87      $GLOBALS["old_output_encoding"] = $GLOBALS["output_encoding"];
88      $GLOBALS["output_encoding"]     = $oe;
89    }
90  }
91
92  /**
93   * Return the default language : "en"
94   */
95  function GetDefaultLanguage()
96  {
97    return "en_US";
98  }
99
100  /**
101   * Return the language list supported bye i18n system
102   * (content of the i18n directory)
103   */
104  function GetAcceptedLanguage($type="main")
105  {
106    return /*<GetAcceptedLanguage>*/array('nl_NL','ko_KR','nl_BE','tr_TR','pt_PT','en_US','eo','hr_HR','vi_VN','es_ES','zh_TW','nn_NO','ru_RU','id_ID','hu_HU','th_TH','hy_AM','oc_FR','da_DK','de_DE-formal','uk_RO','nb_NO','fr_FR','it_IT','sv_SE','uk_UA','sr_CS','ar_LB','bg_BG','pt_BR','ba_BA','bn_BD','el_GR','zh_CN','gl_ES','pl_PL','de_DE-informal','ja_JP');/*</GetAcceptedLanguage>*/
107  }
108
109  /**
110   * Parse the source-code and update the i18n ressources files
111   */
112  function UpdateMessageRessources()
113  {
114    // first of all, update the GetAcceptedLanguage list
115    $i18n_basepath = dirname(__FILE__).'/../i18n';
116    $i18n_accepted_lang = array();
117    $dh = opendir($i18n_basepath);
118    while (false !== ($file = readdir($dh)))
119    {
120      // skip . and .. generic files, skip also .svn directory
121      if ($file == "." || $file == ".." || strpos($file,".")===0) continue;
122      if (file_exists($i18n_basepath.'/'.$file.'/main.php')) $i18n_accepted_lang[] = $file;
123    }
124    closedir($dh);
125    $i18n_accepted_lang_str = "array('" . implode("','", $i18n_accepted_lang) . "');";
126    $data = file_get_contents_flock(__FILE__);
127    $data = preg_replace("/(\/\*<GetAcceptedLanguage>\*\/)(.*)(\/\*<\/GetAcceptedLanguage>\*\/)/",
128                         "$1".$i18n_accepted_lang_str."$3",
129                         $data);
130    file_put_contents(__FILE__, $data, LOCK_EX);
131
132    // Now scan the source code in order to find "_pfc" patterns
133    $files = array();
134    $files = array_merge($files, glob(dirname(__FILE__)."/*.php"));
135    $files = array_merge($files, glob(dirname(__FILE__)."/commands/*.php"));
136    $files = array_merge($files, glob(dirname(__FILE__)."/containers/*.php"));
137    $files = array_merge($files, glob(dirname(__FILE__)."/proxies/*.php"));
138    $files = array_merge($files, glob(dirname(__FILE__)."/client/*.php"));
139    $files = array_merge($files, glob(dirname(__FILE__)."/../themes/default/*.php"));
140    $res = array();
141    foreach ( $files as $src_filename )
142    {
143      $lines = file($src_filename);
144      $line_nb = 1;
145      foreach( $lines as $l)
146      {
147        // the labels server side
148        if( preg_match_all('/_pfc\("([^\"]+)"/', $l, $matches) )
149        {
150          foreach($matches[1] as $label)
151          {
152            echo "line: ".$line_nb."\t- ".$label."\n";
153            $res[$label] = "// line ".$line_nb." in ".basename($src_filename);
154          }
155        }
156        // the labels client side (JS)
157        if( preg_match_all('/"([^"]*)",\s\/\/\s_pfc/', $l, $matches) )
158        {
159          echo "line: ".$line_nb."\t- ".$matches[1][0]."\n";
160          $res[$matches[1][0]] = "// line ".$line_nb." in ".basename($src_filename);
161        }
162        $line_nb++;
163      }
164    }
165
166    $dst_filenames = array();
167    foreach($i18n_accepted_lang as $lg)
168      $dst_filenames[] = dirname(__FILE__)."/../i18n/".$lg."/main.php";
169
170    foreach( $dst_filenames as $dst_filename )
171    {
172      // filter lines to keep, line to add
173      $old_content = file_get_contents_flock($dst_filename);
174      // remove php tags to keep only real content
175      $old_content = preg_replace("/^\<\?php/", "", $old_content);
176      $old_content = preg_replace("/\?\>$/", "", $old_content);
177
178      // save into the file
179      $new_content = "";
180      foreach($res as $str => $com)
181      {
182        //echo "com=".$com."\n";
183        //echo "str=".$str."\n";
184        if (preg_match("/".preg_quote($str,'/')."/", $old_content) == 0)
185          $new_content .= $com."\n\$GLOBALS[\"i18n\"][\"".$str."\"] = \"\";\n\n";
186      }
187      $content = "<?php" . $old_content . $new_content . "?>";
188      //echo $content;
189
190      file_put_contents($dst_filename, $content, LOCK_EX);
191    }
192  }
193}
194
195?>
196