<?php if (!defined('PmWiki')) exit();

/*  Copyright 2009 Hans Bracker
    This file is part of PmWiki; 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 2 of the License, or
    (at your option) any later version.  See pmwiki.php for full details.

    This script adds the following tools to help implement language views features:
    $Lang variable from a list $MLVList.
    ?setlang=<id> cookie switcher and ?lang=<id> switcher.
    (:if lang <id>:) conditional markup.
    {$Lang} and {$LangLabel} page variables (lower case also permitted).
    (:title-<id>:) markup for language specific title attributes.
    (:if langinpage <id> <pagename>:) conditional markup.
    (:selectlang <type>:) language select links markup.
*/
# version date
$RecipeInfo['MultiLanguageViews']['Version'] = '2019-11-12';

## language id's and label texts. For id's use "ISO 639-1" 2 letter language codes
SDV($MLVList, array(
        'en' => 'english',
        'de' => 'deutsch',
        'fr' => 'francais',
        'it' => 'italiano',
        'es' => 'espanol',
    ));

## default language id
SDV($MLVDefault,'en');

## link patterns for (:selectlang <type>:) directive
## note that '$page', '$id' and '$label' are used as pseudo-variables
SDVA($MLVLinkPatterns, array(
		'id'    => '[[$page?setlang=$id|$id]]', // links with id label
		'label' => '[[$page?setlang=$id|$label]]', // links with text label
		'flag'  => '[[$page?setlang=$id|Attach:Site/Site/$id.png"$label"]]', // links with images (flags) plus tooltip label
));

## default link type for (:selectlang:) directive;
## type needs to be one of the keys from $MLVLinkPatterns array
SDV($MLVSelectDefault, 'id');

## default cookie name. $CookiePrefix may be defined in config.php,
## so that different wikis on the same server can have separate cookies
SDV($MLVCookie, $CookiePrefix.'userlang');

## default cookie expire time set to 1 year:
SDV($MLVCookieExpires,$Now+60*60*24*365);

## enable language switching
SDV($EnableMLVSwitching,1);

# show content if langs are not installed with (:if !enabled langviews:)
$langviews = 1;

## if enabled $Lang can be set with a cookie by ?setlang=<id>
## and without a cookie by ?lang=<id>
## and also for backwards compatibility with multilanguage.php with ?userlang=<id>

if($EnableMLVSwitching == 1) {
  $sl = '';
  if (isset($_GET['lang']))	$sl = $_GET['lang'];
  else if (isset($_GET['setlang'])) $sl = $_GET['setlang'];
  else if (isset($_GET['userlang'])) $sl = $_GET['userlang'];
  else if (isset($_COOKIE[$MLVCookie])) $sl = $_COOKIE[$MLVCookie];
  else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
		$sl = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
  if (@$MLVList[$sl]) {
  	if (!isset($_GET['lang'])) setcookie($MLVCookie,$sl,$MLVCookieExpires,'/');
  	$Lang = $sl; unset($sl);
  } else $Lang = $MLVDefault;
  $_COOKIE[$MLVCookie] = $Lang;
};

## {$Lang} {$LangLabel} {$lang} {$langlabel} page variables
$FmtPV['$Lang'] = $FmtPV['$lang'] = '$GLOBALS["Lang"]';
$FmtPV['$LangLabel'] = $FmtPV['$langlabel'] = "$MLVList[$Lang]";
$FmtPV['$userlang'] = '$GLOBALS["Lang"]';

## set wiki title if we have array $MLVWikiTitle of language specific wiki titles
if (isset($MLVWikiTitle[$Lang])) $WikiTitle = $MLVWikiTitle[$Lang];

## (:if lang <id>:) conditional markup:
$Conditions['lang'] = "\$GLOBALS['Lang']==\$condparm";
//for backwards compatibility with multilanguage.php: (:if userlang <id>:)
$Conditions['userlang'] = "\$GLOBALS['Lang']==\$condparm";

## (:title-<id>:) title markup
foreach($MLVList as $id => $v) {
		$title = 'title-'.$id;
		Markup($title,'directives',
  		'/\\(:(title-'.$id.')\\s(.*?):\\)/i',
  		"MLVSetTitleProperty");
	}
function MLVSetTitleProperty($m) {
	global $EnablePageTitlePriority;
	extract($GLOBALS['MarkupToHTML']); //get $pagename
   return PZZ(PCache($pagename, $zz=array($m[1] => 
        SetProperty($pagename, $m[1], $m[2], NULL, $EnablePageTitlePriority))));	
}

