<?php
/**
 * DokuGource Plugin: extract gource log from the wiki
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Etienne Meleard <etienne.meleard@free.fr>
 * 
 * 2010/05/19 : Creation
 */

// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'admin.php');

/**
 * All DokuWiki plugins to extend the admin function
 * need to inherit from this class
 */
class admin_plugin_dokugource extends DokuWiki_Admin_Plugin {
	var $colors = array();
	var $log = array();
	var $from = -1;
	var $ns = '';
	
	// return some info
	function getInfo() {
		return confToHash(dirname(__FILE__).'/INFO');
	}
	
	function __construct() {
		global $conf;
		$this->disabled = (isset($conf['pluginfarm']) && ($conf['pluginfarm'] == 0));
	}
	
	/**
	 * Return prompt for admin menu
	 * @param $l language identifier
	 * @return nothing if not in farmer context, menu title otherwise
	 */
	function getMenuText($l) {
		if(!$this->disabled) return 'Gource Log';
		return '';
	}
	
	/**
	 * Return sort order for position in admin menu
	 * @return integer
	 */
	function getMenuSort() {
		return 20;
	}
	
	/**
	 * Handle requests
	 */
	function handle() {
		global $conf;
		
		// Do nothing if disabled / not installed
		if($this->disabled) return;
		
		if(array_key_exists('download', $_GET)) if(@file_exists($conf['metadir'].'gource.log')) {
			$f = @file_get_contents($conf['metadir'].'gource.log');
			header('Content-Transfer-Encoding: binary');
			header('Content-Length: '.strlen($f));
			header('Content-Disposition: attachment; filename="gource.log"');
			header('Expires: 0');
			header('Cache-Control: no-cache, must-revalidate');
			header('Pragma: no-cache');
			echo $f;
			exit();
 		}
 		
 		if(isset($_POST['dokugource_savecnf'])) {
			if($fp = fopen(DOKU_CONF.'/gource.cnf.php', 'w')) {
				fwrite($fp, "<?php exit(); ?>\n\n".trim($_POST['dokugource_cnf']));
				fclose($fp);
			}
		}
 		
 		if(isset($_POST['dokugource_generate'])) {
			$this->from = (isset($_POST['dokugource_from']) && !empty($_POST['dokugource_from'])) ? strtotime($_POST['dokugource_from']) : 0;
			if($this->from === false) $this->from = 0;
			
			$this->ns = (isset($_POST['dokugource_ns']) && !empty($_POST['dokugource_ns'])) ? $_POST['dokugource_ns'] : '';
			if($this->ns) {
				$this->ns = str_replace('/', ':', trim($this->ns, '/:'));
				if(!@is_dir($conf['datadir'].'/'.str_replace(':', '/', $this->ns).'/')) {
					if(@is_file($conf['datadir'].'/'.str_replace(':', '/', $this->ns).'.txt')) {
						$this->ns = preg_replace('`^(.*)\:[^\:]+$`', '$1', $this->ns);
					}
				}
			}
			
			$this->colors = array();
			foreach(preg_split('`\n+`', trim(@file_get_contents($conf['metadir'].'/gource.colors'))) as $l) {
				if(!$l) continue;
				$l = preg_split('`\s+`', $l, 2);
				$this->colors[$l[0]] = $l[1];
			}
			
			$strip = explode(':', $this->ns);
			array_pop($strip);
			$strip = count($strip) ? strlen(implode(':', $strip)) : 0;
			$this->crawl($conf['metadir'].($this->ns ? '/'.str_replace(':', '/', $this->ns) : ''), $strip, $this->from);
			sort($this->log);
			
			if($fp = fopen($conf['metadir'].'gource.log', 'w')) {
				fwrite($fp, trim(implode("\n", $this->log)));
				fclose($fp);
			}
		}
		
		return true;
	}
	
	function color($p) {
		$ns = preg_replace('`^(.*\:)[^\:]+$`', '$1', $p);
		if(isset($this->colors[$p])) return $this->colors[$p];
		if(isset($this->colors[$ns])) return $this->colors[$ns];
		
		$this->colors[$p] = sprintf('%02X%02X%02X', rand(0, 255), rand(0, 255), rand(0, 255));
		return $this->colors[$p];
	}
	
	function crawl($p, $strip, $from) {
		if(!@is_dir($p)) return;
		foreach(scandir($p) as $i) {
			if($i == '.' || $i == '..') continue;
			if(is_file($p.'/'.$i)) if(preg_match('`\.changes$`', $i)) {
				foreach(preg_split('`\n+`', trim(@file_get_contents($p.'/'.$i))) as $l) {
					if(!$l) continue;
					if(preg_match('`^\s*([0-9]+)\s+([^\s]+)\s+([a-z]{1,3})\s+([^\s]+)\s+([^\s]+)`i', $l, $m)) {
						if((int)$m[1] < $from) continue;
						if(preg_match('`(C|cc|sc)`i', $m[3])) {
							$m[3] = 'A';
						}elseif(preg_match('`(D|dc|hc)`i', $m[3])) {
							$m[3] = 'D';
						}else{
							$m[3] = 'M';
						}
						$id = str_replace(':', '/', $m[4]);
						if($strip) $id = trim(substr($id, $strip), '/:');
						$this->log[] = $m[1].'|'.$m[5].'|'.$m[3].'|'.$id.'|'.$this->color($m[4]);
					}
				}
			}
			
			if(is_dir($p.'/'.$i)) $this->crawl($p.'/'.$i, $strip, $from);
		}
	}
	
	/**
	 * Output appropriate html
	 */
	function html() {
		global $conf;
		
		// Do nothing if disabled / not installed
		if($this->disabled) return;
		
		ptln('<h1>Gource Log</h1>');
		ptln('<form action="?do=admin&amp;page=dokugource" method="post">');
		ptln('	Start : <input type="text" name="dokugource_from" value="'.date('Y-m-d H:i:s', ($this->from >= 0) ? $this->from : (time() - 5*24*3600)).'" /><br />');
		ptln('	Namespace : <input type="text" name="dokugource_ns" value="'.($this->ns ? $this->ns : '').'" /><br />');
		ptln('	<input type="submit" name="dokugource_generate" value="OK" />');
		ptln('</form>');
		
		if(isset($_POST['dokugource_generate'])) {
			if(@file_exists($conf['metadir'].'gource.log')) ptln('<a href="?do=admin&amp;page=dokugource&amp;download">Download</a>');
			ptln('<textarea style="width:95%;margin:0 auto" rows="20">');
			ptln(implode("\n", $this->log));
			ptln('</textarea>');
		}
		
		ptln('<h2>Trusted keys autorized namespaces pairs</h2>');
		ptln('<form action="?do=admin&amp;page=dokugource" method="post">');
		ptln('	<textarea rows="10" name="dokugource_cnf">'.preg_replace('`\s*<\?php[^\?]+\?>\s*`', '', @file_get_contents(DOKU_CONF.'/gource.cnf.php')).'</textarea><br />');
		ptln('	<input type="submit" name="dokugource_savecnf" value="OK" />');
		ptln('</form>');
	}
}

?>
