<?php
/**
 * Cliente que usa las funciones básicas del protocolo/Client that uses the basic functions of the protocol
 *
 * @author     Sinfocol
 * @copyright  2009 www.sinfocol.org
 * @version    Release: 2.1.17
 * @link       http://www.sinfocol.org/2009/06/thewalrusbot-un-cliente-irc-sencillo-en-php/
 * @since      Class available since Release 2.1.17
 */
set_time_limit(0);
class 
Cliente{
    public 
$servidor;
    public 
$puerto;
    public 
$canal;
    public 
$nick;
    public 
$clave;
    public 
$nombre;
    public 
$php;

    private 
$version '2.1.17';
    private 
$umsg '';
    private 
$socket;

    public function 
__construct(){
        include(
'IrcParser.php');
    }

    
/**
     * Realiza la conexión cliente-servidor/Performs the client-server connection
     * @return void
     */
    
public function conectar(){
        if(
strval($this->puerto) <=|| strval($this->puerto 65535))
            
$this->puerto 6667;
        
        
$this->socket = @fsockopen($this->servidor$this->puerto$errno$errstr300);

        if(!
$this->socket)
            die(
"No se pudo establecer la comunicación con {$this->servidor}");

        
$nickname '/^[\-\d\x41-\x7d]+$/';
        if(
preg_match($nickname$this->nick) == false)
            
$this->nick $this->_caracteresAleatorios(10'abcdefghijklmnopqrstuvwxyz');

        if(empty(
$this->nombre))
            
$this->nombre "TheWalrusBot {$this->version}";

        echo(
"Iniciando el cliente");

        
$irc  '';
        
$parser = new IrcParser();
        while( !
feof($this->socket) ){
            
//Se obtienen los datos del socket y se procesan con el IrcParser
            
$irc $parser->parsefgets($this->socket) );
            echo 
$irc['raw'];

            
//Si $this->php tiene contenido, lo ejecutamos con la función eval() y capturamos los errores para que no interfiera con la conexión
            
if( isset($this->php) ){
                try{
                    eval(
$this->php);
                }catch(
Exception $e){
                }
            }

        } 
//Fin while(!feof($this->socket))

    
//Fin función conectar()

    /**
     * Escribe sobre el socket usado/Writes in the used socket
     * @param string $cadena Cadena a escribir/String to write
     * @param bool optional $crlf Define la escritura del CRLF en el protocolo IRC/Define the write of the CRLF in the protocol
     * @return void
     */
    
private function _out($cadena$crlf true){
        
//Ignoramos los caracteres nulos
        
$cadena str_replace("\x00"''$cadena);
        
//Asignamos al último mensaje el mensaje que se enviará
        
$this->umsg $cadena;
        
$crlf $crlf "\r\n"'';
        echo 
$cadena;
        
//El mensaje no puede superar los 512 caracteres, incluyendo CRLF
        
$cadena substr($cadena0510) . $crlf;
        if(
$this->socket)
            
fwrite($this->socket$cadena);
    }

    
/**
     * Genera cadenas aleatorias/Generate random strings
     * @param int $num El número de carácteres/The number of characters
     * @param string $caracteres Son los carácteres que se generarán/It is the characters that will be generated
     * @return Una cadena aleatoria entre UNO y VEINTE carácteres/A random string between ONE and TWENTY characters
     */
    
private function _caracteresAleatorios($num$caracteres '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'){
        
$strlen strlen($caracteres);
        if(
strval($num) < || strval($num) > 20$num 10;

        
$tmp '';
        for(
$i=0$i<$num$i++){
            
$tmp .= $caracteres[rand(0$strlen)];
        }
        return 
$tmp;
    }
}