xref: /plugin/autotranslation/helper.php (revision 04971eea45156aeb084c3a7f8bb24951c8c3f07d)
1<?php
2/**
3 * Translation Plugin: Simple multilanguage plugin
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9// must be run within Dokuwiki
10if(!defined('DOKU_INC')) die();
11
12class helper_plugin_translation extends DokuWiki_Plugin {
13    var $trans       = array();
14    var $tns         = '';
15    var $defaultlang = '';
16    var $LN          = array(); // hold native names
17    var $opts        = array(); // display options
18
19    /**
20     * Initialize
21     */
22    function helper_plugin_translation(){
23        global $conf;
24        require_once(DOKU_INC.'inc/pageutils.php');
25        require_once(DOKU_INC.'inc/utf8.php');
26
27        // load wanted translation into array
28        $this->trans = strtolower(str_replace(',',' ',$this->getConf('translations')));
29        $this->trans = array_unique(array_filter(explode(' ',$this->trans)));
30        sort($this->trans);
31
32        // load language names
33        $this->LN = confToHash(dirname(__FILE__).'/lang/langnames.txt');
34
35        // display options
36        $this->opts = $this->getConf('display');
37        $this->opts = explode(',',$this->opts);
38        $this->opts = array_map('trim',$this->opts);
39        $this->opts = array_fill_keys($this->opts, true);
40
41        // get default translation
42        if(!$conf['lang_before_translation']){
43            $dfl = $conf['lang'];
44        } else {
45            $dfl = $conf['lang_before_translation'];
46        }
47        if(in_array($dfl,$this->trans)){
48            $this->defaultlang = $dfl;
49        }else{
50            $this->defaultlang = '';
51            array_unshift($this->trans,'');
52        }
53
54        $this->tns = cleanID($this->getConf('translationns'));
55        if($this->tns) $this->tns .= ':';
56    }
57
58    /**
59     * Check if the given ID is a translation and return the language code.
60     */
61    function getLangPart($id){
62        list($lng) = $this->getTransParts($id);
63        return $lng;
64    }
65
66    /**
67     * Check if the given ID is a translation and return the language code and
68     * the id part.
69     */
70    function getTransParts($id){
71        $rx = '/^'.$this->tns.'('.join('|',$this->trans).'):(.*)/';
72        if(preg_match($rx,$id,$match)){
73            return array($match[1],$match[2]);
74        }
75        return array('',$id);
76    }
77
78    /**
79     * Returns the browser language if it matches with one of the configured
80     * languages
81     */
82    function getBrowserLang(){
83        $rx = '/(^|,|:|;|-)('.join('|',$this->trans).')($|,|:|;|-)/i';
84        if(preg_match($rx,$_SERVER['HTTP_ACCEPT_LANGUAGE'],$match)){
85            return strtolower($match[2]);
86        }
87        return false;
88    }
89
90    /**
91     * Returns the ID and name to the wanted translation, empty
92     * $lng is default lang
93     */
94    function buildTransID($lng,$idpart){
95        global $conf;
96        if($lng){
97            $link = ':'.$this->tns.$lng.':'.$idpart;
98            $name = $lng;
99        }else{
100            $link = ':'.$this->tns.$idpart;
101            $name = $this->realLC('');
102        }
103        return array($link,$name);
104    }
105
106    /**
107     * Returns the real language code, even when an empty one is given
108     * (eg. resolves th default language)
109     */
110    function realLC($lc){
111        global $conf;
112        if($lc){
113            return $lc;
114        }elseif(!$conf['lang_before_translation']){
115            return $conf['lang'];
116        } else {
117            return $conf['lang_before_translation'];
118        }
119    }
120
121    /**
122     * Check if current ID should be translated and any GUI
123     * should be shown
124     */
125    function istranslatable($id,$checkact=true){
126        global $ACT;
127
128        if($checkact && $ACT != 'show') return false;
129        if($this->tns && strpos($id,$this->tns) !== 0) return false;
130        $skiptrans = trim($this->getConf('skiptrans'));
131        if($skiptrans &&  preg_match('/'.$skiptrans.'/ui',':'.$id)) return false;
132        $meta = p_get_metadata($id);
133        if($meta['plugin']['translation']['notrans']) return false;
134
135        return true;
136    }
137
138    /**
139     * Return the (localized) about link
140     */
141    function showAbout() {
142        global $ID;
143        global $conf;
144        global $INFO;
145
146        $about = $this->getConf('about');
147        if($this->getConf('localabout')){
148            list($lc,$idpart) = $this->getTransParts($about);
149            list($about,$name) = $this->buildTransID($conf['lang'],$idpart); #FIXME conf[lang] is wrong
150            $about = cleanID($about);
151        }
152
153        $out = '';
154        $out .= '<sup>';
155        $out .= html_wikilink($about,'?');
156        $out .= '</sup>';
157
158        return $out;
159    }
160
161    /**
162     * Displays the available and configured translations. Needs to be placed in the template.
163     */
164    function showTranslations(){
165        global $ID;
166        global $conf;
167        global $INFO;
168
169        if(!$this->istranslatable($ID)) return;
170        $this->checkage();
171
172        list($lc,$idpart) = $this->getTransParts($ID);
173        $lang = $this->realLC($lc);
174
175
176        $out  = '<div class="plugin_translation">';
177
178        //show title and about
179        if ($this->getConf('description')){
180            $out .= '<span>'.$this->getLang('translations');
181            if ($this->getConf('about')) $out .= $this->showAbout();
182            $out .= ':</span> ';
183        }
184
185        // open wrapper
186        if($this->getConf('dropdown')){
187            // select needs its own styling
188            if($INFO['exists']){
189                $class = 'wikilink1';
190            }else{
191                $class = 'wikilink2';
192            }
193            if(isset($this->opts['flag'])){
194                $flag   = DOKU_BASE.'lib/plugins/translation/flags/'.hsc($lang).'.gif';
195            }
196            $out .= '<form action="'.wl().'" id="translation__dropdown">';
197            if($flag) $out .= '<img src="'.$flag.'" alt="'.hsc($lang).'" height="11" class="'.$class.'" /> ';
198            $out .= '<select name="id" class="'.$class.'">';
199        }else{
200            $out .= '<ul>';
201        }
202
203        // insert items
204        foreach($this->trans as $t){
205            $out .= $this->getTransItem($t, $idpart);
206        }
207
208        // close wrapper
209        if($this->getConf('dropdown')){
210            $out .= '</select>';
211            $out .= '<input name="go" type="submit" value="&rarr;" />';
212            $out .= '</form>';
213        }else{
214            $out .= '</ul>';
215        }
216
217        // show about if not already shown
218        if (!$this->getConf('description') && $this->getConf('about')) {
219            $out .= '&nbsp';
220            $out .= $this->showAbout();
221        }
222
223        $out .= '</div>';
224
225        return $out;
226    }
227
228    /**
229     * Create the link or option for a single translation
230     *
231     * @param $lc string      The language code
232     * @param $idpart string  The ID of the translated page
233     * @returns string        The item
234     */
235    function getTransItem($lc, $idpart) {
236        global $ID;
237        global $conf;
238
239        list($link,$lang) = $this->buildTransID($lc,$idpart);
240        $link = cleanID($link);
241
242
243        // class
244        if(page_exists($link,'',false)){
245            $class = 'wikilink1';
246        }else{
247            $class = 'wikilink2';
248        }
249
250        // local language name
251        if ($this->LN[$lang]){
252            $localname = $this->LN[$lang];
253        } else{
254            $localname = $lang;
255        }
256
257        // current?
258        if($ID == $link){
259            $sel    = ' selected="selected"';
260            $class .= ' cur';
261        }else{
262            $sel    = '';
263        }
264
265        // flag
266        if(isset($this->opts['flag'])){
267            $flag   = DOKU_BASE.'lib/plugins/translation/flags/'.hsc($lang).'.gif';
268            $style  = ' style="background-image: url(\''.$flag.'\')"';
269            $class .= ' flag';
270        }
271
272        // what to display as name
273        if(isset($this->opts['name'])){
274            $display = hsc($localname);
275            if(isset($this->opts['lc'])) $display .= ' ('.hsc($lang).')';
276        }elseif(isset($this->opts['lc'])){
277            $display = hsc($lang);
278        }else{
279            $display = '&nbsp;';
280        }
281
282        // prepare output
283        $out = '';
284        if($this->getConf('dropdown')){
285            $out .= '<option class="'.$class.'" title="'.hsc($localname).'" value="'.$link.'"'.$sel.$style.'>';
286            $out .= $display;
287            $out .= '</option>';
288        }else{
289            $out .= '<li><div class="li">';
290            $out .= '<a href='.wl($link).' class="'.$class.'" title="'.hsc($localname).'">';
291            if($flag) $out .= '<img src="'.$flag.'" alt="'.hsc($lang).'" height="11" />';
292            $out .= $display;
293            $out .= '</a>';
294            $out .= '</div></li>';
295        }
296
297        return $out;
298    }
299
300    /**
301     * Checks if the current page is a translation of a page
302     * in the default language. Displays a notice when it is
303     * older than the original page. Tries to lin to a diff
304     * with changes on the original since the translation
305     */
306    function checkage(){
307        global $ID;
308        global $INFO;
309        if(!$this->getConf('checkage')) return;
310        if(!$INFO['exists']) return;
311        $lng = $this->getLangPart($ID);
312        if($lng == $this->defaultlang) return;
313
314        $rx = '/^'.$this->tns.'(('.join('|',$this->trans).'):)?/';
315        $idpart = preg_replace($rx,'',$ID);
316
317        // compare modification times
318        list($orig,$name) = $this->buildTransID($this->defaultlang,$idpart);
319        $origfn = wikiFN($orig);
320        if($INFO['lastmod'] >= @filemtime($origfn) ) return;
321
322        // get revision from before translation
323        $orev = 0;
324        $revs = getRevisions($orig,0,100);
325        foreach($revs as $rev){
326            if($rev < $INFO['lastmod']){
327                $orev = $rev;
328                break;
329            }
330        }
331
332        // see if the found revision still exists
333        if($orev && !page_exists($orig,$orev)) $orev=0;
334
335        // build the message and display it
336        $orig = cleanID($orig);
337        $msg = sprintf($this->getLang('outdated'),wl($orig));
338        if($orev){
339            $msg .= sprintf(' '.$this->getLang('diff'),
340                    wl($orig,array('do'=>'diff','rev'=>$orev)));
341        }
342
343        echo '<div class="notify">'.$msg.'</div>';
344    }
345}
346