<?php
/*
	Copyright (c) PORTANEO.

	This file is part of POSH (Portaneo Open Source Homepage) http://sourceforge.net/projects/posh/.

	POSH is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version

	POSH is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Posh.  If not, see <http://www.gnu.org/licenses/>.
*/
# !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é
// Functions used in widget creation interfaces


$pagename="includes/modules_tools.php";
//require_once('../includes/config.inc.php');
$folder="";
$not_access=1;
$isScript=true;
$isPortal=false;
$granted=__USERMODULE;

function Specialencode ($toencode) {
    $toencode = preg_replace(
                                   '/
                                   &
                                   /xmsi',
                                   '&amp;',
                                   $toencode);  
    return $toencode;
}
function Specialdecode ($todecode) {
    $todecode = preg_replace(
                                   '/
                                   &amp;
                                   /xmsi',
                                   '&',
                                    $todecode);  
    return  $todecode;                                       
}
/*! getParams

    /brief get xml params: userprefs
    
    all but content

*/
function getParams ($code) {
    $code = preg_replace('/<Content[^>]*>.*?<\/content>/xmsi','',$code);
    return $code;
}
/* 

    Get the different "content" tags of the widget
    
*/
function getContents($code) {
    $i=0;
    $generalContent=Array();
    preg_match_all("/
                        (<content[^>]*[^\/]>
                        .*?
                        <\/content>)
                   /xmsi",$code,$content); 
                   
    preg_match_all("/
                        (<content[^>]*\/>)
                   /xmsi",$code,$contentOther); 
    foreach($content[0] as $cle => $val)               
    {
        $generalContent[$i]=$val;
        $i++;
    }  
    foreach($contentOther[0] as $cle => $val)               
    {
        $generalContent[$i]=$val;
        $i++;
    }
    return $generalContent;    
}

function getHeaderContents ($code) {
    preg_match("/
                <\?xml[^>]*>
                 (.*?)
                    <content        
                   /xmsi",$code,$headers); 
    return $headers[1]; 
}

/**
    \name
    existsLang
    \brief
    Verify that the module is available for a specific language
     
    @param[in] $lang lang to check - $hashLang hash of the available languages 
    @param[out] true/false
**/
function existsLang($lang,$hashLang) 
{
    if (isset($hashLang[$lang])) {
        return true;
    }
    return false;  
}
/**
    \name
    getCacheFile
    \brief
    Get the cache file content
     
    @param[in] $hash widgetid,lang,format,view
    @param[out] string (file content)
 **/
function getCacheFile($hash)
{   
    $content = "";
    $hash['filename']=buildCacheFileName($hash);
    $filepath = '../cache/';
    $ext = ($hash["format"]=="M")?'.xml':'.html';
    $fullPath = $filepath.$hash['filename'].$ext;
    if (file_exists($fullPath)) {
        $fp=fopen($fullPath,"r");    
        while (!feof($fp)) { 
          $content .= fgets($fp, 4096);
        }
        fclose ($fp);
        return $content;
    }
    else {
        //create cache file
        return $content;
    }
    return "";
}
//TO DEPRECATE IN modules_updates_tools
/**
    \name
    createCacheFile
    \brief
    Create the cache file if not already existing
     
    @param[in] $hash filename,format,source,xmlmodule,view
    @param[out] 
**/
function createCacheFile($hash)
{   
    $hash['filename']=buildCacheFileName($hash);
    $filepath = '../cache/';
    $ext = '.html';
    $contentToWrite = $hash["source"];
    if ($hash["format"]=="M") {
        //$contentToWrite = $hash['xmlmodule'];
        $ext = '.xml';
    }
    $fullPath = $filepath.$hash['filename'].$ext;
    if (!file_exists($fullPath)) {
        $fp=fopen($fullPath,"w");
        fputs ($fp, $contentToWrite);     
        fclose ($fp);
         @chmod($fullPath, 0766);  
    }
}
function deleteCacheFile ($hash) {
    $hash['filename']=buildCacheFileName($hash);
    $filepath = '../cache/';
    $ext = '.html';
    $fullPath = $filepath.$hash['filename'].$ext;
    if ( file_exists($fullPath) ) {
        unlink( $fullPath );
    }
}

/**
    \name
    buildCacheFileName
    \brief
    Return the cache file name based on the parameters input
     
    @param[in] $hash widgetid,lang,format,view
    @param[out] MD5 filename
**/
function buildCacheFileName($fileHash)
{
    return md5(__KEY
              .$fileHash['widget_id']
              .$fileHash['lang']
              .$fileHash['format']
              .$fileHash['view']);
}

/**
    \name
    buildInternationalizedVersion
    \brief
    Replace the variables in the content by the translated labels
     
    @param[in] $hash labels and value, $content XML content
    @param[out] $iContent internationalized content 
**/
function buildInternationalizedVersion($labelsHash,$content)
{
    foreach ($labelsHash as $cle => $val) 
    {
        $nb=0;
        $regex = '__MSG_'.$cle.'__';
        $content = preg_replace("/$regex/xmsi",
                                            $val,
                                            $content
                                            
                                     );                          
    }    
    return $content;
}
/** 
    \name
    ParseCodeLocale
    \brief
    Get the msg names and value in the XML
     
    @param[in] $xmlCode XML to parse
    @param[out] Hash[name]=value  
**/
function ParseCodeLocale($xmlCode, $default_labelsHash = null,$dom = null)
{
    $tabMsg=array();
    if (isset($dom)) {
        //if dom and if php > 4
        $ret=buildMsgHash($dom);
        $tabMsg = $ret['labels'];
        while (list($c, $v) = each($tabMsg)) {
            $tabMsg[$c] = preg_replace('/^(\r\n|\r|\n)/xmsi','', $v);
            $tabMsg[$c] = preg_replace('/^(\r\n|\r|\n)$/xmsi','', $v);
            $tabMsg[$c] = preg_replace('/\]\]>/xmsi',"",$v);
            $tabMsg[$c] = preg_replace('/<!\[CDATA\[/xmsi',"",$v);
            $tabMsg[$c] = preg_replace('/(\r\n|\r|\n)/xmsi',' ', $v);
            $tabMsg[$c] = preg_replace('/\'/xmsi',"\\\'", $v);
            if ( !is_utf8($v)) {
                $v = utf8_encode($v);
            }
        }
    } else {
        preg_match_all('
                    /
                    <msg\s+                
                        name="([^"]*)"
                        [^>]*
                        >(.*?)<\/msg>
                    /xsmi',$xmlCode,$msg,PREG_SET_ORDER);    
           
        foreach ($msg as $cle => $val) 
        {
            $val2 = $val[2];
            $val2 = preg_replace('/^(\r\n|\r|\n)/xmsi',"",$val2);
            $val2 = preg_replace('/(\r\n|\r|\n)$/xmsi',"",$val2);
            //$val2 = preg_replace("/(\r\n|\r|\n)/xmsi","",$val2);
            $val2 = preg_replace('/\]\]>/xmsi',"",$val2);
            $val2 = preg_replace('/<!\[CDATA\[/xmsi',"",$val2);
            $val2 = preg_replace("/(\\r\\n|\\r|\\n)/xmsi"," ",$val2);            
            $val2 = preg_replace('/\'/xmsi',"\\\'", $val2);
           if ( !is_utf8($val2)) {
                $val2 = utf8_encode($val2);
            }
            $tabMsg[$val[1]]=$val2;     
        }
    }
    if ($default_labelsHash!=null)  {
        foreach ( $default_labelsHash as $label => $value) {
            if (!isset($tabMsg[$label])) {
                $tabMsg[$label] = $value;

            }
        }
    }
    return $tabMsg;
}
/** 
     \name
     getAllViews
     \brief
     Get all the different views specified in the XML
     
    @param[in] $content XML content tags
    @param[out] String all views   
**/
function getAllViews($content) {
    $allviews='home';
    $multiviews=array();
    
    foreach ($content as $indice => $parameters)
    {
        preg_match('/
                            view="([^"]+)"
                    /xmsi',$parameters,$ct_view);      
        
        if(count($ct_view)>0) {  
            if (strpos($ct_view[1], ',') !== false) {
                $tmpViews = explode(",", $ct_view[1]);
                for ($j=0;$j<count($tmpViews);$j++) {
                    if ($tmpViews[$j]=="default" || $tmpViews[$j]=="profile") {
                        $tmpViews[$j]="home";
                    }
                    if (!in_array($tmpViews[$j], $multiviews)) {
                        array_push($multiviews,$tmpViews[$j]);
                    }
                } 
            } 
            else {
                if ($ct_view[1]=="default" || $ct_view[1]=="profile")
                $ct_view[1]="home";
                array_push($multiviews, $ct_view[1]);
            }
        }

        for($i=0;$i<count($multiviews);$i++)
        {
            if (strpos($allviews, $multiviews[$i]) === false) {
                $allviews.=",".$multiviews[$i];
            }  
        }
    } 
    return $allviews;
}   


/**

    Insert some widget informations in temp_dir_item_external
    
**/
function insertInTempDirItemExternal($contents,$id,$format,$code,$idModuleValidated,$queryType,$DB)
{
    global $tutorial_setTemp_Dir_Item_External,
    $tutorial_UpdateTemp_Dir_Item_External,
    $tutorial_getNbViews,
    $tutorial_getItemViews,
    $tutorial_DeleteTemp_Dir_Item_ExternalView,
    $external_source;
    $external_source='';
    $external_xmlmodule='';
    $oldViews=array();
    $currentViews=array();
    $contentsByView = array();
    $contentsComplementaryInfos = array();
    $sizable = isset($_POST['sizable']) ? $_POST['sizable'] : 1;
    $adjustframeheight = ' onload="_IG_AdjustIFrameHeight();"';
    if ($sizable == 2 || $sizable == 3) {
        $adjustframeheight = '';
    }
    $basename = "";
    $localfolder = "..";
    if (  preg_match( '/author_affiliation="Google\s[^"]*"/xmsi',$code)) {
        $basename = '<base href="http://www.google.com/" />';
        $localfolder = __LOCALFOLDER;
    }
    if ($queryType==1) {
        $DB->getResults($tutorial_getItemViews,$id);
        $row = $DB->fetch(0);
        $view = $row['view'];
        $oldViews = explode(",", $view);
    }
    if ($queryType==2) {
        $DB->getResults($tutorial_getNbViews,$id);
        while ($row = $DB->fetch(0)) {
            array_push($oldViews,$row['view']);
        }
    }
    foreach ($contents as $indice => $parameters)    
    {
        $external_itemid=$id;
        $external_xmlmodule='';
        $external_url='';
        $external_view='';
        $external_type='';
        $external_source='';
        $multiviews=array();
        //<script type="text/javascript" src="$localfolder/includes/modules.js"></script>
        $htmlcode = 
        <<<EOT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
$basename
<title>Widget</title>
<link rel="stylesheet" type="text/css" media="screen" title="default" href="$localfolder/styles/module.css" />
<link rel="stylesheet" type="text/css" media="screen" title="default" href="$localfolder/styles/module1.css" />
<script type="text/javascript" src="$localfolder/includes/modules.js"></script>
__ADDITIONAL_LIB_
<script type="text/javascript">
</script>
</head>
<body $adjustframeheight>
__INSCRIPT_CONTENT_
</body>
</html>
EOT;

        // Get contents types
        preg_match('/
                          type="([^"]+)"
                    /xmsi',$parameters,$c_type);

        $external_type=$c_type[1];
        if ($external_type=="url") {
            $external_xmlmodule=$code;  
            $external_type="U";
            // Get content href
            preg_match('/
                            href="([^"]+)"
                       /xmsi',$parameters,$c_href);  
            $external_url=$c_href[1];    
           
		   	if(substr($external_url,0,3)=="../") {
				$external_url = str_replace("../", "", $external_url);
				$external_url=__LOCALFOLDER.$external_url;

			}
			elseif (substr($external_url,0,7)!="http://") {
               $external_url="http://".$external_url;
            }
        }
        elseif ($external_type=="html") {
            $external_type="I";
            //Get the xmlsource
            preg_match_all("/
                                <content[^>]*>(.+?)<\/content>
                            /xmsi",$parameters,$c_source); 
                            
            if ($format=="M") {
                    $external_xmlmodule=$code;
            }
            //if ($format=="I" || $format=="G") {
            if ($format=="I") {
                $external_xmlmodule=$code;
                foreach ($c_source as $all => $ct_content)
                {
                    $tmp_external_source=$ct_content[0];
                    $tmp_external_source = str_replace("<![CDATA[", "", $tmp_external_source);
                    $tmp_external_source = str_replace("]]>", "", $tmp_external_source);
                    if(!strpos($tmp_external_source,"builtin module")===false) {
                        $tmp_external_source=utf8_decode(lg("internalGoogleWidgetMsg"));
                    }

                    $external_source = Specialdecode($tmp_external_source);        
                    $external_source = preg_replace('/__INSCRIPT_CONTENT_/',$tmp_external_source,$htmlcode);
                    
                    launch_hook('tutorial_loadOpensocialJs');     
                    
                    $external_source = preg_replace('/__ADDITIONAL_LIB_/','',$external_source);   
                }
            }
        }     
        // Get content view
        preg_match('/
                        view="([^"]+)"
                    /xmsi',$parameters,$c_view);  

        if(count($c_view)>0) {
            if (strpos($c_view[1], ',') !== false) {
                $tmpViews = explode(",", $c_view[1]);
                for ($j=0;$j<count($tmpViews);$j++) {
                    if ($tmpViews[$j]=="default" || $tmpViews[$j]=="profile") {
                        $tmpViews[$j]="home";
                    }
                    if (!in_array($tmpViews[$j], $multiviews)) {
                        array_push($multiviews,$tmpViews[$j]);
                    }
                }
            } 
            else {
                if ($c_view[1]=="default" || $c_view[1]=="profile") {
					$c_view[1]="home";
				}
                //array_push($multiviews, $c_view[1]);
                array_push($multiviews, $c_view[1]);
                array_push($currentViews, $c_view[1]);
            }
        }
        else {
            array_push($multiviews, "home");
            array_push($currentViews, "home");
        }
        
        $external_source2save = $external_source;
        $external_xmlmodule2save = $external_xmlmodule;
    
        if ( get_magic_quotes_gpc() && get_magic_quotes_gpc() == 1 ) { 
            $external_xmlmodule2save = preg_replace('!\\"!','\\\\"',$external_xmlmodule2save);
            $external_xmlmodule2save = preg_replace("!\\'!","\\\\'",$external_xmlmodule2save);
            $external_xmlmodule2save = preg_replace("!\\/!","\\\\/",$external_xmlmodule2save);  
            
            $external_source2save = preg_replace("!\\'!","\\\\'",$external_source2save);
            $external_source2save = preg_replace('!\\"!','\\\\"',$external_source2save);    
            $external_source2save = preg_replace("!\\/!","\\\\/",$external_source2save); 
        }

        for($i=0;$i<count($multiviews);$i++)
        {
            
            $external_view=$multiviews[$i];
            if ($queryType==1) {
                $res = $DB->execute($tutorial_setTemp_Dir_Item_External,
                                        $DB->escape($external_itemid),
                                         $DB->quote($external_source2save),
                                         $DB->quote($external_xmlmodule2save),
                                         $DB->quote(preg_replace('/&amp;/','&',$external_url)),
                                         $DB->quote($external_view),
                                         $DB->quote($external_type),
                                         $DB->escape($idModuleValidated)
                                    );       
            }
            else {
                $res = $DB->execute($tutorial_UpdateTemp_Dir_Item_External,
                                        $DB->quote($external_source2save),
                                        $DB->quote($external_xmlmodule2save),
                                        $DB->quote(preg_replace('/&amp;/','&',$external_url)),
                                        $DB->quote($external_type),
                                        $DB->escape($external_itemid),
                                        $DB->quote($external_view)
                                    );                                                 
           }
           $contentsByView[$external_view]=$external_source;
           $contentsComplementaryInfos[$external_view]['url']=$external_url;
           $contentsComplementaryInfos[$external_view]['type']=$external_type; 
        }             
    }


    
    return array($external_source,$external_xmlmodule,$contentsByView,$contentsComplementaryInfos);
}
/**
    \name getUrlLocales
    
    \brief get xmlcode, and get url locales if they exist
    
    @param[in] <xml code>, order,void array  reference to set errors
         
    @param[out]  true/false
    
    errors[0] == 401 //xml missing
    erros[0] == 402 //bad xml ou locale missing

    \details
    
    get datas, but if xml is not in normal order, get datas in other order
    
    $errors = array();  
    $lang_hash = getUrlLocales($xml,1,$errors);
    if ($errors[0] == 403) {
        $errors = array();
        $lang_hash = getUrlLocales($xml,2,$errors);
    }
    
**/
function getUrlLocales ($xml,$order,&$errors) {
    if (!$xml) {
        $errors[0] = 404;
        $errors[1] = "xml missing";
        return false;
    }
    $lang_hash = array();
    
    //control that one of the Locales syntax are correct
    preg_match_all('/
                        <Locale(.+?)>
                    /xmsi',$xml,$locales);  
          
    if (isset($locales[0])) { 
        
        $lang_temp = array();
        foreach($locales[0] as $cle => $val)               
        {
            preg_match_all('/
                        (\S+)="([^"]+)"
                            /xmsi',$val,$results,PREG_SET_ORDER); 
            foreach ($results as $indice => $res) {
                $param = $res[1];
                $value = $res[2];
                $lang_temp[$cle][$param] = $value;
            }
        }
        foreach ($lang_temp as $c => $array) {
            if (isset($array['lang'])) {
               $lang = $array['lang'];
               /*
               if (isset($array['country'])) {
                    $lang = "$lang-".$array['country'];
               }
               */
               $lang_hash[$lang] = $array['messages'];
            } else {
                $lang_hash['en'] = $array['messages'];
                $lang_hash['default'] = $array['messages']; 
            }
        }
        return $lang_hash;
    } else {
        $errors[0] = 402;
        $errors[1] = "locales missing or bad xml ";        
        return $lang_hash;
    }

}

