<?php
/**
 * Google Ads for DokuWiki
 * 
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Bernd Zeimetz <bernd@bzed.de>, based on code by Terence J. Grant<tjgrant@tatewake.com>
 */

$gads_loaded = 0;

function gads_load()
{
	global $gads_loaded, $gads_settings;

	$gads_file = dirname(__FILE__).'/local_pref.php';

	if ($gads_loaded == 0)
	{
		if(file_exists($gads_file))
		{
			include($gads_file);

			$gads_loaded = 1;
		}
	}
}

function gads_write($fp, $name, $val)
{
	fwrite($fp, '$gads_settings[\''.$name.'\'] = \''.$val.'\';'."\n");
}

function gads_save()
{
	global $gads_loaded, $gads_settings;

	$gads_file = dirname(__FILE__).'/local_pref.php';

	if (is_writable($gads_file) || is_writable(dirname(__FILE__)))
	{
		$fp = fopen($gads_file, "w");
		fwrite($fp, '<?php'."\n// This file is automatically generated\n");
		//gads_write($fp, 'code', $gads_settings['code']);
		gads_write($fp, 'enabled', $gads_settings['enabled']);
		gads_write($fp, 'debug', $gads_settings['debug']);
		gads_write($fp, 'dontcountadmin', $gads_settings['dontcountadmin']);
		gads_write($fp, 'dontcountusers', $gads_settings['dontcountusers']);

		gads_write($fp, 'google_ad_client', $gads_settings['google_ad_client']);
		gads_write($fp, 'google_color_border', $gads_settings['google_color_border']);
		gads_write($fp, 'google_color_bg', $gads_settings['google_color_bg']);
		gads_write($fp, 'google_color_link', $gads_settings['google_color_link']);
		gads_write($fp, 'google_color_url', $gads_settings['google_color_url']);
		gads_write($fp, 'google_color_text', $gads_settings['google_color_text']);

		fclose($fp);

		ptln('<div class="success">'.'Google Adsense pref saved successfully.'.'</div>');
	}
	else
	{
		ptln('<div class="error">'.'Google Adsense pref is not writable by the server.'.'</div>');
	}
}

// this function should be included within some templates
function gads_code($id, $styles=NULL)
{
        global $gads_loaded, $gads_settings, $conf;

	$styles_array = gads_getstyle($styles);

	$code = gads_showADS($id, $styles_array);

	if ($code)
	{
		ptln($code);
		ptln('<div class="clearer">&nbsp;</div>');
	}
}

function gads_getstyle($str) {
	if (!strlen($str)) return array();

	$styles = array();

	$tokens = preg_split('/\s+/', $str, 9);                 // limit is defensive
	foreach ($tokens as $token) {
		if (preg_match('/^\d*\.?\d+(%|px|em|ex|pt|cm|mm|pi|in)$/', $token)) {
			$styles['width'] = $token;
			continue;
		}

		// restrict token (class names) characters to prevent any malicious data
		if (preg_match('/[^A-Za-z0-9_-]/',$token)) continue;
		$styles['class'] = (isset($styles['class']) ? $styles['class'].' ' : '').$token;
	}

	return $styles;
}

function gads_boxopen($style, $title=NULL)
{
	if( $title )
	{
		$class = "class='ads debug" . (isset($style['class']) ? ' '.$style['class'] : '') . "'";
	}
	else
	{
                $class = "class='ads" . (isset($style['class']) ? ' '.$style['class'] : '') . "'";
	}
	$style = isset($style['width']) ? " style='width: {$style['width']};'" : '';

	$html = "<div $class$style>\n";

	if( $title )
	{
		$html .= "  <p class='ads_title'>" . $title . "</p>\n";
	}

	return $html;
}

function gads_boxcontent($content)
{
	return "  <div class='ads_content'>" . $content . "\n  </div>\n";
}

function gads_boxclose()
{
	$html = "</div>\n";

	return $html;
}

function gads_showADS($id, $style=NULL)
{
	global $gads_loaded, $gads_settings, $conf;

	//FIXME: hardcoded value !!
	$id = 'googleads:' . $id;

	$obj = '';

	if( !$gads_settings['enabled'] )
	{
		$obj .= "\n" . '<!-- Google ADS DISABLED -->' . "\n";
	}
	elseif( $gads_settings['dontcountadmin'] && auth_isadmin() )
	{
		$obj .= "\n" . '<!-- Google ADS DISABLED for SuperUser -->' . "\n";
	}
	elseif( $gads_settings['dontcountusers'] && $_SERVER['REMOTE_USER'] )
	{
		$obj .= "\n" . '<!-- Google ADS DISABLED for NormalUser -->' . "\n";
	}
	elseif( $gads_settings['debug'] && auth_isadmin() )
	{
		$obj .= "\n" . '<!-- google_ads \'' . $id . '\' start -->' . "\n";
		$obj .= gads_boxopen($style, $id);
                $obj .= gads_boxcontent(gads_getADS($id));
		$obj .= gads_boxclose();
		$obj .= "\n" . '<!-- google_ads \'' . $id . '\' end -->' . "\n";
	}
	else
	{
		$obj .= "\n" . '<!-- google_ads \'' . $id . '\' start -->' . "\n";
		$obj .= gads_boxopen($style);
                $obj .= gads_boxcontent(gads_getADS($id));
		$obj .= gads_boxclose();
		$obj .= "\n" . '<!-- google_ads \'' . $id . '\' end -->' . "\n";
	}

	return $obj;
}

function gads_getADS($id)
{
	global $gads_loaded, $gads_settings;

	$obj = '';

	//check permission
	$perm = auth_quickaclcheck($id);
	if ($perm < AUTH_READ) return false;
					
	//Read embeded page
	$page = io_readfile(wikiFN($id));

	//set pattern to be replaced
	$patterns[0] = '/<default_client>/';
        $replacements[0] = $gads_settings['google_ad_client'];
	$patterns[1] = '/<default_border>/';
        $replacements[1] = $gads_settings['google_color_border'];
        $patterns[2] = '/<default_bg>/';
        $replacements[2] = $gads_settings['google_color_bg'];
        $patterns[3] = '/<default_link>/';
        $replacements[3] = $gads_settings['google_color_link'];
        $patterns[4] = '/<default_url>/';
        $replacements[4] = $gads_settings['google_color_url'];
        $patterns[5] = '/<default_text>/';
        $replacements[5] = $gads_settings['google_color_text'];

	//do replace
	$obj .= preg_replace($patterns, $replacements, $page);

	return $obj;
}

//Load settings
gads_load();
