#!/usr/bin/env python
"""
malwareScanWordPress.py

Copyright 2013 Daniel Maldonado

This file is part of WPHardening project.

WPHardening 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, either version 3 of the License, or
(at your option) any later version.

WPHardening 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 WPHardening.  If not, see <http://www.gnu.org/licenses/>.

"""

import os
import re
import logging
from lib.termcolor import colored


class malwareScanWordPress():
    """
    This class seeks Malware Scan

    :author: Daniel Maldonado (daniel_5502@yahoo.com.ar)
    """
    def __init__(self, directory, verbose=False):
        """
        :param directory: Absolute path of the directory to check.
        :param verbose: Mode verbose.
        """
        self.directory = os.path.abspath(directory)
        self.mode_verbose = verbose
        self.count = 1

    def getCount(self):
        """
        :return: count
        """
        return self.count

    def setCount(self):
        """
        :return: None
        """
        self.count += 1

    def search(self, content, r, wpfile):
        """
        :return: None
        """
        line = 1
        for i in content:
            matchObj = re.search(
                "(file_get_contents.*|curl_exec.*|popen.*|proc_open.*|" +
                "unserialize.*|base64_decode.*|base64_encode.*|shell_exec.*|" +
                "passthru.*|ob_get_contents.*|curl_init.*|readfile.*|" +
                "fsockopen.*|pfsockopen.*|file_put_contents.*)",
                i)
            if matchObj:
                logging.info(
                    os.path.join(r, wpfile) + " - " + matchObj.group()
                )
                print colored(
                    "\n\t" + str(self.getCount()) + ") " +
                    os.path.join(r, wpfile) + " - " + matchObj.group() +
                    " in line " + str(line),
                    'red'
                )
                self.setCount()
            line += 1

    def scan(self):
        """
        :return: None
        """
        print colored('\nMalware Scan', 'yellow')
        for r, d, f in os.walk(self.directory):
            for wpfile in f:
                scanfile = open(os.path.join(r, wpfile), "r")
                content = scanfile.readlines()
                scanfile.close()
                self.search(content, r, wpfile)
