<?php
/*
     Persistency.php Mediawiki extension. Link and page which receive template and arguments.
     See detail http://metabolomics.jp/wiki/Help:Extension/Persistency
     Last-modified: 2011.03.24
     Version: 0.12
     Change:
       - Change that can use only logged in user.

     Version: 0.11 2011.02.22
     Change:
       - fix ignore last item

     Version: 0.1 2009.01.23

     *********************************************************************

     Copyright (C) 2009-2011 Metabolomics.JP Development Team

     This program 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 2 of the License, or
     (at your option) any later version.

     This program 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 this program; if not, write to the Free Software
     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

     *********************************************************************
     Author: Arita laboratory, with Kazuhiro Suwa <metabolome@cb.k.u-tokyo.ac.jp>
     URL: http://metabolomics.jp/
*/
 
if ( !defined( 'MEDIAWIKI' ) ) {
	die( 'This file is a MediaWiki extension, see <a href="http://metabolomics.jp/wiki/Help:Extension/HookInsert">HookInsert.php</a>.' );
}

$wgExtensionCredits['parserhook'][] = array(
	'name' => 'HookInsert',
	'version' => '0.12',
	'author' => 'K, Suwa',
	'description' => '',
	'url' => 'http://metabolomics.jp/wiki/Help:Extension/HookInsert',
);

$wgHooks['ArticleViewHeader'][] = 'efHookinsertInsert';
$wgHooks['ParserBeforeStrip'][] = 'efHookinsertDeleteMark';

global $egHookInsList, $egHookInsTitle, $egHookInsInsertFlag;
$egHookInsList = "";
$egHookInsTitle = "";
$egHookInsInsertFlag = false;

function efHookinsertInsert( &$article, &$outputDone, &$pcache )
{
	global $wgRequest, $wgExtraNamespaces, $egHookInsList, $egHookInsTitle, $egHookInsInsertFlag, $wgUser;

	if( $wgUser->isLoggedIn() == false )
		return true;

	# check flag
	if( strcmp( $wgRequest->getText( "my_hookinsert" ), "__HOOK_AND_INSERT__" ) != 0 ) {
		return true;
	}

	# get namespace number
	$ns = array_keys( $wgExtraNamespaces, "Index" );
	if( count( $ns ) != 1 )
		return true;
	$ns = $ns[0];

	# get data
	$list = "";
	$lists = $wgRequest->getArray( "my_list" );
	$targetTitle = $wgRequest->getText( "my_title" );
	$sep = $wgRequest->getText( "my_separator" );
	if( strlen( $sep ) == 0 )
		$sep = "&&";
	$tmpTitle = preg_replace( "/([^\\\])\//", "$1\\\/", $targetTitle ); // / -> \/ for preg_match
	$content = $article->getContent();
	if( count( $lists ) > 0 ){
		# check list data, if correct data or no exist data.
		$listpage = $wgRequest->getText( "my_listpage" );
#		$listTitle = Title::newFromText( "Index:" . $listpage );
		$listTitle = Title::makeTitleSafe( $ns, eregi_replace( "^Index:", "", $listpage ) );
		$listArticle = new Article( $listTitle );
		$listArticle->clear();
		$listContent = $listArticle->getContent() . "\n";
		#$tmpLists = array();
		$checkStr = "";
		# do not register, if there is no item in listpage
		for( $i = 0; $i < count( $lists ); $i ++ ){
			$tmp = preg_replace( "/([^\\\])\//", "$1\\\/", $lists[$i] ); // / -> \/ for preg_match
#			if( preg_match( "/-$lists[$i]\n/", $listContent ) >= 1 )
#			if( preg_match( "/-$tmp\n/", $listContent ) >= 1 && preg_match( "/&&$tmp&&/", $checkStr ) == 0){
#$ddd = str_replace( "[", "\\[", $tmp);
#$ddd = str_replace( "]", "\\]", $ddd);
#$aaa = preg_match( "/[*#] *$ddd *\n/", $listContent );
#$aaa = preg_match( "/[*#] *$tmp *\n/", $listContent );
#`echo "$tmp $aaa" >> /tmp/log`;
			if( preg_match( "/[*#] *$tmp *\n/", $listContent ) >= 1 && preg_match( "/$sep$tmp$sep/", $checkStr ) == 0){
				$tmpLists[] = $lists[$i];
				$checkStr .= "$sep" . $lists[$i] . "$sep"; // check duplication
			}
		}

		# data, separated by &&
#		$list = implode( "$sep", $tmpLists ) . "$sep";
		$list = implode( "$sep", $tmpLists );
#		$list = implode( "&&", $lists ) . "&&";

#		$nextContent = preg_replace( "/\+\+$tmpTitle\+\+.*\+\+$tmpTitle\+\+/", "++$tmpTitle++$sep$list++$tmpTitle++", $content );
		$nextContent = preg_replace( "/\+\+$tmpTitle\+\+.*\+\+$tmpTitle\+\+/", "++$tmpTitle++$list++$tmpTitle++", $content );
	} else {
		$nextContent = preg_replace( "/\+\+$tmpTitle\+\+.*\+\+$tmpTitle\+\+/", "++$tmpTitle++++$tmpTitle++", $content );
	}

#`echo "$nextContent" >> /tmp/log`;
	# update data
	$article->doEdit( $nextContent, '', EDIT_UPDATE );

	# set data for replacement
#	$egHookInsList = $sep . $list;
	$egHookInsList = $list;
	$egHookInsTitle = $targetTitle;
	$egHookInsInsertFlag = true;

	return true;
}

function efHookinsertDeleteMark( &$parser, &$text, $strip_state ) {
	global $egHookInsList, $egHookInsTitle, $egHookInsInsertFlag;

	# replace data, because do not update immediately
	if( $egHookInsInsertFlag ){
		$tmpTitle = preg_replace( "/([^\\\])\//", "$1\\\/", $egHookInsTitle ); // / -> \/ for preg_match
		$text = preg_replace( "/\+\+$tmpTitle\+\+.*\+\+$tmpTitle\+\+/", "++$tmpTitle++$egHookInsList++$tmpTitle++", $text );
	}
	# delete unnecessary data(marker)
	$text = preg_replace( "/\+\+[^\+]+\+\+/", "", $text );

	return true;
}