<?php

if(!defined('IN_MYBB'))
	die('This file cannot be accessed directly.');

$plugins->add_hook('parse_message_start', 'easymycode_mycodehack');
$plugins->add_hook('admin_config_mycode_xmlhttp_test_mycode_start', 'easymycode_sandbox');
$plugins->add_hook('admin_config_mycode_add', 'easymycode_langhack');
$plugins->add_hook('admin_config_mycode_edit', 'easymycode_langhack');

$GLOBALS['easymycode_tr'] = array(
	'{ALPHA}'		=> '([a-z]+)',
	'{DIGIT}'		=> '([0-9]+)',
	'{NUM}'			=> '(-?[0-9]+(?:\.[0-9]+)?)',
	'{ALPHADIGIT}'	=> '([a-z0-9]+)',
	'{CSS}'			=> '([a-z0-9_\-]+)',
	'{TEXT}'		=> '([a-z0-9_\- ,.+]+)',
	'{URL}'			=> '([a-z0-9]+\://[^\r\n"<>&]+?)',
	'{HTTPURL}'		=> '(https?\://[^\r\n"<>&]+?)',
	'{EMAIL}'		=> '([a-z0-9_.\-]+@[a-z0-9_.\-]+)',
	'{COLOR}'		=> '([a-z\-]+|\\#?[0-9a-f]{6})',
	'{SOMETHING}'	=> '(.+?)',
	'{ANYTHING}'	=> '(.*?)',
);


function easymycode_info() {
	return array(
		'name'			=> 'Easy MyCodes',
		'description'	=> 'Removes the need to understand regex to make MyCodes.',
		'website'		=> 'http://mybbhacks.zingaburga.com/',
		'author'		=> 'ZiNgA BuRgA',
		'authorsite'	=> 'http://zingaburga.com/',
		'version'		=> '1.2',
		'compatibility'	=> '14*,15*,16*,17*,18*',
		'guid'			=> ''
	);
}

function easymycode_activate() {
	global $cache, $db;
	// convert old style MyCodes to our new style
	$query = $db->simple_select('mycode', 'cid,regex');
	$custom_mycodes = array();
	while($mycode = $db->fetch_array($query)) {
		// ugly, but see if we can identify some common patterns...
		if(preg_match('~^\\\\\\[([a-zA-Z0-9_]+)(=\(.+?\))?\\\\\\]\((.+)\)\\\\\\[/\\1\\\\\\]$~', $mycode['regex'], $match)) {
			$prop = '';
			if($match[2])
				$prop = '='.easymycode_revconv_pattern(substr($match[2], 1));
			$mycode['regex'] = '['.$match[1].$prop.']'.easymycode_revconv_pattern('('.$match[3].')').'[/'.$match[1].']';
		} else {
			$mycode['regex'] = '{{'.$mycode['regex'].'}}';
		}
		
		$db->update_query('mycode', array('regex' => $db->escape_string($mycode['regex'])), 'cid='.$mycode['cid']);
	}
	//$cache->update('mycode', $custom_mycodes);
	$cache->update_mycode();
}

function easymycode_deactivate() {
	global $cache, $db;
	$query = $db->simple_select('mycode', 'cid,regex');
	$custom_mycodes = array();
	while($mycode = $db->fetch_array($query)) {
		$mycode['regex'] = easymycode_conv($mycode['regex']);
		$db->update_query('mycode', array('regex' => $db->escape_string($mycode['regex'])), 'cid='.$mycode['cid']);
	}
	$cache->update_mycode();
}


function easymycode_conv($emc) {
	static $tr = null;
	if(!isset($tr)) {
		$tr = array();
		foreach($GLOBALS['easymycode_tr'] as $k => &$v)
			$tr[preg_quote($k, '~')] = $v;
	}
	return preg_replace('~\\\\\\{\\\\\\{(.+?)\\\\\\}\\\\\\}~se', 'easymycode_conv_preg(\'$1\')', strtr(preg_quote($emc, '~'), $tr));
}
function easymycode_conv_preg($s) {
	return stripslashes(str_replace('\\"', '"', $s));
}

function easymycode_revconv_pattern($pattern) {
	static $tr = null;
	if(!isset($tr)) $tr = array_flip($GLOBALS['easymycode_tr']);
	foreach($tr as $check => &$replace)
		if($pattern == $check)
			return $replace;
	
	return '{{'.$pattern.'}}';
}

function easymycode_mycodehack() {
	global $cache, $plugins;
	$custom_mycodes = $cache->read('mycode');
	if(empty($custom_mycodes)) return;
	// make a backup copy of the old MyCode cache before we mess with it
	$cache->cache['easymycode_backup'] = $custom_mycodes;
	foreach($custom_mycodes as &$mycode) {
		$mycode['regex'] = easymycode_conv($mycode['regex']);
	}
	// yeah, cache hacking is a little dirty... meh
	$cache->cache['mycode'] = $custom_mycodes;
	
	// ... but to minimize any problems, we'll set it back ASAP
	$plugins->add_hook('parse_message', 'easymycode_restorehack');
}

function easymycode_restorehack() {
	// no way to get the parser object :/  make a guess...
	global $parser, $cache, $plugins;
	if(!is_object($parser) || !($parser instanceof postParser)) return;
	if(empty($parser->mycode_cache)) return;
	
	$cache->cache['mycode'] = $cache->cache['easymycode_backup'];
	unset($cache->cache['easymycode_backup']);
	
	$plugins->remove_hook('parse_message', 'easymycode_restorehack');
}

function easymycode_sandbox() {
	global $mybb;
	$mybb->input['regex'] = easymycode_conv($mybb->input['regex']);
}

function easymycode_langhack() {
	global $plugins;
	$plugins->add_hook('admin_formcontainer_output_row', 'easymycode_langhack2');
}
function easymycode_langhack2(&$pa) {
	global $lang;
	if($pa['title'] != $lang->regular_expression.' <em>*</em>') return;
	$pa['title'] = 'MyCode Pattern <em>*</em>';
	$pa['description'] = 'Enter an expression that will search for a specific combination of characters. You must make sure the expression is valid and safe - no validation is performed. The following wildcards are supported (note, must be in upper case):<ul><li>{ALPHA} - any series of 1 or more alphabetical characters</li><li>{DIGIT} - any series of 1 or more digits</li><li>{NUM} - as above, but allows a negative sign and a single decimal point</li><li>{ALPHADIGIT} - any series of 1 or more digits and/or alphabetical characters</li><li>{CSS} - a CSS value (eg &quot;<em>&lt;span style=\'background-color: #{CSS value}\'&gt;</em>&quot;); note, spaces are not allowed</li><li>{TEXT} - as with {CSS} but allows spaces, commas, dots and the plus sign</li><li>{URL} - any URL in the form of <em>uri://locator</em></li><li>{HTTPURL} - like above, but only allow HTTP/HTTPS URLs</li><li>{EMAIL} - a valid email address</li><li>{COLOR} - any valid HTML colour (textual or #FFFFFF form)</li><li>{SOMETHING} - allows 1 or more series of any characters (use with caution!)</li><li>{ANYTHING} - as with above, but also allows nothing to be entered (use with caution!)</li><li>You can also specify regular expressions by wrapping them up with {{ .. }}<ul><li>Example: <strong><em>{{(apples|oranges|pears)}}</em></strong> allows a choice of either &quot;apples&quot;, &quot;oranges&quot; or &quot;pears&quot;</li></ul></li></ul><strong>'.$lang->example.'</strong> [b]{ANYTHING}[/b]';
}
?>