<?php
/*
*   parse lang file to get translation
*
*   get url in parameter or file
*
*   Return php hash or js string following Posh lang format 
*
*/
function posh_getMsgDatas ($file) {
    $res = getFile($file);
    if (isset($res['res']) && $res['res'] == 'nok') {
        return $res;
    }
    return buildMsgHash($res['dom']);
}   

/**
*   function : buildMsgHash
*   build php hash with messages from xml file
*   build js hash
**/
function buildMsgHash ($dom) {
    $namelist = $dom->getElementsByTagName("msg");
    $datas = array();
    $datas['js'] = "if (typeof(lang) == \"undefined\") { var lang=new Array;  }\n";
    foreach($namelist as $msg) {
        $value = $msg->firstChild->nodeValue;
        $name = $msg->getAttribute("name");
        $value = preg_replace('/"/','\"',$value);
        $value = preg_replace("/'/",'\'',$value);
        $value = preg_replace("/\r\n/",'\n',$value);
        $value = preg_replace("/\n/",'',$value);
        $datas['js'] .= 'lang["'.$name.'"]="'.$value.'"' .";\n";
        $datas['labels'][$name] = $value;
    }  
    $datas['js'] .= "\nif (typeof(lg) == \"undefined\") {  function lg(v_s,v_p) {var l_ret=lang[v_s],indef;if(v_p && l_ret){l_ret=l_ret.replace(\"\$\$\",v_p);}if (l_ret==indef)l_ret=v_s;return l_ret;}}\n";
    return $datas;
}



function getRSSDescription ($res) {
    $dom = $res['dom'];
    $desclist = $dom->getElementsByTagName("description");
    foreach ( $desclist as $desc ) {
        echo $desc->firstChild->nodeValue . "<br />\n";
        echo $desc->firstChild->nodeName . "<br />\n";
        echo $desc->nodeValue . "<br />\n";
    }
}

function getRSSTitle ($res) {
    $dom = $res['dom'];
    $list = $dom->getElementsByTagName("title");
    foreach ( $list as $elem ) {
        echo $elem->firstChild->nodeValue . "<br />\n";
        echo $elem->nodeValue . "<br />\n";

        echo $elem->firstChild->nodeName . "<br />\n";
    }
   
}


function getFile ($file) {
    $phpnumversion = phpversion();
    
    if (substr(PHP_VERSION_ID,0,1) == 4) {
        error_log('you are in php 4 ');
        return array();
    } else {
        $dom = new DomDocument();
        if (file_exists($file)) {
            $dom->load($file); 
        } else {
            $opts = array(
                    'http' => array(
                        'user_agent' => 'PHP Posh libxml agent',
                        )
                );
            $context = stream_context_create($opts);
            libxml_set_streams_context($context);
            if ( !@$dom->load($file) ) { 
                //error_log( $PHP_ERRORMSG );
                return array('res' => 'nok','msg' => "unknown file");
            }
        }
        return array('dom'=>$dom,'res' => 'ok');

    
    }
}



?>