<?php
/**
 * Translation2 Plugin
 *
 * @license    GPLv3 (http://www.gnu.org/licenses/gpl.html)
 * @link       http://www.dokuwiki.org/plugin:translation2
 * @author     Markus Birth <markus@birth-online.de>
 */

if(!defined('DOKU_INC')) die();
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');

class action_plugin_translation2 extends DokuWiki_Action_Plugin {

    /**
     * return some info
     */
    function getInfo(){
        return confToHash(dirname(__FILE__).'/INFO.txt');
    }

    /*
     * plugin should use this method to register its handlers with the dokuwiki's event controller
     */
    function register(&$controller) {
        $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, '_prepare');
        $controller->register_hook('JQUERY_READY', 'BEFORE', $this, '_addjs');
    }

    function _prepare(&$event, $param) {
        global $conf, $ID;
        $this->loadConfig();
        // Configuration

        // Autodetect all languages your dokuwiki installation supports
        $supportedLanguages = glob(DOKU_INC . 'inc/lang/*', GLOB_ONLYDIR);

        foreach ($supportedLanguages as $idx=>$lang) $supportedLanguages[$idx] = basename($lang);

        if (strlen(trim($this->getConf('languages'))) == 0) {
            $this->conf['languages'] = implode(',', $supportedLanguages);
        }

        // make sure, default lang is valid
        if (strpos($this->getConf('languages'), $this->getConf('default_language')) === false) $this->conf['default_language'] = trim(reset(explode(',', $this->getConf('languages'))));


        // TODO: Check whether this code still works!
        // Set default language to the user agent's most favorite one
        $browserLanguages = split(',', preg_replace('/(;q=\d+.\d+)/i', '', $_SERVER['HTTP_ACCEPT_LANGUAGE']));
        foreach ($browserLanguages as $blang) {
            if (strpos($this->getConf('languages'), $blang) !== false) {
                $conf['lang'] = $blang;
                break;
            }
        }

        // Check, if language is set by namespace and overwrite chosen language
        $lang = preg_replace('/^(..+?)[:\/].*/i', '$1', $ID);
        if (strpos($this->getConf('languages'), $lang) === false) $lang = preg_replace('/^(..+?)[:\/].*/i', '$1', $_REQUEST['ns']);
          else $conf['lang'] = $lang;

        // prepend default start page with language namespace, if this page already exists.
        //if (file_exists($conf['savedir'].'/pages/'.str_replace(':','/',$conf['lang'].':'.$conf['start']).'.txt')) $conf['start'] = $conf['lang'].':'.$conf['start'];
    }

    function _addjs(&$event, $param) {
        global $ID;
        $event->data[] = 'jQuery(\'DIV#bar__topleft\').append(\'' . $this->html_langswitcher() . '\');';

        if ($ID{2} == ':') {
            // translated page ~~> remove first youarehere()
            // TODO: Remove the "&raquo;" #text node from DOM (might not be in all templates!)
            $event->data[] = 'jQuery(\'DIV.breadcrumbs:first A:first\').remove();';
        }
    }

    function flagimg($lang) {
        // translate language-code to country-code (where the lang is mostly spoken/written)
        switch ($lang) {
            case 'da': $lang = 'dk'; break;  // Danish -> Denmark
            case 'el': $lang = 'gr'; break;  // Greek -> Greece
            case 'en': $lang = 'en-all'; break; // English -> combined GB/US flag
            case 'he': $lang = 'il'; break;  // Hebrew -> Israel
            case 'ja': $lang = 'jp'; break;  // Japanese -> Japan
            case 'ko': $lang = 'kr'; break;  // Korean -> Korea
            case 'ku': $lang = 'iq'; break;  // Kurdish -> Iraq
            case 'pt-br': $lang = 'br'; break;  // Braz. Portuguese -> Brazil
            case 'uk': $lang = 'ua'; break;  // Ukrainian -> Ukraine
            case 'zh': $lang = 'cn'; break;  // Simpl. Chinese -> China
            case 'zh-tw': $lang = 'tw'; break;  // Trad. Chinese -> Taiwan
            default: break;
        }
        $img = DOKU_BASE . 'lib/plugins/' . basename(dirname(__FILE__)) . '/flags/' . $lang . '.gif';
        return $img;
    }

    // assumes Flag icons (.gif) from http://www.famfamfam.com/lab/icons/flags/ in flags folder (rename us.gif or gb.gif to en-all.gif)
    function html_langswitcher() {
        global $ID, $conf;
        $result  = ' <div id="langswitcher" class="no">';
        $result .= '<ul style="list-style: none; display: inline;">';
        $languages = explode(',', $this->getConf('languages'));
        array_walk($languages, 'trim');
        foreach ($languages as $lang) {
            $thislang = ($conf['lang']==$lang);
            $newID    = (($lang!=$this->getConf('default_language'))?$lang.':':'') . (($ID{2}==':')?substr($ID, 3):$ID);
            $newFile  = wikiFN($newID);
            $img      = '<img src="' . $this->flagimg($lang) . '" alt="' . hsc($lang) . '" title="' . hsc($lang) . '" />';
            $class = '';
            if (!$thislang) {
                $class .= ' lang';
                if (file_exists($newFile)) $class .= ' translated';
            }
            $result .= '<li style="display: inline; padding: 2px;"' . ((!empty($class))?' class="'.trim($class).'"':'') . '>';
            if (!$thislang) {
                $result .= '<a href="' . wl($newID) . '">' . $img . '</a>';
            } else {
                $result .= $img;
            }
            $result .= '</li>';
        }
        $result .= '</ul>';
        $result .= '</div>';
        return $result;
    }
}