/*
    \brief setGoogleDomain
       
       For Google Widget url may be relative
       
       return absolute path

*/
function setGoogleDomain ($url,$require_hash) {
    if (isset($require_hash['internal-domain'])) {
        return $url;
    } 
    $googleDomain = 'http://www.google.com/ig/';
    $url2 = strtolower($url);
    if (strpos($url2,"http")===false) {
        if ( preg_match('/^\//',$url2)) {
            $googleDomain = 'http://www.google.com/';
            return "$googleDomain$url";
        } else {
            $googleDomain = 'http://www.google.com/ig/';
            return "$googleDomain$url";        
        }
    } else {
        return $url;
    }
    
}

/**
    \brief savel10nInfo
    
    save l10n info in database : table dir_item
    
    @param[in]    $lang_hash , $id_item,
    
     /brief 
     
        savel10nInfo($lang_hash,118);
        
        /see 
        
        getUrlLocales to get  $lang_hash
    
*/
function savel10nInfo ($lang_hash,$id,$DB) {
    $langs="";
    global $tutorial_updatel10n;
    
    foreach ($lang_hash as $lang => $url) {
        $langs .= "$lang,";
    }
    $langs = rtrim($langs,",");
    $DB->execute(
            $tutorial_updatel10n,
            $DB->quote($langs),
            $id
        );         
}

