###############################################################################
# Local Security Check Automation Framework
#
# Authors:
# Veerendra GG <veerendragg@secpod.com>
#
# Revision 1.0
# Date Written: 01/23/2009
#
# Copyright:
# Copyright (c) 2009 SecPod , http://www.secpod.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2
# (or any later version), as published by the Free Software Foundation.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
###############################################################################

import sys

class MantisReporter:
    """
    Report the generated NVT as a task in Mantis
    """

    def __init__(self):
        self.host = ''
        self.db_name = ''
        self.mysql_passwd = ''
        self.mysql_user_name = ''
        self.mantis_user_name = ''

        self.summary = ''
        self.description = ''
        self.project_name = ''
        self.aditional_info = ''

        self.conn = None
        self.cursor = None
        self.category = 'new'
        self.steps_to_reproduce = ""

        # status constant values = '10:new, 20:feedback, 30:acknowledged,
        #                           40:confirmed, 50:assigned, 80:resolved,
        #                           90:closed'
        self.status = 30

        # severity constant values = '10:none, 20:low, 30:medium, 40:high,
        #                            50:critical'
        self.severity = 50


    def _closeDbConn(self, debug=0):
        """ Closing database connection
        """
        if self.cursor:
            if debug:
                print "Closing Cursor..."
            self.cursor.close()
        self.cursor = None

        if self.conn:
            if debug:
                print "Closing Connection..."
            self.conn.close()
        self.conn = None

        
    def _openDbConn(self, debug=0):
        """ Establish a mysql database connection
        """
        import MySQLdb
      
        if not self.host:
            self.host = 'localhost'

        if not (self.mysql_user_name and self.mysql_passwd and self.db_name):
            print "Required vaules are missing, to connect to database"
            sys.exit(0)

        if not self.conn:
            try:
                print "Creting Database connection"
                self.conn = MySQLdb.connect(host = self.host, user=self.mysql_user_name,
                                            passwd=self.mysql_passwd, db=self.db_name)

                self.cursor = self.conn.cursor ()
            except Exception, msg:
                print "Failed to connect database"
                sys.exit(msg)


    def exec_query(self, query, only_execute=True, debug=0):
        """ Execute query, if only_execute=False,
            else execute query and fetchall()
        """
        if not self.conn:
            # Open DB Conn
            self._openDbConn(debug)

        if debug:
            print "executing query : \n(%s)" %(query)

        ## Execute query
        value = self.cursor.execute(query)
        if not value:
            return False
        elif only_execute:
            return value
 
        if debug:
            print "Fetching data..."

        value = self.cursor.fetchall()

        return value


    def createMantisTask(self, debug=0):
        """ Creates a mantis task in developemnt complete state
        """
        ## Insert description and additional info
        query_string = "insert into mantis_bug_text_table (description, steps_to_reproduce, additional_information) values ('%s', '%s', '%s')" % (self.description.replace("'", "&qt"), self.steps_to_reproduce, self.aditional_info.replace("'", "&qt").replace('"', '&qt').replace("NULL", ""))

        bug_text_id = self.exec_query(query_string, debug=debug)

        bug_text_id = int(self.conn.insert_id())
        if debug:
            print "Generated Bug ID : ", bug_text_id

        if not bug_text_id:
            print "ERROR: bug_text_id is not found"
            return False

        ## Get user_id from mantis_user_table
        only_execute = False
        query_string = "select id from mantis_user_table where username='%s'" % self.mantis_user_name
        user_id = self.exec_query(query_string, only_execute, debug)
        if user_id:
            user_id = user_id[0][0]
        else:
            print "ERROR: user_id is not found"
            return False

        ## Get project_id & category value from mantis_project_table
        query_string = "select id from  mantis_project_table where name='%s'" % self.project_name
        project_id = self.exec_query(query_string, only_execute, debug)
        if project_id:
            project_id = project_id[0][0]
        else:
            print "ERROR: project_id are not found"
            return False

        import time
        (year, month, date, hour, min, sec, a, b, c ) = time.localtime()
        date_time = str(year) + "-" + str(month) + "-" + str(date) + " " + str(hour)+ ":" + str(min) + ":" + str(sec)
        date_submitted = date_time
        last_updated = date_time

        ## Execute complete query
        comp_query = "insert into %s (project_id, reporter_id, status, category, bug_text_id, summary, severity, date_submitted, last_updated) values (%s, %s, %s, '%s', %s, '%s', %s, '%s', '%s')" % ('mantis_bug_table', project_id, user_id, self.status, self.category, bug_text_id, self.summary, self.severity, date_submitted, last_updated)
        if self.exec_query(comp_query,  debug=debug):
            return bug_text_id 
        else:
            print "ERROR: Failed to insert a record"

        return False


    def execute(self, debug=0):
        """ Creates database connection and creates mantis task
        """
        try:
            mantis_id = self.createMantisTask(debug)

            if mantis_id:
                self.conn.commit()

            self._closeDbConn(debug)

            if mantis_id:
                if debug:
                    print "Successfully created with mantis task ID : ", mantis_id
                return mantis_id
            else:
                return False

        except Exception, msg:
            self._closeDbConn(debug)
            print "Exception, while creating mantis task..."
            sys.exit(msg)

