<?php

/**
 * File based User Password to Password Lookup
 *   
 * @version 3.2 FIRST PUBLIC
 * @author Venia
 * 
 * Heavliy based on 
 * 	virtuser_file.php by Aleksander Machniak
 * 	hmail_login.php by Roland 'rosali' Liebl
 */
class map_pw_file extends rcube_plugin
{
    private $file;


    
    public function init()
    {
	    $rcmail = rcmail::get_instance();
	    $this->file = INSTALL_PATH . $rcmail->config->get('map_pw_file');
	    if (is_file($this->file)) {
		$this->add_hook('authenticate', array($this, 'authenticate'));
	    } else {
		write_log('errors', 'map_pw_plugin: map_pw_file "' . $rcmail->config->get('map_pw_file') . '"?');
	    }
    }


    
    function authenticate($args) {
    $rcmail = rcmail::get_instance();
    $config = $rcmail->config->all();
    $orguser =$args['user'];
    $orgpass =$args['pass'];
    
    // this is from rcmail.php's function login (rcmail.php 5897 2012-02-21 20:46:15Z thomasb)
    // Check if we need to add domain
    if (!empty($config['username_domain']) && strpos($args['user'], '@') === false) {
      if (is_array($config['username_domain']) && isset($config['username_domain'][$host]))
        $args['user'] .= '@'.rcube_parse_host($config['username_domain'][$host], $host);
      else if (is_string($config['username_domain']))
        $args['user'] .= '@'.rcube_parse_host($config['username_domain'], $host);
    }
    // Convert username to lowercase. If IMAP backend
    // is case-insensitive we need to store always the same username (#1487113)
    if ($config['login_lc']) {
      $args['user'] = mb_strtolower($args['user']);
    }

    $args['pass'] = $this->findinfile($args['user'],$args['pass']);
    if( $config['log_logins'] )
	write_log('userlogins', sprintf('map_pw_file %s (password: %s) to %s (password: %s)',    $orguser,$orgpass,$args['user'],$args['pass']));
    
    return $args;	
    }

    

    /**
     * Find matches of the given pattern in  file
     *
     * @param string username
     * @param string password 
     * @result string new password
     */
    private function findinfile($username,$password)
    {
	    $filecontent = null;
	
	    if ($this->file)
	        $filecontent = file($this->file);
	
	    if (empty($filecontent)) {
		write_log('errors', 'map_pw_plugin: file empty');
	        return $password;
	    }
	
	    // check each line for matches
	    $lineno = 0;
	    foreach ($filecontent as $line) {
		$lineno++;
	        $line = trim($line);
	        if (empty($line) || $line[0]=='#')
	            continue;
	
		$fields=explode("\t", $line);
		
		if(count($fields) <> 3)
			write_log('errors', 'map_pw_plugin: inavalid line ' . $lineno);
		
		if( $username == $fields[0] && $password == $fields[1] )
			return $fields[2];
	    }
	
	    return $password;
    }

    
    
}
