<?php
/**
 * Wxml Dialog Module URL
 *
 * $Id$
 *
 * @author gERD Schaufelberger <gerd@php-tools.net>
 * @package WB
 * @subpackage base
 */

WBClass::load('WBWxml_Dialog');

/**
 * Wxml Dialog Module URL
 *
 * Link
 *
 * @version 0.2.0
 * @package WB
 * @subpackage base
 */
class WBWxml_Dialog_Url extends WBWxml_Dialog
{
    /**
     * storage for URL
     * @var WBDictionary_URL
     */
    protected $dict;

    /**
     * extend constructor
     *
     *
     * Load parent constructor and initialize URL dictionary
     */
    public function __construct()
    {
        parent::__construct();
        $this->dict =   WBClass::create('WBDictionary_URL');
    }
    
    /**
     * Start dialog using default values
     * 
     */
    public function start()
    {
        $values =   array(
                        'text'  =>  trim($this->select),
                        'urlid' =>  urldecode($this->getAttribute('urlid')),
                        'title' =>  trim($this->value),
                        'url'   =>  urldecode($this->getAttribute('href')),
                        'class' =>  $this->getAttribute('class')
                    );

        // create URLid from URL/href
        if (empty($values['urlid']) && !empty($values['url'])) {
            $this->dict->addWord($values['url']);
            $values['urlid']    =   $this->dict->getId();
        }

        // load URL from dictionary
        if (!empty($values['urlid'])) {
            $this->dict->load($values['urlid']);
            $values['url']  =  $this->dict->getWord();
            $data           =   $this->dict->get();
            if ($data['protocol'] == 'self') {
                $values['url']  =   '[[PROTOCOL]]://[[SERVER]]'. $values['url'];
            }
        }        
        
        $this->submit($values);
    }

    /**
     * Form "Url" validated
     *
     * mangle "internal" URLs as such and generate HTML snippet to
     * past into editor
     *
     * @param patForms $forn
     * @param array $values
     * @return bool always true - display valid-template
     */
    protected function onUrlValid($forn, $values)
    {
        // add server for internal URLs
        if ($values['url'][0] == '/') {
            $values['url']  =   WBString::replaceSuperPlaceholders('[[PROTOCOL]]://[[SERVER]]' . $values['url']);
        }
        // $values['url']  =   $this->manglePathLang($values);

        $values['target']   =   '';
        if (!isset($values['class']) || empty($values['class'])) {
            $values['class']    =   '';
        }

        $this->dict->addWord($values['url']);
        $values['urlid']    =   $this->dict->getId();
        $data   =   $this->dict->get();

        switch ($data['protocol']) {
            case 'self':
                // add mimetype to class
                if (strncmp($data['path'], '[[SERVICE_FILE]]', 16) == 0) {
                    $obs    =   substr($data['path'], 16);
                    $obs    =   explode('/', $obs);
                    $obs    =   $obs[0];

                    $file   =   WBClass::create('WBVFS_File');
                    /** @var $file WBVFS_File */
                    $file   =   $file->loadByObscureId($obs);
                    if ($file->isOK()) {
                        $clazz  =   explode(' ', $values['class']);
                        if (!in_array($file->getMime(WBVFS_File::MIME_MAJOR), $clazz)) {
                            $clazz[]    =   $file->getMime(WBVFS_File::MIME_MAJOR);
                        }
                        if (!in_array($file->getMime(WBVFS_File::MIME_MINOR), $clazz)) {
                            $clazz[]    =   $file->getMime(WBVFS_File::MIME_MINOR);
                        }
                        if (!in_array('vfsfile', $clazz)) {
                            $clazz[]    =   'vfsfile';
                        }
                        $values['class']    =   implode(' ', $clazz);
                    }
                }
                break;

            case 'mailto':
                break;

            default:
                $values['target']   =   'target="_blank"';
                break;
        }

        $this->tmpl->addGlobalVars($values);
        return true;
    }

    /**
     * Strip language part from URLs path
     *
     * There is an optional feature manglepathlang that allows to remove
     * language from path before the URL will be added the dictionary. This
     * normalizes multi-language URLs.
     *
     * uses $value['manglepathlang']
     * changes $value['url']
     *
     * manglepathlang can be:
     * - "keep" leave everything as it is (default)
     * - "strip" strip every known path language
     * - "auto" like "strip", but only if language matches the current language
     *
     * Depending on form definition for this dialog, "manglepathlang" may be not
     * set at all.
     *
     * The path languages are defined in locale.xml
     *
     * @deprecated reconsider whether something like this is really necessary
     * @param array $values
     */
    private function manglePathLang($values)
    {
        $url    =   $values['url'];

        // this feature is totally optional
        if (!isset($values['manglepathlang'])) {
            return $url;
        }

        // never remove it
        if ('keep' == $values['manglepathlang']) {
            return $url;
        }

        // check locale config
        $conf   =   WBClass::create('WBConfig');
        $conf->load('locale');
        $pl     =   $conf->get('locale/languages/requestpath', array());

        // in case there are no path languages, nothing has to be done
        if (empty($pl)) {
            return $url;
        }
        $base   =   WBString::replaceSuperPlaceholders('[[PROTOCOL]]://[[SERVER]][[SELF_NO_LANG]]');

        $length =   strlen($base) + 3;
        foreach ($pl as $lang => $short) {

            // find path language in URL
            if (0 != strncmp($base . $short . '/', $values['url'], $length)) {
                continue;
            }
            $path   =   substr($url, $length);
            switch ($values['manglepathlang']) {

                // strip all languages
                case 'strip';
                    $url    =   $base . $path;
                    break;

                // strip current language
                case 'auto':
                    WBClass::load('patI18n');
                    if (patI18n::getLocale(patI18n::LOCALE_TYPE_LANG) == $lang) {
                        $url    =   $base . $path;
                    }
                    break;

                default:
                    break;
            }
            break;
        }
        return $url;
    }
}