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

/**	=== Bloge-Ping ===
 *	Copyright 2009 Eemeli Aro <eemeli@gmail.com>
 *
 *	Notify search engines when a page is modified
 *
 *	Developed and tested using PmWiki 2.2.x
 *	Partly based on Stefan Schimanski's GoogleBlogPing
 *
 *	To install, add the following to your configuration file:

		include_once("$FarmD/cookbook/bloge-ping.php");

 *	This is a part of the Bloge bundle of recipes, but may be used by itself.
 *	For more information, please see the online documentation at
 *		http://www.pmwiki.org/wiki/Cookbook/Bloge-Ping and at
 *		http://www.pmwiki.org/wiki/Cookbook/Bloge
 *
 *	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.
 */

$RecipeInfo['Bloge-Ping']['Version'] = '2009-08-11';

$EditFunctions[] = 'BlogePing';

function BlogePing($pagename, &$page, &$new) {
	global $IsPagePosted, $BlogePing, $MessagesFmt;

	SDVA($BlogePing, array(
		'page' => $pagename,
		'pagefilter' => '/.*/',
		'name' => '{$WikiTitle}',
		'url' => '{$ScriptUrl}',
		'changesURL' => '',
		'tgt' => array(),
		'msgok' => '',
		'msgerror' => '<b style="color:red">Bloge-Ping error ($tgt):</b><br />$msg<br />'
	));
	SDVA($BlogePing['tgt'], array(
		'googleblogsearch' => array(
			'url' => 'http://blogsearch.google.com/ping',
			'param' => array('name','url','changesURL'),
			'msgpat' => '/Thanks for the ping/'
		)
	));

	$pn_filt = MatchPageNames($pagename, $BlogePing['pagefilter']);
	if (!$IsPagePosted || ( @$_POST['diffclass'] == 'minor' ) || empty($pn_filt)) return;

	$pn = MakePageName($pagename, $BlogePing['page']);

	foreach ( $BlogePing['tgt'] as $t => $tgt ) {
		$param = array();
		foreach ( $tgt['param'] as $k ) $param[] = "$k=" . urlencode(FmtPageName(isset($tgt[$k]) ? $tgt[$k] : $BlogePing[$k], $pn));
		$url = $tgt['url'] . '?' . implode('&', $param);

		if (function_exists('curl_init')) {
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
			$msg = curl_exec($ch);
			if (empty($msg)) $msg = 'connection error: ' . curl_error($ch);
			curl_close($ch);
		} else {
			$msg = file_get_contents($url);
			if (empty($msg)) $msg = 'connection error';
		}

		$msg_filt = MatchPageNames($msg, $tgt['msgpat']);
		$MessagesFmt[] = str_replace(
			array( '$tgt','$msg' ),
			array( $t, htmlspecialchars($msg) ),
			$tgt[ empty($msg_filt) ? 'msgerror' : 'msgok' ]
		);
	}
}