/*

    \brief getLangFile
    
    @param[in] $lang_hash, $lang,&$errors
    
    @param[out] content of xml page 
    
    \see
    
      getUrlLocales to get  $lang_hash

*/
function getLangFile ($lang_hash,$lang,&$errors,$require_hash,&$dom) {
    $url = $lang_hash[$lang];
    //get file in internal domain
    $content = '';
    if(!defined('PHP_VERSION_ID'))
    {
        $version = PHP_VERSION;
        define('PHP_VERSION_ID', ($version{0} * 10000 + $version{2} * 100 + $version{4}));
    }
    if (isset($require_hash['internal-domain'])) {
        if (substr(PHP_VERSION_ID,0,1) > 4 && $dom) {
            //get dom if php > 4
            $ret = getFile($url);
            $content = $dom->saveXML();
            $dom = $ret['dom']; 
            return $content;
        } else {
            //use only file if php < 4
            $langfile=new file($url);
            return $langfile->read();
        }
    } else {
        if (substr(PHP_VERSION_ID,0,1) > 4 && $dom) {
            $ret = getFile($url);
            if (isset(  $ret['dom'] )) {
                $dom = $ret['dom'];
                $content = $dom->saveXML();
            }
        } else {
            $h = new http($url);
            $content = $h->get(); 
            if ($h->code) {
                $errors['code'] = $h->code;
            }    
        }
    }
    return $content;
}

