'''
importResults.py

Copyright 2006 Andres Riancho

This file is part of w3af, w3af.sourceforge.net .

w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

w3af is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with w3af; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

'''

import core.controllers.outputManager as om

# options
from core.data.options.option import option
from core.data.options.optionList import optionList

from core.controllers.basePlugin.baseDiscoveryPlugin import baseDiscoveryPlugin
from core.data.request.frFactory import createFuzzableRequestRaw
from core.controllers.w3afException import w3afRunOnce


class importResults(baseDiscoveryPlugin):
    '''
    Import URLs found by other tools.
    @author: Andres Riancho ( andres.riancho@gmail.com )
    '''
    def __init__(self):
        baseDiscoveryPlugin.__init__(self)

        # Internal variables
        self._exec = True
        
        # User configured parameters
        self._input_file = ''

    def discover(self, fuzzableRequest ):
        '''
        Read the input file, and create the fuzzableRequests based on that information.
        
        @parameter fuzzableRequest: A fuzzableRequest instance that contains
                                    (among other things) the URL to test. It ain't used.
        '''
        if not self._exec:
            # This will remove the plugin from the discovery plugins to be runned.
            raise w3afRunOnce()

        else:
            self._exec = False
            res = []

            if self._input_file != '':
                try:
                    file_handler = file( self._input_file )
                except Exception, e:
                    msg = 'An error was found while trying to read the input file: "'
                    msg += str(e) + '".'
                    om.out.error( msg )
                else:
                    for line in file_handler:
                        obj = self._obj_from_file( line.strip() )
                        if obj:
                            res.append( obj )
                        
        return res
    
    def _obj_from_file( self, csv_line ):
        '''
        @return: A fuzzableRequest based on the csv_line.
        '''
        try:
            method, uri, postdata = csv_line.split(',',2)
        except ValueError, value_error:
            msg = 'The file format is incorrect, an error was found while parsing: "'
            msg += csv_line + '". Exception: "' + str(value_error) + '".'
            om.out.error( msg )
        else:
            # Create the obj based on the information
            return createFuzzableRequestRaw( method, uri, postdata, {} )
    
    def getOptions( self ):
        '''
        @return: A list of option objects for this plugin.
        '''
        d1 = 'Define the input file from which to create the fuzzable requests'
        h1 = 'The input file is comma separated and holds the following data:'
        h1 += ' HTTP-METHOD,URI,POSTDATA'
        o1 = option('input_file', self._input_file, d1, 'string', help=h1)
        
        ol = optionList()
        ol.add(o1)
        return ol
        
    def setOptions( self, optionsMap ):
        '''
        This method sets all the options that are configured using the user interface 
        generated by the framework using the result of getOptions().
        
        @parameter optionsMap: A dictionary with the options for the plugin.
        @return: No value is returned.
        ''' 
        self._input_file = optionsMap['input_file'].getValue()
        
    def getPluginDeps( self ):
        '''
        @return: A list with the names of the plugins that should be runned before the
        current one.
        '''
        return []
    
    def getLongDesc( self ):
        '''
        @return: A DETAILED description of the plugin functions and features.
        '''
        return '''
        This plugin serves as an entry point for the results of other tools that search for URLs.
        The plugin reads an input file that is comma separated and holds the following data:
        HTTP-METHOD,URI,POSTDATA.
        
        One configurable parameter exists:
            - input_file
        '''
