<commit_before><?php

/**
 * This package is capable of interfacing with the open source Asterisk PBX via 
 * its built in Manager API.  This will allow you to execute manager commands
 * for administration and maintenance of the server.
 * 
 * Copyright (c) 2008, <NAME> <<EMAIL>>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * - Neither the name of the author nor the names of its 
 *   contributors may be used to endorse or promote products derived from 
 *   this software without specific prior written permission.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * PHP version 5
 *
 * @category  Net
 * @package   Net_AsteriskManager
 * @author    <NAME> <<EMAIL>>
 * @copyright 2008 <NAME>
 * @license   http://www.debian.org/misc/bsd.license New BSD License
 * @link      http://pear.php.net/pepr/pepr-proposal-show.php?id=543
 */

/**
 * PEAR Exception class is used for exception handling
 */
require_once 'PEAR/Exception.php';

/**
 * Class for accessing the Asterisk Manager interface 
 * {@link http://www.voip-info.org/wiki/view/Asterisk+manager+API}
 * 
 * @category Net
 * @package  Net_AsteriskManager
 * @author   <NAME> <<EMAIL>>
 * @license  http://www.debian.org/misc/bsd.license New BSD License
 * @link     http://pear.php.net/pepr/pepr-proposal-show.php?id=543
 */
class Net_AsteriskManager
{
    /**
     * The Asterisk server which will recieve the manager commands 
     * @access public
     * @var string
     */
    public $server;

    /**
     * The port to use when connecting to the Asterisk server
     * @access public
     * @var integer
     */
    public $port = 5038;

    /**
     * The opened socket to the Asterisk server
     * @access private 
     * @var object
     */
    private $_socket;

    /**
     * Class constructor
     * 
     * @param array $params Array of the parameters used to connect to the server
     * <code>
     * array(
     *       'server' => '127.0.0.1'    // The server to connect to
     *       'port' => '5038',          // Port of manager API
     *       'auto_connect' => true     // Autoconnect on construction?
     *      );
     * </code>
     * 
     * @uses AsteriskManager::$server
     * @uses AsteriskManager::$port
     * @uses AsteriskManager::$_socket
     */
    public function __construct($params = array())
    {
        if (!isset($params['server'])) {
            throw new PEAR_Exception('You must provide a server');
        }
        $this->server = $params['server'];

        if (isset($params['port'])) {
            $this->port = $params['port'];
        }

        if (isset($params['auto_connect'])) {
            $this->connect();
        }
    }

    /**
     * If not already connected then connect to the Asterisk server
     * otherwise close active connection and reconnect
     *
     * @return bool
     */
    public function connect()
    {
        if ($this->_socket) {
            $this->close();
        }

        if ($this->_socket = fsockopen($this->server, $this->port)) {
            stream_set_timeout($this->_socket, 3);
        } else {
            throw new PEAR_Exception("Could not establish connection to "
            ."{$this->server} on {$this->port}");
        }
    }

    /**
     * Login into Asterisk Manager interface given the user credentials
     *
     * @param string $username The username to access the interface
     * @param string $password The password defined in manager interface of server
     * 
     * @return bool
     */
    public function login($username, $password)
    {
        fputs($this->_socket, "Action: login\r\nUsername: {$username}\r\n"
                               ."Secret: {$password}\r\<PASSWORD>");
        $response = stream_get_contents($this->_socket);
        if (strpos($response, "Message: Authentication accepted") != false) {
            return true;
        } else {
            throw new PEAR_Exception('Authentication failed');
        }
    }

    /**
     * Logout of the current manager session attached to $this::socket
     * 
     * @return bool
     */
    public function logout()
    {
        if (!$this->_socket) { 
            throw new PEAR_Exception('No socket detected');
        }
        
        fputs($this->_socket, "Action: Logoff\r\n\r\n");

        return true;
    }

    /**
     * Close the connection
     *
     * @return bool
     */
    public function close()
    {
        if (!$this->_socket) {
            throw new PEAR_Exception('No socket detected');
        }

        return fclose($this->_socket);
    }

    /**
     * Send a command to the Asterisk CLI interface. Acceptable commands 
     * are dependent on the Asterisk installation.
     *
     * @param string $command Command to execute on server
     *
     * @return string|bool
     */
    public function command($command)
    {
        if (!$this->_socket) { 
            throw new PEAR_Exception('No socket detected');
        }
    
        fputs($this->_socket, "Action: Command\r\nCommand: $command\r\n\r\n");
        $response = fgets($this->_socket);

        if (strpos($response, 'No such command') !== false) {
            throw new PEAR_Exception('No such command');
        } else {
            return $response;
        }
    }