/**
    \brief saveInternationalizedContent
    
    @param[in] $datas (hash)
    
    \description hash parameters
    
        array(
                                       'widget_id' => 12,
                                       'lang'   => 'fr',
                                       'url'    => '',
                                        'source' => $l10n_content,
                                        'view'  => 'home',
                                        'viewtype' => 'I'
                                       )
    

**/

function saveInternationalizedContent ($datas) {
    global $tutorial_insertTempL10NSource;
    $item_id = $datas['widget_id'];
    $lang = $datas['lang'];
    $source = $datas['source'];
    $url = $datas['url'];
    $view = $datas['view'];
    $viewtype = $datas['viewtype'];
    $params = $datas['params'];
    $DB = $datas['db'];
    
    //item_id,lang,url,source,view,viewtype,last_updated
    if ( get_magic_quotes_gpc() && get_magic_quotes_gpc() == 1 ) { 
        $source = preg_replace('!\\"!','\\\\"',$source);    
        $source = preg_replace("!\\'!","\\\\'",$source);
        $source = preg_replace("!\\/!","\\\\/",$source); 
    
        $params = preg_replace('!\\"!','\\\\"',$params);    
        $params = preg_replace("!\\'!","\\\\'",$params); 
        $params = preg_replace("!\\/!","\\\\/",$params);
    }
    $isOk = $DB->execute(
                   $tutorial_insertTempL10NSource,
                   $item_id,
                   $DB->quote($lang),
                   $DB->quote($url),
                   $DB->quote($source),
                   $DB->quote($view),
                   $DB->quote($viewtype),
                   $DB->quote($params)
                );

    return $isOk;
}

function updateInternationalizedContent ($datas) {
    global $tutorial_updateTempL10NSource;
    $item_id = $datas['widget_id'];
    $lang = $datas['lang'];
    $source = $datas['source'];
    $url = $datas['url'];
    $view = $datas['view'];
    $viewtype = $datas['viewtype'];
    $params = $datas['params'];
    $DB = $datas['db'];
   // $source = utf8_encode($source);
    //item_id,lang,url,source,view,viewtype,last_updated                         
    if ( get_magic_quotes_gpc() && get_magic_quotes_gpc() == 1 ) { 
        $source = preg_replace('!\\"!','\\\\"',$source);    
        $source = preg_replace("!\\'!","\\\\'",$source);  
        $source = preg_replace("!\\/!","\\\\/",$source); 
    
        $params = preg_replace('!\\"!','\\\\"',$params);    
        $params = preg_replace("!\\'!","\\\\'",$params); 
        $params = preg_replace("!\\/!","\\\\/",$params);
    }
    $isOk = $DB->execute(
                   $tutorial_updateTempL10NSource,
                   $DB->quote($source),
                   $DB->quote($params),
                   $DB->quote($viewtype),
                  $item_id,
                  $DB->quote($view),
                  $DB->quote($lang)
                );
    
    return $isOk;
}


/*

    \name saveSourceXMLCode
    
    \brief  save 

**/

function saveSourceXMLCode () {

}

/**

    \brief getInternationalizedSource
    
    @param[in] $datas hash
    
                        array(
                                       'widget_id' => 12,
                                       'lang'   => 'fr',
                                        'view'  => 'home'
                                       )

    @param[out] $datas hash
    
                        array(
                                       'source' => '<? xml ?>' or '<html>'
                                       'url'   => '' or 'http://www.google.fr'
                                        'viewtype'  => 'I' 'U'
                                       )

**/

