Extension:LanguageFunctions/v0.1.2/LanguageFunctions.php

From MediaWiki.org
Jump to navigation Jump to search
<?php

/*
	LanguageFunctions.php
	Leovitch 27Jun2009
	The code is licensesd under a Creative Commons Attribution 3.0 United States License
*/

if ( !defined( 'MEDIAWIKI' ) ) {
	die( 'This file is a MediaWiki extension, it is not a valid entry point' );
}

// Standard plug-in variables

$wgExtensionFunctions[] = 'wfSetupLanguageFunctions';
$wgExtensionCredits['parserhook'][] = array(
	'name' => 'LanguageFunctions',
	'version' => '0.1.1',
	'url' => 'http://www.mediawiki.org/wiki/Extension:LanguageFunctions',
	'author' => 'Leo Hourvitz',
	'description' => 'Allow multilingual content pages to be filtered by language',
	'descriptionmsg' => 'lfunc_desc',
);

$wgExtensionMessagesFiles['LanguageFunctions'] = dirname(__FILE__) . '/LanguageFunctions.i18n.php';
// Force them to load now so that we can use them in initializing the 
// LanguageFilters array
$wgHooks['LanguageGetMagic'][]       = 'lfLanguageFunctionsLanguageGetMagic';
$wgHooks['SkinBuildSidebar'][]		 = 'lfExtendSidebar';
$wgHooks['BeforePageDisplay'][]      = 'lfCookieJavascript';
$wgHooks['GetCacheVaryCookies'][]	 = 'lfGetCacheVaryCookies';

// Configuration
// Override this variable in your localSettings.php, this is just an example.
// In general the keys should be non-translated.
// The values should be comma-separated arrays of language code; the 
// zero-length string means to ignore the cookie and use the user's
// language preference.  Although we should that as an example here,
// in most cases where you are using this kind of internationalization,
// you probably don't want the 'default' choice.
$wgLanguageFunctions_LanguageFilters = array(
	'English' => 'en',
	'日本語' => 'ja',
	'All / 両方' => 'en,ja',
	'User Default' => '',
);

/*
	Advanced Configuration
	It will be helpful to your users to create some custom editing buttons that
	allow them to easily insert multilingual blocks of text.  Go to the
	MediaWiki:Common.js page on your site and set up the JavaScript to do so.
	Below is an example for English as a first language and Japanese as a second
	language.  The complex backslashing is required to get through the layers
	of JavaScript.

		var lf_b1 = {
			"imageFile": "extensions/LanguageFunctions/UpDownLanguage.png",
			"speedTip": "place language alternations above and below",
			"tagOpen": '\{\{\#iflang: en\|',
			"tagClose": '\}\}\n\{\{\#iflang: ja\|\n\}\}',
			"sampleText": "original"
		};
		mwCustomEditButtons.push(lf_b1);
		var lf_b2 = {
			"imageFile": "extensions/LanguageFunctions/RightLeftLanguage.png",
			"speedTip": "place language alternations left and right (as for a header)",
			"tagOpen": '\{\{\#iflang: en|',
			"tagClose": '\}\}\{\{\#ifmultlang: \}\}\{\{\#iflang: ja|\}\}',
			"sampleText": "original"
		};
		mwCustomEditButtons.push(lf_b2);
*/

class ExtLanguageFunctions {
	function registerParser( &$parser ) {
		if ( defined( get_class( $parser ) . '::SFH_OBJECT_ARGS' ) ) {
			// These functions accept DOM-style arguments
			$parser->setFunctionHook( 'iflang', array( &$this, 'iflangObj' ), SFH_OBJECT_ARGS );
			$parser->setFunctionHook( 'ifmultlang', array( &$this, 'ifmultlangObj' ), SFH_OBJECT_ARGS );
		} else {
			$parser->setFunctionHook( 'iflang', array( &$this, 'iflangHook' ) );
			$parser->setFunctionHook( 'ifmultlang', array( &$this, 'ifmultlangHook' ) );
		}
		wfLoadExtensionMessages('LanguageFunctions');
		return true;
	}

	// Returns whether or not the given language code is in the list of currently presented
	// languages
	function IsLanguageShown($lang) {
		global $wgRequest;
		global $wgUser;
		global $wgLanguageCode;

		if (isset($_COOKIE['lfmw_langs']) and strlen($_COOKIE['lfmw_langs']) > 0) {
			$language_codes = explode(',',$_COOKIE['lfmw_langs']);
			foreach ($language_codes as $language_code) {
				if ($language_code == $lang) {
					return true;
				}
			}
			// If the cookie is defined, it is the absolute reference
			return false;
		}
		$uLang = $wgUser->getOption('language');
		if ($uLang != '' ) {
			if ($uLang == $lang) {
				return true;
			} else {
				return false;
			}
		}
		return ($wgLanguageCode == $lang);
	}