    /**
     * A simple 'ping' command which the server responds with 'pong'
     *
     * @return bool
     */
    public function ping()
    {
        if (!$this->_socket) { 
            throw new PEAR_Exception('No socket detected');
        }
        
        fputs("Action: Ping\r\n\r\n");
        $response = stream_get_contents($this->_socket);
        if (strpos($response, "Pong") === false) {
            throw new PEAR_Exception('No response to ping');
        } else {
            return true;
        }
    }
<commit_msg>Removing rogue fgets function and replacing with stream_get_contents. Bug reported by sidhu.j<commit_after><?php

/**
 * This package is capable of interfacing with the open source Asterisk PBX via 
 * its built in Manager API.  This will allow you to execute manager commands
 * for administration and maintenance of the server.
 * 
 * Copyright (c) 2008, <NAME> <<EMAIL>>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 * - Neither the name of the author nor the names of its 
 *   contributors may be used to endorse or promote products derived from 
 *   this software without specific prior written permission.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * PHP version 5
 *
 * @category  Net
 * @package   Net_AsteriskManager
 * @author    <NAME> <<EMAIL>>
 * @copyright 2008 <NAME>
 * @license   http://www.debian.org/misc/bsd.license New BSD License
 * @link      http://pear.php.net/pepr/pepr-proposal-show.php?id=543
 */

/**
 * PEAR Exception class is used for exception handling
 */
require_once 'PEAR/Exception.php';

/**
 * Class for accessing the Asterisk Manager interface 
 * {@link http://www.voip-info.org/wiki/view/Asterisk+manager+API}
 * 
 * @category Net
 * @package  Net_AsteriskManager
 * @author   <NAME> <<EMAIL>>
 * @license  http://www.debian.org/misc/bsd.license New BSD License
 * @link     http://pear.php.net/pepr/pepr-proposal-show.php?id=543
 */
class Net_AsteriskManager
{
    /**
     * The Asterisk server which will recieve the manager commands 
     * @access public
     * @var string
     */
    public $server;

    /**
     * The port to use when connecting to the Asterisk server
     * @access public
     * @var integer
     */
    public $port = 5038;

    /**
     * The opened socket to the Asterisk server
     * @access private 
     * @var object
     */
    private $_socket;

    /**
     * Class constructor
     * 
     * @param array $params Array of the parameters used to connect to the server
     * <code>
     * array(
     *       'server' => '127.0.0.1'    // The server to connect to
     *       'port' => '5038',          // Port of manager API
     *       'auto_connect' => true     // Autoconnect on construction?
     *      );
     * </code>
     * 
     * @uses AsteriskManager::$server
     * @uses AsteriskManager::$port
     * @uses AsteriskManager::$_socket
     */
    public function __construct($params = array())
    {
        if (!isset($params['server'])) {
            throw new PEAR_Exception('You must provide a server');
        }
        $this->server = $params['server'];

        if (isset($params['port'])) {
            $this->port = $params['port'];
        }

        if (isset($params['auto_connect'])) {
            $this->connect();
        }
    }

    /**
     * If not already connected then connect to the Asterisk server
     * otherwise close active connection and reconnect
     *
     * @return bool
     */
    public function connect()
    {
        if ($this->_socket) {
            $this->close();
        }

        if ($this->_socket = fsockopen($this->server, $this->port)) {
            stream_set_timeout($this->_socket, 3);
        } else {
            throw new PEAR_Exception("Could not establish connection to "
            ."{$this->server} on {$this->port}");
        }
    }

    /**
     * Login into Asterisk Manager interface given the user credentials
     *
     * @param string $username The username to access the interface
     * @param string $password The password defined in manager interface of server
     * 
     * @return bool
     */
    public function login($username, $password)
    {
        fputs($this->_socket, "Action: login\r\nUsername: {$username}\r\n"
                               ."Secret: {$password}\<PASSWORD>");
        $response = stream_get_contents($this->_socket);
        if (strpos($response, "Message: Authentication accepted") != false) {
            return true;
        } else {
            throw new PEAR_Exception('Authentication failed');
        }
    }

    /**
     * Logout of the current manager session attached to $this::socket
     * 
     * @return bool
     */
    public function logout()
    {
        if (!$this->_socket) { 
            throw new PEAR_Exception('No socket detected');
        }
        
        fputs($this->_socket, "Action: Logoff\r\n\r\n");

        return true;
    }

    /**
     * Close the connection
     *
     * @return bool
     */
    public function close()
    {
        if (!$this->_socket) {
            throw new PEAR_Exception('No socket detected');
        }

        return fclose($this->_socket);
    }

    /**
     * Send a command to the Asterisk CLI interface. Acceptable commands 
     * are dependent on the Asterisk installation.
     *
     * @param string $command Command to execute on server
     *
     * @return string|bool
     */
    public function command($command)
    {
        if (!$this->_socket) { 
            throw new PEAR_Exception('No socket detected');
        }
    
        fputs($this->_socket, "Action: Command\r\nCommand: $command\r\n\r\n");
        $response = stream_get_contents($this->_socket);

        if (strpos($response, 'No such command') !== false) {
            throw new PEAR_Exception('No such command');
        } else {
            return $response;
        }
    }

    /**
     * A simple 'ping' command which the server responds with 'pong'
     *
     * @return bool
     */
    public function ping()
    {
        if (!$this->_socket) { 
            throw new PEAR_Exception('No socket detected');
        }
        
        fputs("Action: Ping\r\n\r\n");
        $response = stream_get_contents($this->_socket);
        if (strpos($response, "Pong") === false) {
            throw new PEAR_Exception('No response to ping');
        } else {
            return true;
        }
    }

{'fraction_non_alphanumeric': 0.1076388888888889, 'fraction_numerical': 0.004251700680272109, 'mean_word_length': 2.296659658958187, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 79, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 2, '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': '2597412', 'n_tokens_mistral': 4020, 'n_tokens_neox': 3751, 'n_words': 1317}