## title page variables
$FmtPV['$Titlespaced'] =
    '@$page["mltitle-'.$Lang.'"] ? $page["mltitle-'.$Lang.'"] :
    (@$page["title"] ? $page["title"] : $AsSpacedFunction($name))';
$FmtPV['$Title'] =
    '@$page["mltitle-'.$Lang.'"] ? $page["mltitle-'.$Lang.'"] :
    (@$page["title"] ? $page["title"] : ($GLOBALS["SpaceWikiWords"]
       ? $AsSpacedFunction($name) : $name))';

## set $HTMLTagAttr, used in some skin's <HTML> tag
if ($HTMLTagAttr) {
	$htmltag = ParseArgs($HTMLTagAttr);
	$HTMLTagAttr = preg_replace('/lang=[\'\"\w]+/',"lang='$Lang'",$HTMLTagAttr);
} else $HTMLTagAttr = "lang='$Lang'";
       
## on page edits save 'languages=<id>,...' and title-<id>=... as page attributes
array_unshift($EditFunctions,'MLVSaveAttr');
function MLVSaveAttr($pagename, &$page, &$new) {
	global $MLVList;
	$text = $new['text'];
	$text = preg_replace('/(\[=.+=\])/msiU', '', $text);
	$text = preg_replace('/(\[@.+@\])/msiU', '', $text);
	$plang = array();
	// look for language conditionals as indicators for languages used in page
	preg_match_all('/\(:if\d*\s+(user|)lang\s+(\w+?)\s*:\)/msi', $text, $m);
	foreach (array_keys($MLVList) as $id)
			if (in_array($id, $m[2])) $plang[] = $id;
	if (count($plang)>0) $new['languages'] = implode(',', $plang);
	else unset($new['languages']);
	$ltitles = array();
	//look for title markups
	preg_match_all('/\(:if\d*\s+(user|)lang\s+(\w+?)\s*:\).*?\(:title\s+(.+?)\s*:\)/msi', $text, $m);
		for ($i=0; $i<count($m[2]); ++$i)
			if (array_key_exists($m[2][$i],$MLVList)) {
				$new['mltitle-'.$m[2][$i]] = $m[3][$i];
				$ltitles[] = $m[2][$i];
			}
	//look for title-id markups
	preg_match_all('/\(:title-(\w\w)\s+(.+?)\s*:\)/msi', $text, $m);
	for ($i=0; $i<count($m[1]); ++$i)
		if (array_key_exists($m[1][$i],$MLVList)) {
			$new['mltitle-'.$m[1][$i]] = $m[2][$i];
			$ltitles[] = $m[1][$i];
		}
	//remove any old mltitle
	foreach($MLVList as $k => $v) {
		if (isset($page['mltitle-'.$k]) && !in_array($k, $ltitles))
			unset($new['mltitle-'.$k]);
	}
} //}}}

## (:if langinpage <id> <pagename>:) conditional markup
## example: show language specific pagelist for instance with
## (:pagelist group=... if="langinpage {$Lang} {=$FullName}":)
$Conditions['langinpage'] = 'MLVLangInPage(\$pagename, \$condparm)';
function MLVLangInPage($pagename, $parm) {
	$arg = explode(' ',$parm);
	if ($arg[0]=='') return false;
	$pn = ($arg[1])? MakePagename($pagename, $arg[1]) : $pagename;
	$page = RetrieveAuthPage($pn, 'read', false, READPAGE_CURRENT);
	$plang = explode(',', $page['languages']);
	return in_array($arg[0], $plang);
} //}}}

## (:selectlang <type>:) links markup
Markup('selectlang','directives','/\\(:selectlang\\s*(.*?)\\s*:\\)/i', "MLVSelectLangLinks");
function MLVSelectLangLinks($m) {
	global $MLVList, $MLVSelectDefault, $MLVLinkPatterns;
	extract($GLOBALS['MarkupToHTML']);
	$args = ParseArgs($m[1]);
	if ($args['']) $type = array_shift($args['']);
	if (!$type || !array_key_exists($type, $MLVLinkPatterns))
		$type = $MLVSelectDefault;
	if ($args['lang']) {
		if ($args['lang']=='all') $plang = array_keys($MLVList);
		else $plang = explode(',', $args['lang']);
	} else {
		$page = RetrieveAuthPage($pagename, 'read', false, READPAGE_CURRENT);
		$plang = explode(',', $page['languages']);
	}
	if(!$plang[0]=="")
	foreach ($plang as $k) {
		$str = '';
		$str = str_replace('$id', $k, $MLVLinkPatterns[$type]);
		$str = str_replace('$label', $MLVList[$k], $str);
		$out .= str_replace('$page', $pagename, $str).' ';
	}
	return $out;
} //}}}
//EOF