function getInternationalizedSource ($datas) {
    global $tutorial_getL10NSource,$tutorial_getTempL10NSource;
    $item_id = $datas['widget_id'];
    $lang = $datas['lang'];
    $view = $datas['view'];
    $DB = $datas['db'];
    $widgetInfos = array();
    $source='';
    $widgetInfos["source"]="";
    $widgetInfos["viewtype"]="I";
    $widgetInfos["url"]="";
    $DB->getResults(
               $tutorial_getTempL10NSource,
               $item_id,
               $DB->quote($lang),
               $DB->quote($view)
            );   
    if ($DB->nbResults()==0) {
        $DB->freeResults();
        $DB->getResults($tutorial_getL10NSource,
           $item_id,
           $DB->quote($lang),
           $DB->quote($view)
        );         
    }     
    if ($DB->nbResults() > 0 ) {
        $row=$DB->fetch(0);
        $source= $row['source'];
        $type= $row['viewtype'];
        $url= $row['url'];
        $widgetInfos["source"]=$source;
        $widgetInfos["viewtype"]=$type;
        $widgetInfos["url"]=$url;
    }
    $DB->freeResults();

    return $widgetInfos;
}
/**

    \brief getContentType
    
    Return the content 'type'
    
    @param[in] $parameters string

    @param[out] $c_type[1];  string ('url'/'html')

**/
function getContentType($parameters)
{
    preg_match('/
                      type="([^"]+)"
                /xmsi',$parameters,$c_type);   
    return $c_type[1];     
}
/**

    \brief getContentUrlParam
    
    Return the content 'href' parameter for a content type 'url'
    
    @param[in] $parameters string

    @param[out] $c_href[1];  string (www.website.com, http://www.website.com etc..)

**/
function getContentUrlParam($parameters) 
{

    preg_match('/
                    href="([^"]+)"
               /xmsi',$parameters,$c_href);       
    if (substr($c_href[1],0,7)!="http://") {
       $c_href[1]="http://".$c_href[1];
    }
    return $c_href[1];
}
/**

    \brief getContentViewParam
    
    Return the content 'view' parameter
    
    @param[in] $parameters string

    @param[out] $c_href[1];  string (default 'home')

**/
function getContentViewParam($parameters)
{
    $view='home';

    preg_match('/
                    view="([^"]+)"
                /xmsi',$parameters,$c_view);  
    if(count($c_view)>0) {
        $view = $c_view[1];
    }
    return $view;
}
/*
    /brief save title and desc in default portal language in dir_tem 

    __MSG_gadgetTitle__
    
*/
function updateL10nTitle ($lang,$labelsHash,$prefs_hash,$id,$DB) {
    global $__AVLANGS,$tutorial_updateTitle;
    if (isset($prefs_hash['title'])) { $label_title = preg_replace('/__MSG_(.+)__/','\1',$prefs_hash['title']); }
    if (isset($prefs_hash['description'])) { $label_desc = preg_replace('/__MSG_(.+)__/','\1',$prefs_hash['description']); }
    $title = $label_title;
    $desc = $label_desc;    
    
    $defaultlang = $__AVLANGS[0];
    if ($defaultlang != $lang ) {
        return;
    }
    if (  isset($labelsHash[$label_title]) ) {
        $title = $labelsHash[$label_title];
    }
    if (  isset($labelsHash[$label_desc]) ) {
        $desc = $labelsHash[$label_desc];
    }
    
    $desc = utf8_encode($desc);
    $title = utf8_encode($title);
    $res  = $DB->execute(
                $tutorial_updateTitle,
                    $DB->quote($title),
                    $DB->quote($desc),
                    $DB->escape($id)
            );
}
/**
*
*   \function getModulesPrefAttributes
*           get attributes in ModulePrefs
*
*  @param   $xml xml string 
*
*   @return $prefs_hash hash with an entry for each attribute
*
**/
function getModulesPrefAttributes ($xml) {
    
    if ($xml=='') return "";
    preg_match_all(
                    '/
                    <ModulePrefs\s+
                        ([^>]+)
                        >
                    /xmsi',
                    $xml,
                    $array,
                    PREG_SET_ORDER
                    );
    $prefs = $array[0][1];
 
    preg_match_all(
                    '/
                    (\S+)="([^"]+)"
                    /xmsi',
                    $prefs,$array_pref,
                    PREG_SET_ORDER
                    );
    $prefs_hash=array();
    foreach ( $array_pref as $c ) {
        $prefs_hash[  $c[1] ]  = $c[2];
    }
    
    return $prefs_hash;
}
/*! getRequireParams

    get Require from xml params
*/
function getRequireParams ($xml) {
    if ($xml=='') return "";
    $require_hash = array();
    preg_match_all(
                    '/
                    <Require[^<]+feature="([^"]+)"[^>]*\/>
                    /xmsi',
                    $xml,
                    $array,
                    PREG_PATTERN_ORDER
                    );    
    foreach ($array[1] as $c => $require) {
        $require_hash[$require] = 1;
    }
    return $require_hash;
}
/*!  savel10nContent

    @parameters[in] hash
    
    \brief hash
        
    $errors = array();
    $lang_hash = getUrlLocales($external_xmlmodule,1,$errors);
    if ( !isset($errors[0]) ) {
        savel10nContent( array(
                            'lang_hash'             => $lang_hash,
                            'id'                    => $id,
                            'l10nSelected'          => $l10nSelected,
                            'external_source'       => $external_source,
                            'external_xmlmodule'    => $external_xmlmodule,
                            'l10n_content'          => $l10n_content,
                            'format'                => $format,
                            'prefs_hash'            => $prefs_hash
                            )
                        );
    }
*/
function savel10nContent ($datas) {
        $lang_hash  = $datas['lang_hash'];
        $id         = $datas['id'];
        $l10nSelected = $datas['l10nSelected'];
        $external_source        = $datas['external_source'];
        $external_xmlmodule     = $datas['external_xmlmodule'];
        //$l10n_content           = $datas['l10n_content'];
        $format                 = $datas['format'];
        $prefs_hash             = $datas['prefs_hash']; 
        $action                 = $datas['action'];
        $contentsByView         = $datas['contentsByView'];
        $complementaryInfos     = $datas['complementaryInfos'];
        $require_hash           = $datas['require_hash'];
        $DB                     = $datas['db'];
        $params_array_returned = array();

        savel10nInfo($lang_hash,$id,$DB);
        $errors = array();        
        //must get default hash
        $defaulturl = (isset($lang_hash['default']))?$lang_hash['default']:'';
        $content_default_langfile='';
        $default_labelsHash = '';
        $dom = null;
        if ($defaulturl!='') {
            $lang_hash['default'] = setGoogleDomain($lang_hash['default'],$require_hash);
            $content_default_langfile = getLangFile($lang_hash,'default',$errors,$require_hash,$dom);    
            $default_labelsHash = ParseCodeLocale($content_default_langfile,null,$dom);
        }
        $params = getParams($external_xmlmodule);
        $errors = array();

        foreach ($l10nSelected as $c) {
            if (isset($lang_hash[$c])) {
                $lang_hash[$c] = setGoogleDomain($lang_hash[$c],$require_hash);
                $content_langfile = getLangFile($lang_hash,$c,$errors,$require_hash,$dom);
                $labelsHash = ParseCodeLocale($content_langfile , $default_labelsHash,$dom );
                updateL10nTitle($c,$labelsHash,$prefs_hash,$id,$DB);
                foreach  ($contentsByView as $view => $content) {
                    $l10n_params = buildInternationalizedVersion($labelsHash,$params);
                    $params_array_returned[$c] = $l10n_params;
                    $l10n_content = buildInternationalizedVersion($labelsHash,$content);
                    //must get if lang is already saved or not
                    if ($action == 'insert') {
                        saveInternationalizedContent(array(
                                           'widget_id' => $id,
                                           'lang'   => $c,
                                           'url'    => $complementaryInfos[$view]['url'],
                                           'source' => $l10n_content,
                                           'view'  => $view,
                                           'viewtype' => $complementaryInfos[$view]['type'],
                                           'params'   => $l10n_params,
                                           'db'       => $DB
                                           ));
                    } else {
                         updateInternationalizedContent(array(
                                           'widget_id' => $id,
                                           'lang'   => $c,
                                           'url'    => $complementaryInfos[$view]['url'],
                                           'source' => $l10n_content,
                                           'view'  => $view,
                                           'viewtype' => $complementaryInfos[$view]['type'],
                                           'params'   => $l10n_params,
                                           'db'       => $DB
                                           ));               
                    }
                }
            }
        }
        return $params_array_returned;
}

