<?php
/**
 * Givemeyouremail Plugin: allows visitors to give their email
 *
 * @license	GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author	 Anthony Dahanne <anthony.dahanne@gmail.com>    
 */
 
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');
 
/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_givemeyouremail extends DokuWiki_Syntax_Plugin {
	/**
	* return some info
	*/
  function getInfo(){
	return array(
		'author' => 'Anthony Dahanne',
		'email'  => 'anthony.dahanne@gmail.com',
		'date'   => '2009/01/01',
		'name'   => 'GiveMeYourEmail Plugin',
		'desc'   => 'Allow visitors to give their email adress',
		'url'	=> 'http://blog.dahanne.net',
	);
  }

  function getType(){ return 'substition';}
  function getPType(){ return 'block';}
  function getSort(){ return 4343; }
  
	/**
	* Connect pattern to lexer
	*/
  function connectTo($mode){
	$this->Lexer->addSpecialPattern('<givemeyouremail>', $mode, 'plugin_givemeyouremail');
  }

	/**
	* Handle the match
	*/
  function handle($match, $state, $pos, &$handler){
	$match = substr($match, 8, -9);  // strip markup
	list($title, $options) = preg_split('/>/u', $match, 2);
	list($leftstr, $rightstr) = split('\|', $title);
	if ($rightstr == "") {
		$title = $leftstr;
		$disable = "";
		$single = "";
		$login = "";
	}
	else {
		$title = $rightstr;
		$disable = strpos($leftstr, "disable");
		$single = strpos($leftstr, "single");
		$login = strpos($leftstr, "login");
	}
	if (!$options){
		$options = $title;
		$title   = NULL;
	}
	$options = explode('^', $match);
	
	$c = count($options);
	for ($i = 0; $i < $c; $i++){
		$options[$i] = trim($options[$i]);
	}
	
	return array(trim($title), $options, $disable, $single, $login);
  }
	/**
	* Create output
	*/
  function render($mode, &$renderer, $data) {
	if ($mode == 'xhtml'){
		global $lang;

		$options = $data[1];
		$c = count($options)-1;
		$title   = $renderer->_xmlEntities($data[0]);
		$disable   = $renderer->_xmlEntities($data[2]);
		$single   = $renderer->_xmlEntities($data[3]);
		$login   = $renderer->_xmlEntities($data[4]);
		$dID	 = md5($title);
				  
		// prevent caching to ensure the poll results are fresh
		$renderer->info['cache'] = false;
				  
		// get givemeyouremail file contents
		$dfile   = metaFN($dID, '.givemeyouremail');
		$old_dfile   = metaFN(md5(cleanID($title)), '.givemeyouremail');
		// rename old meta File
		if (file_exists($old_dfile)) {
			rename($old_dfile, $dfile);
		}
		$givemeyouremail  = unserialize(@file_get_contents($dfile));

		// output the givemeyouremail
		$renderer->table_open();
		if ($title){
			$renderer->tablerow_open();
			$renderer->tableheader_open($c);
			$renderer->doc .= $title;
			$renderer->tableheader_close();
			$renderer->tablerow_close();
		}
		$renderer->tablerow_open();
		$renderer->tableheader_open();
		$renderer->doc .= $lang['email'];
		$renderer->tableheader_close();
		for ($i = 1; $i < $c; $i++){
			$renderer->tableheader_open();
			$renderer->doc .= $renderer->_xmlEntities($options[$i]);
			$renderer->tableheader_close();
		}
		$renderer->tablerow_close();
					
					
		$email_adress_valid = true;			
		if ($submit = $_REQUEST[$dID.'-submit']){
		// user has just entered his email address, let's add it
			$user = trim($_REQUEST['fullname']);
			if ($this->_isValidEmailAdress($user)){			      
			      $givemeyouremail .= $user.';';
			      //we append this email to the export list
			      @file_put_contents(getcwd().'/lib/plugins/givemeyouremail/adresses.txt',$givemeyouremail);
			}else{
			  $email_adress_valid=false;
			}
			$fh = fopen($dfile, 'w');
			fwrite($fh, serialize($givemeyouremail));
			fclose($fh);
		}

		// display results
		if(!empty($user)){
		  $renderer->doc .= $this->_givemeyouremailResults($givemeyouremail, $options,$email_adress_valid,$user);
		}
		// display entry form
		if ($disable=="") {
			$renderer->doc .= $this->_givemeyouremailForm($c, $dID, $givemeyouremail, $options, $login, $single);
		}
		//if user is admin, print the addresses list		
		if (auth_quickaclcheck($ID) >= AUTH_ADMIN) {
			$renderer->doc.= $this->_givemeyouremailReadAllAddresses($dfile);
		}
		$renderer->table_close();
		
		return true;
	  }

	return false;
	}
  
  function _isValidEmailAdress($email_adress){
      $pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/';
      if(empty($email_adress) || !preg_match($pattern,$email_adress)){
	return false;
      }
      return true;
  }
  
  
  function _givemeyouremailResults($givemeyouremail, $options, $email_adress_valid,$last_email_adress){

	$message_not_ok = 'L\'adresse email que tu as saisi :'.$last_email_adress.' n\'était pas valide';
	$message_ok = 'Ton adresse : '.$last_email_adress.' est bien enregistrée.';

	//was the previous email adress filled in ok? print the message!
	if(!$email_adress_valid){
	  $ret.= '<tr><td class="givemeyouremail_warning">'.$this->getLang('email_not_ok').' : '.$last_email_adress.'</td></tr><script>window.alert("'.$this->getLang('email_not_ok').'");</script>';
	}else{
	  $ret.='<tr><td class="givemeyouremail_ok">'.$this->getLang('email_ok').' : '.$last_email_adress.'</td></tr><script>window.alert("'.$this->getLang('email_ok').'");</script>';
	}
	return $ret;
  }

	function _givemeyouremailReadAllAddresses($dfile){
		$email_addresses= unserialize(@file_get_contents($dfile));
//getcwd().'/lib/plugins/givemeyouremail/adresses.txt');
		$addresses_array = explode(';',$email_addresses);
		foreach($addresses_array as $address){
			$ret.='<tr><td>'.$address.'</td></tr>';
		}
		$ret.='<tr><td><textarea>'.$email_addresses.'</textarea></td></tr>';
		return $ret;
	}

  
  function _givemeyouremailForm($n, $dID, $givemeyouremail, $options, $login, $single){
	global $lang;
	global $ID;
	global $INFO;

	$count = array();

	$ret = '<form id="givemeyouremail__form" method="post" action="'.script().
		'" accept-charset="'.$lang['encoding'].'"><tr>'.
		'<input type="hidden" name="do" value="show" />'.
		'<input type="hidden" name="id" value="'.$ID.'" />';
	$ret .= '<td class="rightalign"><input type="text" name="fullname" /></td>';
	$ret .= '</tr><tr><td class="centeralign">'.
		'<input class="button" type="submit" name="'.$dID.'-submit" '.
		'value="'.$this->getLang('btn_submit').'" />'.
		'</td></tr></form>';
	return $ret;
  }
}

?>
