<?php
/**
 * Setting up the sympa-soap authentication admin plugin
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     David Pepin <sympa-authors AT cru.fr>
 */

if(!defined('DOKU')) define('DOKU',realpath(dirname(__FILE__).'/../../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU.'lib/plugins/');
require_once(DOKU_PLUGIN.'admin.php');
if(!defined('DOKU_CONFIGLANG')) define('DOKU_CONFIGLANG', realpath(dirname(__FILE__).'/../config/lang/'));
if(!defined('DOKU_SYMPALANG')) define('DOKU_SYMPALANG', realpath(dirname(__FILE__) .'/lang/'));




/**
 * All DokuWiki plugins to extend the admin function
 * need to inherit from this class
 */
class admin_plugin_sympaauth extends DokuWiki_Admin_Plugin {


  /**
   * Return some info about the plugin
   *
   **/
  function getInfo(){

      return array(
		   'author' => 'David Pepin',
		   'email'  => 'sympa-authors AT cru.fr',
		   'date'   => '2008/02/15',
		   'version' => '1.3',
		   'name'   => 'sympaauth',
		   'desc'   => 'Plugin to grant authentication and access rights from a Soap Sympa server',
		   'url'    => 'http://www.sympa.org',
		   );
  }


  /**
   * handle user request
   */
  function handle() {
    if ($_REQUEST['action_'] == 'install') {
      $this->install();
    }
    elseif ($_REQUEST['action_'] == 'uninstall') {
      $this->uninstall();
    }      
  }


  /**
   * Output appropriate html
   *
   */
  function html() {
    global $ID;
    // Display the text about this plugin from "sympaauth/lang/$lang/intro.txt"
    print $this->locale_xhtml('intro');

    // If not installed, it displays the install menu
    // if installed, it displays the uninstall menu
    ptln('<form action_="'.wl($ID).'" method="post">');
    if($this->is_installed()) {
      if($this->is_used()) {
	ptln('<p> ' .$this->getLang('is_used'). '</p>');
      }
      else {
	ptln('<p> '.$this->getLang('uninstall') .' </p>');
	ptln('<p> <input type="hidden" name="action_" value="uninstall" />');
	ptln('    <input type="submit" name="submit" class="button" value="'.$this->getLang('btn_uninstall').'" /> </p>');
      }
    }
    else {
      ptln('<p> '.$this->getLang('install') .' </p>');
      ptln('<p> <input type="hidden" name="action_" value="install" />');
      ptln('    <input type="submit" name="submit" class="button" value="'.$this->getLang('btn_install').'" /> </p>');
    }
    ptln('  <p> <input type="hidden" name="do"     value="admin" />');
    ptln('      <input type="hidden" name="page"   value="sympaauth" /> </p>');
    ptln('</form>');
  }

  /**********************
   * Check if the plugin
   * is installed
   *
   **********************/
  function is_installed() {
    //Check if the file sympa.class.php is in the authenticafion methods directory
    if (!file_exists(DOKU . '/inc/auth/sympa.class.php')) {
      return false;
    }
    
    //Check if the sympa soap server is rightly set up in the file local.php
    if (!$local_handle = fopen(DOKU . '/conf/local.php', 'r')) {
      return false;
    } 
    while (!feof($local_handle)) {
      $line = fgets($local_handle, 1000);
      if(preg_match('!\$conf\[\'plugin\'\]\[\'sympaauth\'\]\[\'sympaSoapService\'\] *= *.*!', $line)) {
	fclose($local_handle);
	return true;
      }
    }
    fclose($local_handle);
    return false;
  }
   

  /**********************
   * Check if the plugin
   * is currently used
   *
   **********************/
  function is_used() {
    //Check if the authentication mode is the sympa-soap server one
    if (!$local_handle = fopen(DOKU . '/conf/local.php', 'r')) {
      return true;
    } 
    while (!feof($local_handle)) {
      $line = fgets($local_handle, 1000);
      if(preg_match('!\$conf\[\'authtype\'\] *= *.*!', $line)) {
	$value = $line;
      }
      if(preg_match('!\$conf\[\'authtype\'\] *= *[\'"]sympa[\'"]!', $value)) return true;
    }
    fclose($local_handle);
    return false;
  }


  /**********************
   * Install the plugin
   *
   **********************/
  function install() {
    // Check if the plugin files are already there, and delete it if it's the case
    if (file_exists(DOKU . '/inc/auth/sympa.class.php')) {
      if(!unlink(DOKU . '/inc/auth/sympa.class.php')) return false;
    }
    // Copy the new ones
    if (!copy(DOKU .'/lib/plugins/sympaauth/files/sympa.class.php', DOKU .'/inc/auth/sympa.class.php')) return false;
    
    // Backup
    if (file_exists(DOKU . '/conf/local.php')) {
      if (!copy(DOKU . '/conf/local.php', DOKU . '/conf/local.php.bak')) return false;
    }
  
    // Open local.php, copy its content to $lines, look for $conf['sympaSoapService'] line(s) delete it (them) and create it
    // just before loading the protected settings.
    // Note that $conf['plugin']['sympaauth']['sympaSoapService'] should be before "@include(DOKU_CONF.'local.protected.php');"
    $i=0;
    //    if (!(feof($local_handle))) { // if the file is not empty, assuming it has a <? 
    if (file_exists(DOKU .'/conf/local.php') && $local_handle = fopen(DOKU . '/conf/local.php', 'r')) { // if the file exists and is readable
      if (!(feof($local_handle))) { // and if the file is not empty, assuming it has a <? 
	do {
	  $lines[$i] = fgets($local_handle, 1000);
	  if(preg_match('!\$conf\[\'plugin\'\]\[\'sympaauth\'\]\[\[\'sympaSoapService\'\] *= *.*!', $lines[$i])) unset($lines[$i--]);
	} while (!(preg_match('!local.protected.php!', $lines[$i++]) || feof($local_handle)) );
	$temp = $lines[--$i];
	$lines[$i++] = '$conf[\'plugin\'][\'sympaauth\'][\'sympaSoapService\'] = \'\';' . "\n";
	$lines[$i] = $temp;
	while (!feof($local_handle)) {
	  $i++;
	  $lines[$i] = fgets($local_handle, 1000);
	  if(preg_match('!\$conf\[\'plugin\'\]\[\'sympaauth\'\]\[\[\'sympaSoapService\'\] *= *.*!', $lines[$i])) unset($line[$i--]);
	}    
      }
      else {
	$lines[$i] = '<?'."\n";
	$lines[++$i] = '$conf[\'plugin\'][\'sympaauth\'][\'sympaSoapService\'] = \'\';' . "\n";
      }
    }
    else { // if the file does not exist
      if (!$local_handle = fopen(DOKU . '/conf/local.php', 'w+')) return false;
      $lines[$i] = '<?'."\n";
      $lines[++$i] = '$conf[\'plugin\'][\'sympaauth\'][\'sympaSoapService\'] = \'\';' . "\n";
    }
    fclose($local_handle);
    
    // Delete local.php (a backup was created few lines before), then copy $lines to a new local.php. Restore backup if failure.
    if(!unlink(DOKU . '/conf/local.php')) return false;
    if (!$local_handle = fopen(DOKU . '/conf/local.php', 'w')) {
      copy(DOKU . '/conf/local.php.bak', DOKU . '/conf/local.php');
      return false;
    }
    foreach ($lines as $line) {
      if (!empty($line) && fwrite($local_handle, $line) == FALSE) {
	fclose($local_handle);
	unlink(DOKU . '/conf/local.php');
	copy(DOKU . '/conf/local.php.bak', DOKU . '/conf/local.php');
	return false;
      }
    }
    
    // Install localization for the config plugin
    return($this->install_langconf());
    
    return(true);
  }


  /***********************
   * Uninstall the plugin
   *
   ***********************/
  function uninstall() {
     // Check if the plugin files are already there, and delete it if it's the case
    if (file_exists(DOKU . '/inc/auth/sympa.class.php')) {
      if(!unlink(DOKU . '/inc/auth/sympa.class.php')) return false;
    }
    if (file_exists(DOKU . '/lib/nusoap.php')) {
      if(!unlink(DOKU . '/lib/nusoap.php')) return false;
    }
    
    if (file_exists(DOKU . '/conf/local.php')) {
      if (!copy(DOKU . '/conf/local.php', DOKU . '/conf/local.php.bak')) return false;
    }
    
    // Open local.php, copy its content to $lines, look for $conf['sympaSoapService'] line(s) and delete it (them)
    if (!$local_handle = fopen(DOKU . '/conf/local.php', 'r')) return false;
    $i = -1;
    while (!feof($local_handle)) {
      $i++;
      $lines[$i] = fgets($local_handle, 1000);
      if(preg_match('!\$conf\[\'plugin\'\]\[\'sympaauth\'\]\[\[\'sympaSoapService\'\] *= *.*!', $lines[$i])) unset($lines[$i--]);
    }
    fclose($local_handle);
    
    // Delete local.php after having backed it up, then copy $lines to a new local.php. Restore backup if failure.
    if(!unlink(DOKU . '/conf/local.php')) return false;
    if (!$local_handle = fopen(DOKU . '/conf/local.php', 'w+')) {
      copy(DOKU . '/conf/local.php.bak', DOKU . '/conf/local.php');
      return false;
    }
    foreach ($lines as $line) {
      if (!empty($line) && fwrite($local_handle, $line) == FALSE) {
	fclose($local_handle);
	unlink(DOKU . '/conf/local.php');
	copy(DOKU . '/conf/local.php.bak', DOKU . '/conf/local.php');
	return false;
      }
    }
    fclose($local_handle);
    
    // Uninstall localization for the config plugin
    return($this->uninstall_langconf());
  }


  /**************************
   * Install the language
   * phrases related to this
   * plugin in the config
   * plugin
   *
   **************************/
  function install_langconf() {
    // Read what are the languages available with the config plugin
    if( !$configlang_h = opendir(DOKU_CONFIGLANG) ) return false;
    while ($lang = readdir($configlang_h)) {
      if ($lang != "." && $lang != ".." && is_dir(DOKU_CONFIGLANG.'/'. $lang)) {
	// Then look for every languages in the sympaauth plugin
	if(is_dir(DOKU_SYMPALANG.'/'. $lang)) {
	  if(!$sympa_file = fopen(DOKU_SYMPALANG .'/' .$lang .'/config_lang.php','r')) return false;
	  $i=0;
	  // And copy the $lang lines from each... assuming that noone would place a ; at the beginning of a new line :-)
	  while (!feof($sympa_file)) {
	    $lines[$i] = fgets($sympa_file, 1000);
	    if(!preg_match('!\$lang\[\'\w{1,}\'\] *= *.*!', $lines[$i])) unset($lines[$i--]);
	    $i++;
	  }
	  fclose($sympa_file);
	  // To the associated language file of the config plugin
	  if(!$config_file= fopen(DOKU_CONFIGLANG .'/'.$lang .'/lang.php','a')) return false;
	  if(!fwrite($config_file,'/* Parameters for authenticating from a sympa server */'."\n")) return false;
	  foreach ($lines as $line) {
	    if(!empty($line) && !fwrite($config_file,$line ."\n")) return false;
	  }
	  fclose($config_file);
	}
      }
    }
    closedir($configlang_h);
    return(true);
  }


  /**************************
   * Uninstall the language
   * phrases from the config
   * plugin
   *
   **************************/
  function uninstall_langconf() {
    if( !$configlang_h = opendir(DOKU_CONFIGLANG) ) return false;
    // Delete every line containing the word "sympa"
    while (false !== ($lang = readdir($configlang_h)) ) {
      if ($lang != "." && $lang != ".." && is_dir(DOKU_CONFIGLANG.'/'. $lang)) {
	if(file_exists(DOKU_CONFIGLANG .'/' .$lang .'/lang.php')){
	  if(!$sympa_file = fopen(DOKU_CONFIGLANG .'/' .$lang .'/lang.php','r')) return false;
	  $i = 0;
	  while (!feof($sympa_file)) {
	    $lines[$i] = fgets($sympa_file, 1000);
	    if(preg_match('!sympa!i', $lines[$i])) unset($lines[$i--]);
	    $i++;
	  }
	  fclose($sympa_file);
	  
	  // Delete lang.php after having backed it up, then copy $lines to a new lang.php. Restore backup if failure.
	  if(!copy(DOKU_CONFIGLANG .'/' .$lang .'/lang.php', DOKU_CONFIGLANG .'/' .$lang .'/lang.php.bak')) return false;
	  if(!unlink(DOKU_CONFIGLANG .'/' .$lang .'/lang.php')) return false;
	  if (!$sympa_file = fopen(DOKU_CONFIGLANG .'/' .$lang .'/lang.php', 'w')) {
	    copy(DOKU . '/conf/local.php.bak', DOKU . '/conf/local.php');
	    return false;
	  }
	  foreach ($lines as $line) {
	    if (!empty($line) && fwrite($sympa_file, $line) == FALSE) {
	      copy(DOKU . '/conf/local.php.bak', DOKU . '/conf/local.php');
	      return false;
	    }
	  }
	  fclose($sympa_file);
	}
      }
    }
  }


}