/*! createParamXMLFile

*/

function createParamXMLFile ($id,$params_array,$code) {
        global $__AVLANGS;
        if (isset( $params_array[$__AVLANGS[0]] )) {
            $modulecode=$params_array[$__AVLANGS[0]];
        }
        if (!isset($modulecode)) {
            $modulecode = preg_replace("/
                            <content[^>]+>
                            .*?
                            <\/content>
                                /xmsi","",$code);                
        } 
       
        $modulecode = preg_replace("/&/xmsi","&amp;",$modulecode);        

        $paramfile=new file("../modules/tmp_module".$id."_param.xml");
        $paramfile->write($modulecode);
        @chmod("../modules/tmp_module".$id."_param.xml", 0766);
        
        foreach ( $__AVLANGS as $lang) {            
            if ( isset($params_array[$lang]) ) {
                $filename = "../modules/tmp_module".$id."_".$lang."_param.xml";
                $paramfile=new file($filename);
                $paramfile->write($params_array[$lang]);
                @chmod($filename, 0766);                
            }
            
        }
}

/*! rewriteUrl

    /brief
    
        rewrite url of url format widget to add variables 

*/
function rewriteUrl ($url) {
    return replaceUP($url,'url');
}

function replaceUPVars ($content) {
    return replaceUP($content,'content');
}

function replaceUP ($data,$type) {
                foreach ($_GET as $c => $v) {
                    if ( $c == 'getCacheFile'   ||
                        $c == 'format'   ||
                        $c == 'pitem'   ||
                        $c == 'pid'   ||
                        $c == 'prof'   ||
                        $c == 'p'   ||                        
                        $c == 'view'   ||
                        $c == 'getsource'   ||
                        $c == 'l10n' 
                        
                    ) {
                        continue;
                    } else {
                        $regex = '__UP_'.$c.'__';
                        $regex = '__UP_'.$c.'__';
                        $data = preg_replace("/
                                    $regex
                                    /xmsi",
                                        $v,
                                        $data
                                        );
                    }
                }
    return $data;
}

function replaceModuleJSVars ($content,$p_prof,$p_tab) {
    $content = preg_replace(
                                '/__MODULE_ID__/xmsi',
                                $p_tab,
                                $content);  
  //  $content = str_replace("\'", "'", $content);                            
    return $content;
}
/*
    function to save widget from xml only

*/

/*
    addNewModule
    
    \brief add new widget without validation step

        
    
    @param hash ref
    
    must contains datas below to save without validation
    $datas['widget']['validated'] = 1;
    
    category and iconid must be defined in or out of xml file
    
    \sample
    
    $poshdom = new PoshTutorialDom();
    $ret = $poshdom->getFile($xmlfile);

    $datas = array();
    $datas['DB'] = $DB;

    $poshdom->getModulesPrefs($datas);
    $poshdom->getUserPrefs($datas);
    $poshdom->getContent($datas);

    $datas['widget']['validated_id'] = 0;
    $datas['widget']['xmlcontent'] = $poshdom->saveXML();
    $datas['widget']['quotes'] = 'NO'; ### don't quotes datas
    $datas['widget']['lang'] = __LANG;
    $datas['widget']['validated'] = 1;  

    addnewModule($datas);
    setBaseName($datas);
    saveContents($datas);
    addWidgetInDirCat($datas);    
    
*/

function addNewModule (&$datas) {
    $DB = $datas['DB'];
    global $tutorial_insertNewModule;
    $url = getWidgetUrl($datas,$datas['widget']['contents']['home']['type'],
                                $datas['widget']['contents']['home']['href'] );
    $defvar =  isset($datas['widget']['defvar']) ?  $datas['widget']['defvar'] : '';
    $datas['widget']['url'] = $url;
    $name = $datas['widget']['title'];
    $desc = $datas['widget']['description'];
    $status = isset($datas['widget']['status']) ? $datas['widget']['status'] :'N';
    //$format = $datas['widget']['contents']['home']['type'];
    $format = $datas['widget']['format'];
    $height = isset($datas['widget']['status']) ? $datas['widget']['height'] :300;
    $minwidth = isset($datas['widget']['minwidth']) ? $datas['widget']['minwidth'] :150;
    $sizable = isset($datas['widget']['sizable']) ? $datas['widget']['sizable'] :1;
    $website = isset($datas['widget']['website']) ? $datas['widget']['website'] :'';
    $editor_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] :1;
    $nbvariables = isset($datas['widget']['nbvariables']) ? $datas['widget']['nbvariables'] : 0;
    $lang = isset($datas['widget']['lang']) ? $datas['widget']['lang'] : 'en';
    $iconid = isset($datas['widget']['iconid']) ? $datas['widget']['iconid'] : '';
    $keyword = isset($datas['widget']['keyword']) ? $datas['widget']['keyword'] : '';
    $keywords = isset($datas['widget']['keywords']) ? $datas['widget']['keywords'] : '';
    $autorefresh = isset($datas['widget']['autorefresh']) ? $datas['widget']['autorefresh'] : 0;
    $views = isset($datas['widget']['views']) ? $datas['widget']['views'] : 'home';
    $icon = buildIconPath($iconid);
    $l10n = '';
    $DB->execute($tutorial_insertNewModule,
                $DB->quote(   $DB->escape( $url ) ),
                $DB->noHTML(htmlspecialchars($name,ENT_QUOTES,'UTF-8')),
                $DB->noHTML(htmlspecialchars($desc,ENT_QUOTES,'UTF-8')),           
                $DB->quote($DB->escape( $defvar ) ),
                
                $DB->escape($height),                
                $DB->quote($DB->escape($format) ),
                $DB->escape($minwidth),
                
                $DB->escape($sizable),
                $DB->quote($DB->escape($website)),
                $DB->escape($editor_id ),
                $DB->escape($nbvariables),
                
                $DB->quote($lang),
                0,
                $DB->escape($autorefresh ),
                $DB->quote($views),
                $DB->quote($icon),
                $DB->quote($l10n)
        );
    $id=$DB->getId();
    $datas['widget']['id'] = $id;
}