	// Returns whether ot not multiple languages are currently enabled
	function IsMultipleLanguages() {
		if (isset($_COOKIE['lfmw_langs'])) {
			$language_codes = explode(',',$_COOKIE['lfmw_langs']);
			return count($language_codes) > 1;
		}
		return false;
	}

	function iflangHook( &$parser, $lang = '', $value = '' ) {
		if ( $this->IsLanguageShown($lang) ) {
			return $value;
		} else {
			return '';
		}
	}

	function iflangObj( &$parser, $frame, $args ) {
		$lang = isset( $args[0] ) ? trim( $frame->expand( $args[0] ) ) : '';
		if ( $this->IsLanguageShown($lang) ) {
			return isset( $args[1] ) ? trim( $frame->expand( $args[1] ) ) : '';
		} else {
			return '';
		}
	}

	function ifmultlangHook( &$parser, $value = ' ' ) {
		if ( $this->IsMultipleLanguages() ) {
			return $value;
		} else {
			return '';
		}
	}

	function ifmultlangObj( &$parser, $frame, $args ) {
		if ( $this->IsMultipleLanguages() ) {
			return isset( $args[1] ) ? trim( $frame->expand( $args[1] ) ) : ' ';
		} else {
			return '';
		}
	}

}

function wfSetupLanguageFunctions() {
	global $wgParser, $wgExtLanguageFunctions, $wgHooks;

	$wgExtLanguageFunctions = new ExtLanguageFunctions;

	// Check for SFH_OBJECT_ARGS capability
	if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
		$wgHooks['ParserFirstCallInit'][] = array( &$wgExtLanguageFunctions, 'registerParser' );
	} else {
		if ( class_exists( 'StubObject' ) && !StubObject::isRealObject( $wgParser ) ) {
			$wgParser->_unstub();
		}
		$wgExtLanguageFunctions->registerParser( $wgParser );
	}
}

function lfLanguageFunctionsLanguageGetMagic( &$magicWords, $langCode ) {
	require_once( dirname( __FILE__ ) . '/LanguageFunctions.i18n.magic.php' );
	foreach( lfLanguageFunctionsWords( $langCode ) as $word => $trans )
		$magicWords[$word] = $trans;
	return true;
}

function lfGetCacheVaryCookies($out, &$cookies) {
	$cookies[] = 'lfmw_langs';
	$cookies[] = 'lfmediawiki_dummyValue';
	return true;
}


function lfExtendSidebar( $skin, &$bar ) {
	global $wgLanguageFunctions_LanguageFilters;

	$contents = "<ul>\n";
	foreach ($wgLanguageFunctions_LanguageFilters as $filter => $langCode ) {
		$contents .= "<li><a href='' onclick='lfmediawiki_languageCookie(\"$langCode\")' >$filter</a>";
		if (isset($_COOKIE['lfmw_langs']) and $_COOKIE['lfmw_langs'] == $langCode) {
			$contents .= " &#10003;";
		}
		$contents .= "</li>\n";
	}
	$contents .= "</ul>\n";
	// Handy for cookie debugging
	// $contents .= "<p>Cookie set is '".isset($_COOKIE['lfmw_langs'])."'.</p>\n";
	// $contents .= "<p>Cookie value is '".$_COOKIE['lfmw_langs']."'.</p>\n";
	// $contents .= "<p>Cookie length is '".strlen($_COOKIE['lfmw_langs'])."'.</p>\n";
	$bar[wfMsg('language_filters')] = $contents;
	return true;
}

function lfCookieJavascript(&$out, $a=null) {
	$out->addScript(<<<LFJAVASCRIPT

	<script type="text/javascript">
		/* Any JavaScript here will be loaded for all users on every page load. */

		function lfmediawiki_setCookie( name, value, expires, path, domain, secure )
		{
			// set time, it's in milliseconds
			var today = new Date();
			today.setTime( today.getTime() );

			if ( expires )
			{
				expires = expires * 1000 * 60 * 60 * 24;
			}
			var expires_date = new Date( today.getTime() + (expires) );

			document.cookie = name + "=" +escape( value ) +
				( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
				( ( path ) ? ";path=" + path : "" ) +
				( ( domain ) ? ";domain=" + domain : "" ) +
				( ( secure ) ? ";secure" : "" );
		}


		function lfmediawiki_languageCookie(value) {
			lfmediawiki_setCookie('lfmw_langs',value,365,'/','',false);
		}

	</script>
LFJAVASCRIPT
	);
	return true;
}
?>