<?php
/*
Plugin Name: WordPress search and replace
Plugin URI: http://rudd-o.com/projects/wp-search-replace/
Description: Lets you search and replace text in posts using Perl-compatible regular expressions — <a href="http://rudd-o.com/projects/wp-search-replace/wp-search-replace-usage/">Usage instructions</a>
Version: 0.1.0
Author: Manuel Amador (Rudd-O)
Author URI: http://rudd-o.com/
*/

/*  Copyright 2005  Manuel Amador

Derivative work from bsuite, written by Casey Bisson, and Simple Ajax Code Kit, written by Gregory Wild-Smith ( http://twilightuniverse.com )

    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
*/

/* TODO:
ensure when user hits enter in the expression or replacement boxes, enter does not submit the form
disable replace button, undo button and textarea while replacing, and reenable them afterwards
make installable under any folder name or directly under plugins/
*/


function get_public_url_for_file($filename) {
	return get_settings('fileupload_url') . '/plugins/wp-search-replace/' . $filename;
}

function get_plugin_public_url() {
	return get_public_url_for_file(basename(__FILE__));
}

class wpsr
{

	/* this function is stolen from Canary Comment.  Hope Owen does not mind that this plugin is licensed under the GPL */
	function include_up($filename)
	{
		$c=0;
		while(!is_file($filename))
		{
			$filename = '../' . $filename;
			$c++;
			if($c==30) {
				die ('Could not find ' . basename($filename) . '.');
				return '';
			}
		}
		return $filename;
	}

	function stripslashespost($varname) {
		global $_POST;
		$_POST[$varname] = stripslashes($_POST[$varname]);
	}
	function performSearchAndReplace() {

		get_currentuserinfo();
		global $user_ID;
		if (!user_can_create_draft($user_ID))
			die ( __('You are not allowed to run this code.') );

/* TODO remove the modifier that allows php code to be run */

		foreach (array("searchregexp","searchmodifiers","searchreplacement","content") as $a) {
			wpsr::stripslashespost($a);
		}
		$regexp = "/" . str_replace("/","\\/",$_POST["searchregexp"]) . "/" . str_replace("e","",$_POST["searchmodifiers"]);

		$replacement = $_POST["searchreplacement"];
		$content = $_POST["content"];
		print preg_replace($regexp,$replacement,$content);
// 		print "\n\n";
	}

	function admin_head() /* FIXME this should autodetect the directory it is installed within plugins/ so I don't have to hardcode wp-search-replace there */
	{
		echo "";
	}

	function admin_footer()
	{
		$sackjsurl = get_public_url_for_file('sack.js');
		$ownjsurl = get_plugin_public_url() . '?op=outputjs';
		echo "\n";
		echo "<script type='text/javascript' language='JavaScript' src='$sackjsurl'></script>";
		echo "<script type='text/javascript' language='JavaScript' src='$ownjsurl'></script>";
		echo "\n";
	}

	function outputJS() {
		header('Content-Type: text/javascript');
		header("Cache-Control: public");
		$offset = 60*60*24*60;
		$ExpStr = "Expires: ".gmdate("D, d M Y H:i:s",time() + $offset)." GMT";
		header($ExpStr);
		include_once(dirname(__FILE__)."/wp-search-replace.js");
	}

}


if(!defined('ABSPATH')) {
	require_once(wpsr::include_up('wp-config.php'));
	$op = $_POST['op'];
	if (!$op) $op = $_GET['op'];
	switch($op) {
		case 'searchandreplace':
			wpsr::performSearchAndReplace();
			break;
		case 'outputjs':
			wpsr::outputJS();
			break;
		default:
			die("Operation unspecified");
	}
} else {
	$wantedpages = array ("/post.php","/page-new.php");
	foreach ($wantedpages as $wantedpage) {
		if (substr($PHP_SELF,-strlen($wantedpage)) == $wantedpage) {
			add_action('admin_head', array('wpsr', 'admin_head'));
			add_action('admin_footer', array('wpsr', 'admin_footer'));
			break;
		}
	}
}

?>