/*
    addnewTempModule
    
    \brief add widget in tmp table before validation
    
    @param hash ref
   
        must NOT contain datas below to save without validation
        $datas['widget']['validated'] = 0;   
        
        category and iconid must be defined in or out of xml file
    \sample
    
    $poshdom = new PoshTutorialDom();
    $ret = $poshdom->getFile($xmlfile);

    $datas = array();
    $datas['DB'] = $DB;

    $poshdom->getModulesPrefs($datas);
    $poshdom->getUserPrefs($datas);
    $poshdom->getContent($datas);

    $datas['widget']['validated_id'] = 0;
    $datas['widget']['xmlcontent'] = $poshdom->saveXML();
    $datas['widget']['quotes'] = 'NO';
    $datas['widget']['lang'] = __LANG;
    $datas['widget']['validated'] = O;  ######## 0 to save in temporary table

    addnewModule($datas);
    setBaseName($datas);
    saveContents($datas);
    addWidgetInDirCat($datas);
    

*/
function addnewTempModule (&$datas) {
    $DB = $datas['DB'];
    global $tutorial_addModule;
    $url = getWidgetUrl($datas,$datas['widget']['contents']['home']['type'],
                                $datas['widget']['contents']['home']['href'] );
    $defvar =  $datas['widget']['defvar'];
    $datas['widget']['url'] = $url;
    $name = $datas['widget']['title'];
    $desc = $datas['widget']['description'];
    $status = isset($datas['widget']['status']) ? $datas['widget']['status'] :'N';
    //$format = $datas['widget']['contents']['home']['type'];
    $format = $datas['widget']['format'];
    $height = isset($datas['widget']['height']) ? $datas['widget']['height'] :300;
    $minwidth = isset($datas['widget']['minwidth']) ? $datas['widget']['minwidth'] :150;
    $sizable = isset($datas['widget']['sizable']) ? $datas['widget']['sizable'] :1;
    $website = isset($datas['widget']['website']) ? $datas['widget']['website'] :'';
    $editor_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] :1;
    $nbvariables = isset($datas['widget']['nbvariables']) ? $datas['widget']['nbvariables'] : 0;
    $lang = isset($datas['widget']['lang']) ? $datas['widget']['lang'] : 'en';
    $iconid = isset($datas['widget']['iconid']) ? $datas['widget']['iconid'] : '';
    $keyword = isset($datas['widget']['keyword']) ? $datas['widget']['keyword'] : '';
    $keywords = isset($datas['widget']['keywords']) ? $datas['widget']['keywords'] : '';
    $autorefresh = isset($datas['widget']['autorefresh']) ? $datas['widget']['autorefresh'] : 0;
    $views = isset($datas['widget']['views']) ? $datas['widget']['views'] : 'home';
    $DB->execute($tutorial_addModule,
                $DB->quote(   $DB->escape( $url ) ),
                $DB->quote($DB->escape( $defvar ) ),
                $DB->noHTML(htmlspecialchars($name,ENT_QUOTES,'UTF-8')),
                $DB->noHTML(htmlspecialchars($desc,ENT_QUOTES,'UTF-8')),  
                $DB->quote($DB->escape( $status )),
                $DB->quote($DB->escape($format) ),
                $DB->escape($height),
                $DB->escape($minwidth),
                $DB->escape($sizable),
                $DB->quote($DB->escape($website)),
                $DB->escape($editor_id ),
                $DB->escape($nbvariables),
                $DB->quote($lang),
                $DB->quote($icon),
                $DB->quote($keyword),
                $DB->quote($DB->escape($keywords)),
                $DB->escape($autorefresh ),
                $DB->quote($views)
        );
    $id=$DB->getId();
    $datas['widget']['id'] = $id;
    
}

/*
    buildIconPath
    
    \brief build icon path for widget (not rss widget)
    
    @param iconid
    
    return icon path to image
*/
function buildIconPath ($iconid) {
    $iconpath = "../modules/pictures/_deficon".$iconid.".gif";
    return $iconpath;
}   

