]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiTranslation.php
function run: @return mixed
[SourceForge/phpwiki.git] / lib / plugin / WikiTranslation.php
1 <?php
2
3 /*
4  * Copyright 2004,2005 $ThePhpWikiProgrammingTeam
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * _WikiTranslation:  Display pagenames and other strings in various languages.
25  * Can also be used to let a favorite translation service translate a whole page.
26  * Current favorite: translate.google.com if from_lang = en or fr
27  *
28  * Examples:
29  *  <<WikiTranslation page=HomePage languages=fr >>
30  *     Translation service for HomePage into french (redirect to translate.google.com)
31  *  <<WikiTranslation what=pages >>
32  *     Translation matrix of all pages with proper translations (all in pgsrc)
33  *  <<WikiTranslation what=wikiwords match="W*" limit=20 >>
34  *     Translation matrix of the first 20 wikiwords matching "W*"
35  *  <<WikiTranslation string=HomePage languages=fr,de,sv >>
36  *     Translation matrix for all given languages
37  *  <<WikiTranslation string=HomePage >>
38  *     Translation matrix for all supported languages
39  *  <<WikiTranslation string=HomePage languages=fr >>
40  *     Just return the translated string for this language.
41  *
42  * @author:  Reini Urban
43  */
44
45 /* Container for untranslated pagenames. Needed to show up in locale/po/phpwiki.pot */
46 $pgsrc_container =
47     _("AddComment") . ',' .
48     _("AddCommentPlugin") . ',' .
49     _("AddingPages") . ',' .
50     _("AllPages") . ',' .
51     _("AllPagesCreatedByMe") . ',' .
52     _("AllPagesLastEditedByMe") . ',' .
53     _("AllPagesOwnedByMe") . ',' .
54     _("AllUsers") . ',' .
55     _("AnalyseAccessLogSql") . ',' .
56     _("AppendText") . ',' .
57     _("AsciiMath") . ',' .
58     _("AsciiSVG") . ',' .
59     _("AtomFeed") . ',' .
60     _("DebugAuthInfo") . ',' .
61     _("AuthorHistory") . ',' .
62     _("AuthorHistoryPlugin") . ',' .
63     _("DebugBackendInfo") . ',' .
64     _("BackLinks") . ',' .
65     _("BlogArchives") . ',' .
66     _("BlogJournal") . ',' .
67     _("BoxRight") . ',' .
68     _("CacheTest") . ',' .
69     _("Calendar") . ',' .
70     _("CalendarList") . ',' .
71     _("CalendarListPlugin") . ',' .
72     _("CalendarPlugin") . ',' .
73     _("CategoryCategory") . ',' .
74     _("CategoryHomePages") . ',' .
75     _("CategoryPage") . ',' .
76     _("Chart") . ',' .
77     _("Chown") . ',' .
78     _("Comment") . ',' .
79     _("CommentPlugin") . ',' .
80     _("CreateBib") . ',' .
81     _("CreatePage") . ',' .
82     _("CreateToc") . ',' .
83     _("CreateTocPlugin") . ',' .
84     _("CurrentTime") . ',' .
85     _("DeadEndPages") . ',' .
86     _("DebugInfo") . ',' .
87     _("Diff") . ',' .
88     _("DynamicIncludePage") . ',' .
89     _("EditMetaData") . ',' .
90     _("EditMetaDataPlugin") . ',' .
91     _("ExternalSearch") . ',' .
92     _("ExternalSearchPlugin") . ',' .
93     _("FacebookLike") . ',' .
94     _("FileInfo") . ',' .
95     _("FindPage") . ',' .
96     _("FoafViewer") . ',' .
97     _("FoafViewerPlugin") . ',' .
98     _("FullRecentChanges") . ',' .
99     _("FullTextSearch") . ',' .
100     _("FuzzyPages") . ',' .
101     _("GoogleMaps") . ',' .
102     _("GooglePlugin") . ',' .
103     _("GoTo") . ',' .
104     _("GraphViz") . ',' .
105     _("DebugGroupInfo") . ',' .
106     _("HelloWorld") . ',' .
107     _("HelloWorldPlugin") . ',' .
108     _("HomePageAlias") . ',' .
109     _("HtmlConverter") . ',' .
110     _("IncludePage") . ',' .
111     _("IncludePagePlugin") . ',' .
112     _("IncludePages") . ',' .
113     _("IncludeSiteMap") . ',' .
114     _("IncludeTree") . ',' .
115     _("InterWiki") . ',' .
116     _("InterWikiSearch") . ',' .
117     _("JabberPresence") . ',' .
118     _("LdapSearch") . ',' .
119     _("LikePages") . ',' .
120     _("LinkDatabase") . ',' .
121     _("LinkIcons") . ',' .
122     _("LinkSearch") . ',' .
123     _("ListPages") . ',' .
124     _("ListRelations") . ',' .
125     _("ListSubpages") . ',' .
126     _("MagicPhpWikiURLs") . ',' .
127     _("MediawikiTable") . ',' .
128     _("ModeratedPage") . ',' .
129     _("MoreAboutMechanics") . ',' .
130     _("MostPopular") . ',' .
131     _("NewPagesPerUser") . ',' .
132     _("NoCache") . ',' .
133     _("OldStyleTable") . ',' .
134     _("OldStyleTablePlugin") . ',' .
135     _("OrphanedPages") . ',' .
136     _("PageDump") . ',' .
137     _("PageGroup") . ',' .
138     _("PageHistory") . ',' .
139     _("PageInfo") . ',' .
140     _("PageTrail") . ',' .
141     _("PasswordReset") . ',' .
142     _("PhotoAlbum") . ',' .
143     _("PhotoAlbumPlugin") . ',' .
144     _("PhpHighlight") . ',' .
145     _("PhpHighlightPlugin") . ',' .
146     _("PhpWeather") . ',' .
147     _("PhpWeatherPlugin") . ',' .
148     _("PhpWiki") . ',' .
149     _("PhpWikiAdministration") . ',' .
150     _("PhpWikiDocumentation") . ',' .
151     _("PhpWikiPoll") . ',' .
152     _("Ploticus") . ',' .
153     _("PloticusPlugin") . ',' .
154     _("PluginManager") . ',' .
155     _("PopularNearby") . ',' .
156     _("PopularTags") . ',' .
157     _("PopUp") . ',' .
158     _("PreferenceApp") . ',' .
159     _("PreferencesInfo") . ',' .
160     _("PrevNext") . ',' .
161     _("Processing") . ',' .
162     _("RandomPage") . ',' .
163     _("RateIt") . ',' .
164     _("RawHtml") . ',' .
165     _("RawHtmlPlugin") . ',' .
166     _("RecentChanges") . ',' .
167     _("RecentChangesCached") . ',' .
168     _("RecentComments") . ',' .
169     _("RecentEdits") . ',' .
170     _("RecentReferrers") . ',' .
171     _("RecentVisitors") . ',' .
172     _("RedirectTo") . ',' .
173     _("RedirectToPlugin") . ',' .
174     _("RelatedChanges") . ',' .
175     _("ReleaseNotes") . ',' .
176     _("Remove") . ',' .
177     _("Rename") . ',' .
178     _("Replace") . ',' .
179     _("DebugRetransform") . ',' .
180     _("RichTable") . ',' .
181     _("RichTablePlugin") . ',' .
182     _("RssFeed") . ',' .
183     _("SearchHighlight") . ',' .
184     _("SemanticRelations") . ',' .
185     _("SemanticSearch") . ',' .
186     _("SemanticSearchAdvanced") . ',' .
187     _("SetAcl") . ',' .
188     _("SiteMap") . ',' .
189     _("SpellCheck") . ',' .
190     _("SpecialPages") . ',' .
191     _("SqlResult") . ',' .
192     _("SyncWiki") . ',' .
193     _("SyntaxHighlighter") . ',' .
194     _("SystemInfo") . ',' .
195     _("SystemInfoPlugin") . ',' .
196     _("Template") . ',' .
197     _("TeX2png") . ',' .
198     _("text2png") . ',' .
199     _("TextFormattingRules") . ',' .
200     _("TexToPng") . ',' .
201     _("TitleSearch") . ',' .
202     _("Transclude") . ',' .
203     _("TranscludePlugin") . ',' .
204     _("TranslateText") . ',' .
205     _("UnfoldSubpages") . ',' .
206     _("UnfoldSubpagesPlugin") . ',' .
207     _("UpLoad") . ',' .
208     _("UpLoadPlugin") . ',' .
209     _("UriResolver") . ',' .
210     _("UserPreferences") . ',' .
211     _("UserRatings") . ',' .
212     _("Video") . ',' .
213     _("VisualWiki") . ',' .
214     _("WabiSabi") . ',' .
215     _("WantedPages") . ',' .
216     _("WantedPagesOld") . ',' .
217     _("WatchPage") . ',' .
218     _("WhoIsOnline") . ',' .
219     _("WikiAdminChown") . ',' .
220     _("WikiAdminDeleteAcl") . ',' .
221     _("WikiAdminPurge") . ',' .
222     _("WikiAdminRemove") . ',' .
223     _("WikiAdminRename") . ',' .
224     _("WikiAdminSearchReplace") . ',' .
225     _("WikiAdminSelect") . ',' .
226     _("WikiAdminSetAcl") . ',' .
227     _("WikiAdminSetAclSimple") . ',' .
228     _("WikiAdminSetExternal") . ',' .
229     _("WikiAdminUtils") . ',' .
230     _("WikiBlog") . ',' .
231     _("WikiBlogPlugin") . ',' .
232     _("WikicreoleTable") . ',' .
233     _("WikiForm") . ',' .
234     _("WikiFormRich") . ',' .
235     _("WikiForum") . ',' .
236     _("WikiPlugin") . ',' .
237     _("WikiPoll") . ',' .
238     _("WikiTranslation") . ',' .
239     _("WikiWikiWeb") . ',' .
240     _("YouTube");
241
242 require_once 'lib/PageList.php';
243
244 class WikiPlugin_WikiTranslation
245     extends WikiPlugin
246 {
247
248     function getDescription()
249     {
250         return _("Show translations of various words or pages.");
251     }
252
253     function getDefaultArguments()
254     {
255         return array_merge
256         (
257             PageList::supportedArgs(),
258             array('languages' => '', // comma delimited string of de,en,sv,...
259                 'string' => '',
260                 'page' => '', // use a translation service
261                 'what' => 'pages', // or 'buttons', 'plugins' or 'wikiwords'
262
263                 'match' => '*',
264                 'from_lang' => false,
265                 'include_empty' => false,
266                 //'exclude'       => '',
267                 //'sortby'        => '',
268                 //'limit'         => 0,
269                 'nolinks' => false, // don't display any links
270                 // (for development only)
271                 'noT' => false // don't display the T link
272                 // (for development only)
273             ));
274     }
275
276     function init_locale($lang)
277     {
278         if ($lang != $this->lang)
279             update_locale($lang);
280         $this->_locales[$lang] = $locale;
281     }
282
283     // reverse translation:
284     function translate_to_en($text, $lang = false)
285     {
286         if (!$lang) $lang = $this->lang; // current locale
287         if ($lang == 'en') return $text;
288
289         $this->_locales = array();
290         $this->_reverse_locales = array();
291
292         if (!isset($this->_locales[$lang])) {
293             $this->init_locale($lang);
294         }
295         assert(!empty($this->_locales[$lang]));
296         if (!isset($this->_reverse_locales[$lang])) {
297             // and now do a reverse lookup in the $locale hash
298             $this->_reverse_locales[$lang] = array_flip($this->_locales[$lang]);
299         }
300         if (!empty($this->_reverse_locales[$lang][$text])) {
301             return $this->_reverse_locales[$lang][$text];
302         } else {
303             return $text;
304         }
305     }
306
307     /**
308      * setlocale() switching with the gettext extension is by far too slow.
309      * So use the hash regardless if gettext is loaded or not.
310      */
311     function fast_translate($text, $to_lang, $from_lang = false)
312     {
313         if (!$from_lang) $from_lang = $this->lang; // current locale
314         if ($from_lang == $to_lang) return $text;
315         // setup hash from en => to_lang
316         if (!isset($this->_locales[$to_lang]))
317             $this->init_locale($to_lang);
318         if ($from_lang != 'en') {
319             // get reverse gettext: translate to english
320             $text = $this->translate_to_en($text, $from_lang);
321         }
322         return !empty($this->_locales[$to_lang][$text])
323             ? $this->_locales[$to_lang][$text]
324             : $text;
325     }
326
327     //FIXME! There's something wrong.
328     function translate($text, $to_lang, $from_lang = false)
329     {
330         if (!$from_lang) $from_lang = $this->lang; // current locale
331         if ($from_lang == $to_lang) return $text;
332         // Speed up hash lookup. Not needed for gettext module
333         if (!isset($this->_locales[$from_lang]) and !function_exists('bindtextdomain')) {
334             $this->init_locale($from_lang);
335         }
336         if ($from_lang != 'en') {
337             // get reverse gettext: translate to english
338             $en = $this->translate_to_en($text, $from_lang);
339             // and then to target
340             update_locale($to_lang);
341             $result = gettext($en);
342             update_locale($from_lang);
343         } else {
344             // locale switching is very slow with the gettext extension.
345             // better use fast_translate
346             if ($from_lang != $to_lang) {
347                 update_locale($to_lang);
348             }
349             $result = gettext($text);
350             if ($from_lang != $to_lang) {
351                 update_locale($from_lang);
352             }
353         }
354         return $result;
355     }
356
357     /**
358      * @param WikiDB $dbi
359      * @param string $argstr
360      * @param WikiRequest $request
361      * @param string $basepage
362      * @return mixed
363      */
364     function run($dbi, $argstr, &$request, $basepage)
365     {
366         $this->args = $this->getArgs($argstr, $request);
367         extract($this->args);
368         $this->request = &$request;
369         if (!$from_lang) $from_lang = $request->getPref('lang');
370         if (!$from_lang) $from_lang = $GLOBALS['LANG'];
371         $this->lang = $from_lang;
372
373         if (empty($languages)) {
374             $available_languages = listAvailableLanguages();
375             if ($from_lang == 'en') {
376                 // "en" is always the first.
377                 array_shift($available_languages);
378             }
379             // put from_lang to the very end.
380             if (in_array($from_lang, $available_languages))
381                 $languages = $available_languages;
382             else
383                 $languages = array_merge($available_languages, array($from_lang));
384         } elseif (strstr($languages, ',')) {
385             $languages = explode(',', $languages);
386         } else {
387             $languages = array($languages);
388         }
389         $to_lang = $languages[0];
390         if (!empty($string) and count($languages) == 1) {
391             return $this->translate($string, $to_lang, $from_lang);
392         }
393         if (!empty($page)) {
394             $pagename = $page;
395             if ($dbi->isWikiPage($pagename)) {
396                 $url = '';
397                 // google can only translate from english and french
398                 if (in_array($from_lang, array('en', 'fr'))) {
399                     $url = "http://translate.google.com/translate";
400                     $url .= "?langpair=" . urlencode($from_lang . "|" . $to_lang);
401                     $url .= "&u=" . urlencode(WikiURL($pagename, array(), true));
402                 }
403                 // redirect or transclude?
404                 if ($url) {
405                     return $request->redirect($url);
406                 }
407                 return HTML(fmt("TODO: Google can only translate from english and french. Find a translation service for %s to language %s",
408                     WikiURL($pagename, array(), true),
409                     $to_lang));
410             } else {
411                 return $this->error(fmt("%s is empty.", $pagename));
412             }
413         }
414
415         $pagelist = new PageList('', $exclude, $this->args);
416         $pagelist->_columns[0]->_heading = "$from_lang";
417         foreach ($languages as $lang) {
418             if ($lang == $from_lang) continue;
419             $field = "custom:$lang";
420             $pagelist->addColumnObject(
421                 new _PageList_Column_customlang($field, $from_lang, $this));
422         }
423         if (!empty($string)) {
424             $pagelist->addPage($string);
425             return $pagelist;
426         }
427         switch ($what) {
428             case 'allpages':
429                 $pagelist->addPages($dbi->getAllPages($include_empty, $sortby,
430                     $limit, $exclude));
431                 break;
432             case 'pages':
433                 // not all pages, only the pgsrc pages
434                 if (!is_array($exclude))
435                     $exclude = $pagelist->explodePageList($exclude, false, $sortby,
436                         $limit, $exclude);
437                 $path = FindLocalizedFile(WIKI_PGSRC);
438                 $pgsrc = new fileSet($path);
439                 foreach ($pgsrc->getFiles($exclude, $sortby, $limit) as $pagename) {
440                     $pagename = urldecode($pagename);
441                     if (substr($pagename, -1, 1) == '~') continue;
442                     if (in_array($pagename, $exclude))
443                         continue; // exclude page.
444                     if ($match != '*' and !glob_match($match, $pagename))
445                         continue;
446                     $page_handle = $dbi->getPage($pagename);
447                     $pagelist->addPage($page_handle);
448                 }
449                 break;
450             case 'wikiwords':
451                 if (!isset($this->_locales[$from_lang])) {
452                     $this->init_locale($from_lang);
453                 }
454                 $locale = & $this->_locales[$from_lang];
455                 if (is_array($locale)) {
456                     $count = 0;
457                     foreach ($locale as $from => $to) {
458                         if ($match != '*' and !glob_match($match, $from))
459                             continue;
460                         if (isWikiWord($from)) {
461                             $count++;
462                             $pagelist->addPage($from);
463                             if ($limit and $count > $limit) break;
464                         }
465                     }
466                 }
467                 break;
468             // all Button texts, which need a localized .png
469             // where to get them from? templates/*.tmpl: Button()
470             // and WikiLink(?,'button')
471             // navbar links, actionpages, and admin requests
472             case 'buttons':
473                 $buttons = $GLOBALS['AllActionPages'];
474                 $fileset = new FileSet(FindFile("themes/MacOSX/buttons/en"),
475                     "*.png");
476                 foreach ($fileset->getFiles() as $file) {
477                     $b = urldecode(substr($file, 0, -4));
478                     if (!in_array($b, $buttons))
479                         $buttons[] = $b;
480                 }
481                 $count = 0;
482                 foreach ($buttons as $button) {
483                     $pagelist->addPage($button);
484                     if ($limit and ++$count > $limit) break;
485                 }
486                 break;
487         }
488         return $pagelist;
489     }
490 }
491
492 class _PageList_Column_customlang extends _PageList_Column
493 {
494     function _PageList_Column_customlang($field, $from_lang, $plugin)
495     {
496         $this->_field = $field;
497         $this->_from_lang = $from_lang;
498         $this->_plugin =& $plugin;
499         $this->_what = $plugin->args['what'];
500         $this->_noT = $plugin->args['noT'];
501         $this->_nolinks = $plugin->args['nolinks'];
502         $this->_iscustom = substr($field, 0, 7) == 'custom:';
503         if ($this->_iscustom)
504             $this->_field = substr($field, 7);
505         //$heading = $field;
506         $this->dbi = &$GLOBALS['request']->getDbh();
507         $this->_PageList_Column_base($this->_field);
508     }
509
510     function _getValue($page, &$revision_handle)
511     {
512         if (is_object($page)) $text = $page->getName();
513         else $text = $page;
514         $trans = $this->_plugin->fast_translate($text, $this->_field,
515             $this->_from_lang);
516         // how to markup untranslated words and not existing pages?
517         // untranslated: (TODO) link to translation editor
518         if ($trans == $text or // untranslated
519             (($this->_from_lang != 'en') and
520                 ($this->_field != 'en') and
521                     ($trans == $this->_plugin->fast_translate($text, 'en',
522                         $this->_from_lang))
523             )
524         ) {
525             global $WikiTheme;
526             $link = $WikiTheme->linkUnknownWikiWord($trans);
527             if (!($this->_noT or $this->_nolinks)
528                 and $this->dbi->isWikiPage($trans)
529             ) {
530                 $url = WikiURL($trans, array('action' => 'TranslateText',
531                     'lang' => $this->_field));
532                 $button = $WikiTheme->makeButton('T', $url);
533                 $button->addTooltip(sprintf(_("Define the translation for %s in %s"),
534                     $trans, $this->_field));
535                 $link = HTML::span($button);
536                 $link->setAttr('class', 'wikiunknown');
537                 $text = HTML::span($WikiTheme->maybeSplitWikiWord($trans));
538                 $text->setAttr('style', 'text-decoration:line-through');
539                 $link->pushContent($text);
540                 return $link;
541             } elseif (is_object($page))
542                 return ''; else // not existing: empty
543                 return '';
544         } elseif (is_object($page)) {
545             if (!$this->_nolinks)
546                 return WikiLink($trans, 'auto');
547             else
548                 return $trans;
549         } else {
550             return $trans;
551         }
552     }
553 }
554
555 // Local Variables:
556 // mode: php
557 // tab-width: 8
558 // c-basic-offset: 4
559 // c-hanging-comment-ender-p: nil
560 // indent-tabs-mode: nil
561 // End: