<?php
/**
 * ISSNs in wiki pages will create links to this page, with the ISSN passed
 * in via the query string.
 *
 * @package MediaWiki
 * @subpackage SpecialPage
 */

/**
 * Constructor
 */
function wfSpecialPeriodicalsources( $par ) {
	global $wgRequest;
	
	$issn = $par;
	if( empty( $par ) ) {
		$issn = $wgRequest->getVal( 'issn' );
	}
	$issn = preg_replace( '/[^0-9X]/', '', $issn );
	
	$bsl = new PeriodicalSourceList( $issn );
	$bsl->show();
}

/**
 *
 * @package MediaWiki
 * @subpackage SpecialPage
 */
class PeriodicalSourceList {
	var $mIssn;

	function PeriodicalSourceList( $issn ) {
		$this->mIssn = $issn;
	}

	function show() {
		global $wgOut;

		$wgOut->setPagetitle( wfMsg( "periodicalsources" ) );
		if( empty( $this->mIssn ) ) {
			$this->askForm();
		} else {
			$this->showList();
		}
	}
	
	function showList() {
		global $wgOut, $wgUser, $wgContLang;
		$fname = "PeriodicalSourceList::showList()";
		
		# First, see if we have a custom list setup in
		# [[Wikipedia:Periodical sources]] or equivalent.
		$bstitle = Title::makeTitleSafe( NS_PROJECT, wfMsg( "periodicalsources" ) );
		$dbr =& wfGetDB( DB_SLAVE );
		$bstext = $dbr->selectField( 'cur', 'cur_text', $bstitle->curCond(), $fname );
		if( $bstext ) {	
			$bstext = str_replace( "MAGICNUMBER", $this->mIssn, $bstext );
			$wgOut->addWikiText( $bstext );
			return;
		}
		
		# Otherwise, use the list of links in the default Language.php file.
		$s = wfMsg( "periodicalsourcetext" ) . "<ul>\n";
		$bs = $wgContLang->getPeriodicalstoreList() ;
		$bsn = array_keys ( $bs ) ;
		foreach ( $bsn as $name ) {
			$adr = $bs[$name] ;
			if ( ! $this->mIssn ) {
				$adr = explode( ":" , $adr , 2 );
				$adr = explode( "/" , $adr[1] );
				$a = "";
				while ( $a == "" ) {
					$a = array_shift( $adr );
				}
				$adr = "http://".$a ;
			} else {
				$adr = str_replace ( "$1" , $this->mIssn , $adr ) ;
			}
			$name = htmlspecialchars( $name );
			$adr = htmlspecialchars( $adr );
			$s .= "<li><a href=\"{$adr}\" class=\"external\">{$name}</a></li>\n" ;
		}
		$s .= "</ul>\n";

		$wgOut->addHTML( $s );
	}
	
	function askForm() {
		global $wgOut, $wgLang, $wgTitle;
		$fname = "PeriodicalSourceList::askForm()";
		
		$action = $wgTitle->escapeLocalUrl();
		$issn = htmlspecialchars( wfMsg( "issn" ) );
		$go = htmlspecialchars( wfMsg( "go" ) );
		$out = "<form action=\"$action\" method='post'>
			$issn: <input name='issn' id='issn' />
			<input type='submit' value=\"$go\" />
		</form>";
		$wgOut->addHTML( $out );
	}
}

?>