/*
    saveContents
    
    \brief save content in dir_item_external
    
    @param[in] hash ref
    
    get html template in ../tutorial/template.html

    if $datas['widget']['validated']
        save directly in dir_item_external
    else
        save in temporary table    

    if $datas['widget']['quotes'] != 'NO'
        quotes datas
    else 
        don't quotes
        Because datas can retrieve from xml file and not only through
        post http request
        
    then createParamXMLFile
        
*/
function saveContents (&$datas) {
    global $tutorial_setTemp_Dir_Item_External,
        $tutorial_UpdateTemp_Dir_Item_External,
        $tutorial_getNbViews,
        $tutorial_getItemViews,
        $tutorial_DeleteTemp_Dir_Item_ExternalView,
        $tutorial_setDir_Item_External;
    $DB = $datas['DB'];
    $f = new file('../tutorial/template.html');
    $itemid = $datas['widget']['id'];
    $idModuleValidated = $datas['widget']['validated_id'];
    $template_original = $f->read();
    $basename = $datas['widget']['basename'];
    $localfolder = $datas['widget']['localfolder'];
    $external_xmlmodule2save = $datas['widget']['xmlcontent'];
    if ($datas['widget']['quotes'] != 'NO') {
        $external_xmlmodule2save = preg_replace('!\\"!','\\\\"',$external_xmlmodule2save);
        $external_xmlmodule2save = preg_replace("!\\'!","\\\\'",$external_xmlmodule2save);
        $external_xmlmodule2save = preg_replace("!\\/!","\\\\/",$external_xmlmodule2save); 
    }
    $format = $datas['widget']['format'];
    $type = '';
    //save in tmp or not following parameter $datas['widget']['validated']
    $save_request = $tutorial_setTemp_Dir_Item_External;
    if (isset($datas['widget']['validated'])) {
        $save_request = $tutorial_setDir_Item_External;
    }
    foreach ($datas['widget']['contents'] as $view => $wcontent) {
        $type = $wcontent['type'];
        $content = $wcontent['content'];

        $htmlcode = $template_original;
        $external_source='';
        if ($type=="html") {
            updateWidgetUrl($datas,$datas['widget']['url'],$type);
            $url = '';
            $content = Specialdecode($content);
            $external_source = preg_replace('/__INSCRIPT_CONTENT_/',$content,$htmlcode);
            $external_source = preg_replace('/__BASENAME_/',$basename,$external_source);
            $external_source = preg_replace('/__LOCALFOLDER_/',$localfolder,$external_source);
            if (isset($datas['widget']['quotes']) && $datas['widget']['quotes'] != 'NO') {
                $external_source = preg_replace("!\\'!","\\\\'",$external_source);
                $external_source = preg_replace('!\\"!','\\\\"',$external_source);    
                $external_source = preg_replace("!\\/!","\\\\/",$external_source); 
            }
        } else if ($type == "url") {
            $url = $wcontent['href'];
            if (substr($url,0,7)!="http://") {
               $url="http://".$url;
            }
            $datas['widget']['url'] = $url;
            updateWidgetUrl($datas,$url,$type);
        }
        if (isset($datas['widget']['validated'])) {
            $res = $DB->execute($save_request,$DB->escape($itemid),
                                                 $DB->quote($external_source),
                                                 $DB->quote($external_xmlmodule2save),
                                                 $DB->quote($url),
                                                 $DB->quote($view),
                                                 $DB->quote($format)
                                                 ); 
        } else {
            $res = $DB->execute($save_request,$DB->escape($itemid),
                                                 $DB->quote($external_source),
                                                 $DB->quote($external_xmlmodule2save),
                                                 $DB->quote($url),
                                                 $DB->quote($view),
                                                 $DB->quote($format),
                                                 $DB->escape($idModuleValidated)
                                                 ); 
        }                                    
    }
   // updateWidgetUrl($datas,$url,$type);
    createParamXMLFile($itemid,array(),$external_xmlmodule2save);
}
/*
    updateWidgetUrl
    
    \brief update widget url to add pitem=<id>
    
    @param[in]
        hash ref
        
        $url
        $type
        
    if $datas['widget']['validated']
        save directly in dir_item
    else
        save in temporary table

*/
function updateWidgetUrl (&$datas,$url,$type) {
    $DB = $datas['DB'];
    global $tutorial_updateUrl,
            $tutorial_DirectupdateUrl;
    $format = $datas['widget']['format'];
    $id = $datas['widget']['id'];
    $update_request = $tutorial_updateUrl;
    if (isset($datas['widget']['validated'])) {
        $update_request = $tutorial_DirectupdateUrl;
    }

    if ($format == 'I' || $format == 'U' || $format == 'G') {
        if ($type == "url") {
            if ( preg_match('/\?/',$url) ) {
                if ( !preg_match('/\?$/',$url) ) {
                    if ( !preg_match('/\&$/',$url) ) {
                        $url = $url . "&";
                    }
                }
            } else {
                $url = $url . "?";
            }
            $DB->execute(
                    $update_request,
                        $DB->quote($url),
                        $id
                );
        } else {
            $DB->execute(
                    $update_request,
                        $DB->quote("$url?getsource=1&pitem=$id&format=I&"),
                        $id
                );
        }
    }    
} 
/*
    addWidgetInDirCat
    
    \brief add widget in a directory category
    
    @param hash reference
    
    must contains
        $datas['widget']['category_id']
        $datas['widget']['id']
    
    if $datas['widget']['validated'] == 1
        add directly in catdir_item
    else
        add in temporary table
    
*/
function addWidgetInDirCat (&$datas) {
    $DB = $datas['DB'];
    global $tutorial_insertTempDirCat,
            $tutorial_insertDirCat;
    $category_id = $datas['widget']['category'];
    $id = $datas['widget']['id'];
    $insert_dircat = $tutorial_insertTempDirCat;
    if (isset($datas['widget']['validated'])) {
        $insert_dircat = $tutorial_insertDirCat;
    }    
    $DB->execute($insert_dircat,
                 $id,
                 $DB->escape($category_id)
                );
}

/*
    getWidgetUrl
    
    @param[in]
        hash ref
        type
        url
    get url of widget
    url set in url field of dir_tem or tmp_dir_item
    
    set $datas['widget']['format'] to U or I
    
    return $url

*/
function getWidgetUrl (&$datas,$type,$url) {
    if ($type == "rss") {
        return "../modules/p_rss.php";
    } else if ($type == "html") {
        if (__USE_OPENSOCIAL) {
            $datas['widget']['format'] = 'G';
        }
        else {
            $datas['widget']['format'] = 'I';
        }
        return "../modules/xml_getwidget.php";
    } else if ($type == 'url') {
        $datas['widget']['format'] = 'U';
        return $url;
    } else {
        return $url;
    }
}

/*
    setBaseName
    
    \brief for use of IGoogle widget
    
    add google basename meta and google localfolder
    
    set
        $datas['widget']['basename']
        $datas['widget']['localfolder']

*/
function setBaseName (&$datas) {
    $datas['widget']['basename'] = '';
    $datas['widget']['localfolder'] = '..';
    if ( isset($datas['widget']['author_affiliation']) 
            &&  preg_match(
                    '/author_affiliation="Google\s[^"]*"/xmsi',
                        $datas['widget']['author_affiliation']
                    ) 
        ) 
    {
        $datas['widget']['basename'] = '<base href="http://www.google.com/" />';
        $datas['widget']['localfolder'] = __LOCALFOLDER;  
    }
}

function get404WidgetPage () {
    $widget404page =  __WIDGET404;
	$content = "";
    $fp=fopen($widget404page,"r");    
    while (!feof($fp)) { 
      $content .= fgets($fp, 4096);
    }
    fclose ($fp);
    return $content;
}

/*
    @function getWidgetTemplate
    
        get wdget html template from template if exists

*/
function getWidgetTemplate () {
    //use parameter ?
    $filename = "../tutorial/template.html";
    if (file_exists($filename)) {
        $f = new file($filename);
        $template_original = $f->read();
        return $template_original;
    } else {
        return <<<EOT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
__BASENAME_
<title>Widget</title>
<link rel="stylesheet" type="text/css" media="screen" title="default" href="__LOCALFOLDER_/styles/module.css" />
<link rel="stylesheet" type="text/css" media="screen" title="default" href="__LOCALFOLDER_/styles/module1.css" />
<script type="text/javascript" src="__LOCALFOLDER_/includes/modules.js"></script>
<script type="text/javascript">
</script>
</head>
<body onload="_IG_AdjustIFrameHeight();">
__INSCRIPT_CONTENT_
</body>
</html>
EOT;
    }
}

/*
    @function checkModuleInDB
    
        Check if module exists in DB

*/
function checkModuleInDB ( $url,$DB ) {
	global $tutorial_getIdModuleByUrl;
	$chkId = 0;
	$DB->getResults($tutorial_getIdModuleByUrl,$DB->quote('%'.$url.'%'));
	if ($DB->nbResults() != 0)
	{
		$row=$DB->fetch(0);
		$chkId = $row["id"];
	}
	$DB->freeResults();
	
	return $chkId;
}
/*
    @function updateModuleInDB
    
        Show module in DB 

*/
function updateModuleInDB ( $modId,$DB ) {
    global $tutorial_showModule;
	$DB->execute($tutorial_showModule,$DB->escape($modId));
}

?>