<commit_before><?php
/**
 * PHPNessusAPI
 *
 * PHP Version 5
 *
 * @category Library
 * @package  PHPNessusAPI
 * @author   <NAME> <@leonjza>
 * @license  MIT
 * @link     @leonjza
 */

namespace Nessus;

/**
 * This class will handle all off the Nessus API related functions
 *
 * @category Library
 * @package  PHPNessusAPI
 * @author   <NAME> <@leonjza>
 * @license  MIT
 * @link     @leonjza
 */
class NessusInterface
{

    public $token = null;
    private $timeout = 30;  // 30 second Request Time
    private $validate_cert = false;
    public static $version = '0.5';

    /**
     * Instantiate the instance
     *
     * @param string $url      The host to which we should connect.
     * @param string $port     The port to which we should connect.
     * @param string $username The username
     * @param string $password The that would be used.
     *
     * @return void
     */
    public function __construct($url, $port, $username, $password)
    {

        // Check that we have a valid URL here.
        if (!filter_var($url, FILTER_VALIDATE_URL))
            throw new \Exception('Invalid URL for NessusInterface Object', 1);

        // Check that we have a valid port here.
        if (!is_numeric($port) || ( 0 > $port ) || ( $port > 65535 ))
            throw new \Exception('Invalid port for NessusInterface Object', 1);

        // Prepare the full url
        $this->url = rtrim($url, '/') . ':' . $port;
        $this->username = $username;
        $this->password = $password;

        // Perform the login and set the token that will be used.
        $this->login();
    }

    /**
     * Class deconstructor used once all references to this Class is cleared. We want to log out cleanly.
     *
     * @return void
     */
    public function __destruct()
    {

        $this->logout();
    }

    /**
     * Check a Requests Response if it was OK
     *
     * @param string $result The result from a cURL request
     *
     * @return void
     */
    private function checkResponse($response)
    {

        // Parse the XML to check the status and read the error if required
        if ($response->status <> 'OK')
            throw new \Exception('Error Processing Request. Error was: ' . $response->contents, 1);
    }

    /**
     * Generate a random sequence number betwee 1 and 65535. This is used for API call synchronization checks.
     *
     * @return int
     */
    private function setSequence()
    {

        return $this->sequence = rand(1, 65535);
    }

    /**
     * Check that the returned sequence number matched the sequence that was sent.
     *
     * @param string $sequence The received sequence number from the API return
     *
     * @return void
     */
    private function checkSequence($sequence)
    {

        if ($sequence <> $this->sequence)
            throw new \Exception(
                'Out of sequence request calling ' . $this->call . '. Got #$sequence instead of #' . $this->sequence,
                1
            );
    }

    /**
     * Log API requests to the Applications General Log
     *
     * @return void
     */
    private function logRequest()
    {

        // This can be configured to do anything you like really.
        return;
    }

    /**
     * Make the Nessus Request
     *
     * @param array   $fields   An array with arguements that accompany the endpoint
     * @param string  $endpoint The API endpoint that should be called
     * @param boolean $raw      Should the response be parsed as json or return raw
     *
     * @return multi Raw response or JSON parsed body
     */
    private function askNessus($endpoint, $fields = array(), $raw = false)
    {

        // Prepare the full API call URL
        $this->call = $this->url . $endpoint;

        // Set a sequence number for later checking as well as the JSON flag,
        // added to the already requested fields
        $fields = array_merge(
            $fields, array(
                'token' => $this->token,
                'seq'   => $this->setSequence(),
                'json'  => 1
            )
        );

        // Configure the options we want to use for this \Request
        $options = array(
            'verify'    => $this->validate_cert,
            'timeout'   => $this->timeout,
            'useragent' => 'PHPNessusNG/' . self::$version
        );

        // Attempt the request. Should a \Requests internal fail, catch and rethrow
        // a modified extemption
        try {

            $response = \Requests::post($this->call, array(), $fields, $options);

        } catch (\Exception $e) {

            throw new \Exception('Error Processing API Request to ' . $this->call . ': ' . $e->getMessage(), 1);
        }

        // Ensure that the request was successfull
        if (!$response->success)
            throw new \Exception('Unsuccessfull Request to ' . $this->call . ': HTTP Code ' . $response->status_code, 1);

        // Check that the response is sane
        $body = json_decode($response->body)->reply;

        // Check the response Sequence Number
        $this->checkSequence($body->seq);

        // Ensure that the response was OK
        $this->checkResponse($body);

        if ($raw)
            // Return the raw response body
            return $response->body;

        else
            // Return the JSON parsed body contents
            return $body->contents;
    }

    /**
     * Login to the Nessus Server preserving the token in this->token
     *<commit_msg>Add response body to errors as apparently Tenable gives 404s out for free<commit_after><?php
/**
 * PHPNessusAPI
 *
 * PHP Version 5
 *
 * @category Library
 * @package  PHPNessusAPI
 * @author   <NAME> <@leonjza>
 * @license  MIT
 * @link     @leonjza
 */

namespace Nessus;

/**
 * This class will handle all off the Nessus API related functions
 *
 * @category Library
 * @package  PHPNessusAPI
 * @author   <NAME> <@leonjza>
 * @license  MIT
 * @link     @leonjza
 */
class NessusInterface
{

    public $token = null;
    private $timeout = 30;  // 30 second Request Time
    private $validate_cert = false;
    public static $version = '0.5';

    /**
     * Instantiate the instance
     *
     * @param string $url      The host to which we should connect.
     * @param string $port     The port to which we should connect.
     * @param string $username The username
     * @param string $password The that would be used.
     *
     * @return void
     */
    public function __construct($url, $port, $username, $password)
    {

        // Check that we have a valid URL here.
        if (!filter_var($url, FILTER_VALIDATE_URL))
            throw new \Exception('Invalid URL for NessusInterface Object', 1);

        // Check that we have a valid port here.
        if (!is_numeric($port) || ( 0 > $port ) || ( $port > 65535 ))
            throw new \Exception('Invalid port for NessusInterface Object', 1);

        // Prepare the full url
        $this->url = rtrim($url, '/') . ':' . $port;
        $this->username = $username;
        $this->password = $password;

        // Perform the login and set the token that will be used.
        $this->login();
    }

    /**
     * Class deconstructor used once all references to this Class is cleared. We want to log out cleanly.
     *
     * @return void
     */
    public function __destruct()
    {

        $this->logout();
    }

    /**
     * Check a Requests Response if it was OK
     *
     * @param string $result The result from a cURL request
     *
     * @return void
     */
    private function checkResponse($response)
    {

        // Parse the XML to check the status and read the error if required
        if ($response->status <> 'OK')
            throw new \Exception('Error Processing Request. Error was: ' . $response->contents, 1);
    }

    /**
     * Generate a random sequence number betwee 1 and 65535. This is used for API call synchronization checks.
     *
     * @return int
     */
    private function setSequence()
    {

        return $this->sequence = rand(1, 65535);
    }

    /**
     * Check that the returned sequence number matched the sequence that was sent.
     *
     * @param string $sequence The received sequence number from the API return
     *
     * @return void
     */
    private function checkSequence($sequence)
    {

        if ($sequence <> $this->sequence)
            throw new \Exception(
                'Out of sequence request calling ' . $this->call . '. Got #$sequence instead of #' . $this->sequence,
                1
            );
    }

    /**
     * Log API requests to the Applications General Log
     *
     * @return void
     */
    private function logRequest()
    {

        // This can be configured to do anything you like really.
        return;
    }

    /**
     * Make the Nessus Request
     *
     * @param array   $fields   An array with arguements that accompany the endpoint
     * @param string  $endpoint The API endpoint that should be called
     * @param boolean $raw      Should the response be parsed as json or return raw
     *
     * @return multi Raw response or JSON parsed body
     */
    private function askNessus($endpoint, $fields = array(), $raw = false)
    {

        // Prepare the full API call URL
        $this->call = $this->url . $endpoint;

        // Set a sequence number for later checking as well as the JSON flag,
        // added to the already requested fields
        $fields = array_merge(
            $fields, array(
                'token' => $this->token,
                'seq'   => $this->setSequence(),
                'json'  => 1
            )
        );

        // Configure the options we want to use for this \Request
        $options = array(
            'verify'    => $this->validate_cert,
            'timeout'   => $this->timeout,
            'useragent' => 'PHPNessusNG/' . self::$version
        );

        // Attempt the request. Should a \Requests internal fail, catch and rethrow
        // a modified extemption
        try {

            $response = \Requests::post($this->call, array(), $fields, $options);

        } catch (\Exception $e) {

            throw new \Exception('Error Processing API Request to ' . $this->call . ': ' . $e->getMessage(), 1);
        }

        // Ensure that the request was successfull
        if (!$response->success)
            throw new \Exception('Unsuccessfull Request to ' . $this->call . ': HTTP Code ' . $response->status_code . ' Raw: ' . $response->raw, 1);

        // Check that the response is sane
        $body = json_decode($response->body)->reply;

        // Check the response Sequence Number
        $this->checkSequence($body->seq);

        // Ensure that the response was OK
        $this->checkResponse($body);

        if ($raw)
            // Return the raw response body
            return $response->body;

        else
            // Return the JSON parsed body contents
            return $body->contents;
    }

    /**
     * Login to the Nessus Server preserving the token in this->token
     *
{'fraction_non_alphanumeric': 0.10822510822510822, 'fraction_numerical': 0.006042568542568543, 'mean_word_length': 1.90744625065548, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 94, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4015687', 'n_tokens_mistral': 3098, 'n_tokens_neox': 2962, 'n_words': 1100}