code:
<?php

/**
 * XMPPHP: The PHP XMPP Library
 * Copyright (C) 2008  Nathanael C. Fritz
 * This file is part of SleekXMPP.
 *
 * XMPPHP 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 2 of the License, or
 * (at your option) any later version.
 *
 * XMPPHP 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 XMPPHP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   xmpphp
 * @package    XMPPHP
 * @author     Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author     Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author     Michael Garvin <JID: gar@netflint.net>
 * @author     Alexander Birkner (https://github.com/BirknerAlex)
 * @author     zorn-v (https://github.com/zorn-v/xmpphp/)
 * @author     GNU social
 * @copyright  2008 Nathanael C. Fritz
 */

namespace XMPPHP;

/** Exception */
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Exception.php';

/** XMLObj */
require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLObj.php';

/** Log */
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Log.php';

/**
 * XMPPHP XMLStream
 *
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 * @version   $Id$
 */
class XMLStream
{
    /**
     * @var resource
     */
    protected $socket;
    /**
     * @var resource
     */
    protected $parser;
    /**
     * @var string
     */
    protected $buffer;
    /**
     * @var integer
     */
    protected $xml_depth = 0;
    /**
     * @var string
     */
    protected $host;
    /**
     * @var integer
     */
    protected $port;
    /**
     * @var string
     */
    protected $stream_start = '<stream>';
    /**
     * @var string
     */
    protected $stream_end = '</stream>';
    /**
     * @var boolean
     */
    protected $disconnected = false;
    /**
     * @var boolean
     */
    protected $sent_disconnect = false;
    /**
     * @var array
     */
    protected $ns_map = array();
    /**
     * @var array
     */
    protected $current_ns = array();
    /**
     * @var array
     */
    protected $xmlobj = null;
    /**
     * @var array
     */
    protected $nshandlers = array();
    /**
     * @var array
     */
    protected $xpathhandlers = array();
    /**
     * @var array
     */
    protected $idhandlers = array();
    /**
     * @var array
     */
    protected $eventhandlers = array();
    /**
     * @var integer
     */
    protected $lastid = 0;
    /**
     * @var string
     */
    protected $default_ns;
    /**
     * @var string[]
     */
    protected $until = [];
    /**
     * @var int[]
     */
    protected $until_count = [];
    /**
     * @var array
     */
    protected $until_happened = false;
    /**
     * @var array
     */
    protected $until_payload = array();
    /**
     * @var Log
     */
    protected $log;
    /**
     * @var boolean
     */
    protected $reconnect = true;
    /**
     * @var boolean
     */
    protected $been_reset = false;
    /**
     * @var boolean
     */
    protected $is_server;
    /**
     * @var float
     */
    protected $last_send = 0;
    /**
     * @var boolean
     */
    protected $use_ssl = false;
    /**
     * @var integer
     */
    protected $reconnectTimeout = 30;

    /**
     * Constructor
     *
     * @param string $host
     * @param string $port
     * @param boolean $printlog
     * @param string $loglevel
     * @param boolean $is_server
     */
    public function __construct($host = null, $port = null, $printlog = false, $loglevel = null, $is_server = false)
    {
        $this->reconnect = !$is_server;
        $this->is_server = $is_server;
        $this->host = $host;
        $this->port = $port;
        $this->setupParser();
        $this->log = new Log($printlog, $loglevel);
    }

    /**
     * Setup the XML parser
     */
    public function setupParser()
    {
        $this->parser = xml_parser_create('UTF-8');
        xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);
        xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
        xml_set_object($this->parser, $this);
        xml_set_element_handler($this->parser, 'startXML', 'endXML');
        xml_set_character_data_handler($this->parser, 'charXML');
    }

    /**
     * Destructor
     * Cleanup connection
     */
    public function __destruct()
    {
        if (!$this->disconnected && $this->socket) {
            $this->disconnect();
        }
    }

    /**
     * Disconnect from XMPP Host
     */
    public function disconnect()
    {
        $this->log->log("Disconnecting...", Log::LEVEL_VERBOSE);
        if (false == (bool)$this->socket) {
            return;
        }
        $this->reconnect = false;
        $this->send($this->stream_end);
        $this->sent_disconnect = true;
        $this->processUntil('end_stream', 5);
        $this->disconnected = true;
    }

    /**
     * Send to socket
     *
     * @param string $msg
     * @param null $timeout
     * @return bool|int
     * @throws Exception
     */
    public function send($msg, $timeout = NULL)
    {

        if (is_null($timeout)) {
            $secs = NULL;
            $usecs = NULL;
        } else if ($timeout == 0) {
            $secs = 0;
            $usecs = 0;
        } else {
            $maximum = $timeout * 1000000;
            $usecs = $maximum % 1000000;
            $secs = floor(($maximum - $usecs) / 1000000);
        }

        $read = array();
        $write = array($this->socket);
        $except = array();

        $select = @stream_select($read, $write, $except, $secs, $usecs);

        if ($select === False) {
            $this->log->log("ERROR sending message; reconnecting.");
            $this->doReconnect();
            # TODO: retry send here
            return false;
        } elseif ($select > 0) {
            $this->log->log("Socket is ready; send it.", Log::LEVEL_VERBOSE);
        } else {
            $this->log->log("Socket is not ready; break.", Log::LEVEL_ERROR);
            return false;
        }

        $sentbytes = @fwrite($this->socket, $msg);
        $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), Log::LEVEL_VERBOSE);
        if ($sentbytes === FALSE) {
            $this->log->log("ERROR sending message; reconnecting.", Log::LEVEL_ERROR);
            $this->doReconnect();
            return false;
        }
        $this->log->log("Successfully sent $sentbytes bytes.", Log::LEVEL_VERBOSE);
        return $sentbytes;
    }

    /**
     * Reconnect XMPP Host
     * @throws Exception
     */
    public function doReconnect()
    {
        if (!$this->is_server) {
            $this->log->log("Reconnecting ($this->reconnectTimeout)...", Log::LEVEL_WARNING);
            $this->connect($this->reconnectTimeout, false, false);
            $this->reset();
            $this->event('reconnect');
        }
    }

    /**
     * Connect to XMPP Host
     *
     * @param integer $timeout
     * @param boolean $persistent
     * @param boolean $sendinit
     * @throws Exception
     * @throws Exception
     */
    public function connect($timeout = 30, $persistent = false, $sendinit = true)
    {
        $this->sent_disconnect = false;
        $starttime = time();

        do {
            $this->disconnected = false;
            $this->sent_disconnect = false;
            if ($persistent) {
                $conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
            } else {
                $conflag = STREAM_CLIENT_CONNECT;
            }
            $conntype = 'tcp';
            if ($this->use_ssl) $conntype = 'ssl';
            $this->log->log("Connecting to $conntype://{$this->host}:{$this->port}");
            $this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
            if (!$this->socket) {
                $this->log->log("Could not connect.", Log::LEVEL_ERROR);
                $this->disconnected = true;
                # Take it easy for a few seconds
                sleep(min($timeout, 5));
            }
        } while (!$this->socket && (time() - $starttime) < $timeout);

        if ($this->socket) {
            stream_set_blocking($this->socket, 1);
            if ($sendinit) $this->send($this->stream_start);
        } else {
            throw new Exception("Could not connect before timeout.");
        }
    }

    /**
     * Reset connection
     */
    public function reset()
    {
        $this->xml_depth = 0;
        unset($this->xmlobj);
        $this->xmlobj = array();
        $this->setupParser();
        if (!$this->is_server) {
            $this->send($this->stream_start);
        }
        $this->been_reset = true;
    }

    /**
     * Event?
     *
     * @param string $name
     * @param string $payload
     */
    public function event($name, $payload = null)
    {
        $this->log->log("EVENT: $name", Log::LEVEL_DEBUG);
        foreach ($this->eventhandlers as $handler) {
            if ($name == $handler[0]) {
                if ($handler[2] === null) {
                    $handler[2] = $this;
                }
                $handler[2]->{$handler[1]}($payload);
            }
        }
        foreach ($this->until as $key => $until) {
            if (is_array($until)) {
                if (in_array($name, $until)) {
                    $this->until_payload[$key][] = array($name, $payload);
                    if (!isset($this->until_count[$key])) {
                        $this->until_count[$key] = 0;
                    }
                    $this->until_count[$key] += 1;
                    #$this->until[$key] = false;
                }
            }
        }
    }

    /**
     * Process until a specified event or a timeout occurs
     *
     * @param string|array $event
     * @param integer $timeout
     * @return string
     * @throws Exception
     */
    public function processUntil($event, $timeout = -1)
    {
        $start = time();
        if (!is_array($event)) $event = array($event);
        $this->until[] = $event;
        end($this->until);
        $event_key = key($this->until);
        reset($this->until);
        $this->until_count[$event_key] = 0;
        while (!$this->disconnected and $this->until_count[$event_key] < 1 and (time() - $start < $timeout or $timeout == -1)) {
            $this->__process();
        }
        if (array_key_exists($event_key, $this->until_payload)) {
            $payload = $this->until_payload[$event_key];
            unset($this->until_payload[$event_key]);
            unset($this->until_count[$event_key]);
            unset($this->until[$event_key]);
        } else {
            $payload = array();
        }
        return $payload;
    }

    /**
     * Core reading tool
     * 0 -> only read if data is immediately ready
     * NULL -> wait forever and ever
     * integer -> process for this amount of time
     * @param int $maximum
     * @return bool
     * @throws Exception
     */

    private function __process($maximum = 5)
    {

        $remaining = $maximum;

        do {
            $starttime = (microtime(true) * 1000000);
            $read = array($this->socket);
            $write = array();
            $except = array();
            if (is_null($maximum)) {
                $secs = NULL;
                $usecs = NULL;
            } else if ($maximum == 0) {
                $secs = 0;
                $usecs = 0;
            } else {
                $usecs = $remaining % 1000000;
                $secs = floor(($remaining - $usecs) / 1000000);
            }
            $updated = @stream_select($read, $write, $except, $secs, $usecs);
            if ($updated === false) {
                $this->log->log("Error on stream_select()", Log::LEVEL_VERBOSE);
                if ($this->reconnect) {
                    $this->doReconnect();
                } else {
                    fclose($this->socket);
                    $this->socket = NULL;
                    return false;
                }
            } else if ($updated > 0) {
                # XXX: Is this big enough?
                $buff = @fread($this->socket, 4096);
                if (!$buff) {
                    if ($this->reconnect) {
                        $this->doReconnect();
                    } else {
                        fclose($this->socket);
                        $this->socket = NULL;
                        return false;
                    }
                }
                $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
                xml_parse($this->parser, $buff, false);
            } // Otherwise,
              // $updated == 0 means no changes during timeout.

            $endtime = (microtime(true) * 1000000);
            $time_past = $endtime - $starttime;
            $remaining = $remaining - $time_past;
        } while (is_null($maximum) || $remaining > 0);
        return true;
    }

    /**
     * Return the log instance
     *
     * @return Log
     */
    public function getLog()
    {
        return $this->log;
    }

    /**
     * Get next ID
     *
     * @return integer
     */
    public function getId()
    {
        $this->lastid++;
        return $this->lastid;
    }

    /**
     * Set SSL
     * @param bool $use
     */
    public function useSSL($use = true)
    {
        $this->use_ssl = $use;
    }

    /**
     * Add ID Handler
     *
     * @param integer $id
     * @param string $pointer
     * @param string $obj
     */
    public function addIdHandler($id, $pointer, $obj = null)
    {
        $this->idhandlers[$id] = array($pointer, $obj);
    }

    /**
     * Add Handler
     *
     * @param string $name
     * @param string $ns
     * @param string $pointer
     * @param string $obj
     * @param integer $depth
     */
    public function addHandler($name, $ns, $pointer, $obj = null, $depth = 1)
    {
        #TODO deprication warning
        $this->nshandlers[] = array($name, $ns, $pointer, $obj, $depth);
    }

    /**
     * Add XPath Handler
     *
     * @param string $xpath
     * @param string $pointer
     * @param
     */
    public function addXPathHandler($xpath, $pointer, $obj = null)
    {
        if (preg_match_all("/\(?{[^\}]+}\)?(\/?)[^\/]+/", $xpath, $regs)) {
            $ns_tags = $regs[0];
        } else {
            $ns_tags = array($xpath);
        }
        foreach ($ns_tags as $ns_tag) {
            list($l, $r) = explode("}", $ns_tag);
            if ($r != null) {
                $xpart = array(substr($l, 1), $r);
            } else {
                $xpart = array(null, $l);
            }
            $xpath_array[] = $xpart;
        }
        $this->xpathhandlers[] = array($xpath_array, $pointer, $obj);
    }

    /**
     * Add Event Handler
     *
     * @param $name
     * @param string $pointer
     * @param string $obj
     */
    public function addEventHandler($name, $pointer, $obj)
    {
        $this->eventhandlers[] = array($name, $pointer, $obj);
    }

    public function setReconnectTimeout($timeout)
    {
        $this->reconnectTimeout = $timeout;
    }

    /**
     * Are we are disconnected?
     *
     * @return boolean
     */
    public function isDisconnected()
    {
        return $this->disconnected;
    }

    /**
     * Process
     *
     */
    public function process()
    {
        $this->__process(NULL);
    }

    /**
     * Process until a timeout occurs
     *
     * @param integer $timeout
     * @return string
     * @throws Exception
     */
    public function processTime($timeout = NULL)
    {
        if (is_null($timeout)) {
            return $this->__process(NULL);
        } else {
            return $this->__process($timeout * 1000000);
        }
    }

    /**
     * Obsolete?
     * @param $socket
     */
    public function Xapply_socket($socket)
    {
        $this->socket = $socket;
    }

    /**
     * XML start callback
     *
     * @param resource $parser
     * @param string $name
     * @param $attr
     * @see xml_set_element_handler
     */
    public function startXML($parser, $name, $attr)
    {
        if ($this->been_reset) {
            $this->been_reset = false;
            $this->xml_depth = 0;
        }
        $this->xml_depth++;
        if (array_key_exists('XMLNS', $attr)) {
            $this->current_ns[$this->xml_depth] = $attr['XMLNS'];
        } else {
            $this->current_ns[$this->xml_depth] = $this->current_ns[$this->xml_depth - 1];
            if (!$this->current_ns[$this->xml_depth]) $this->current_ns[$this->xml_depth] = $this->default_ns;
        }
        $ns = $this->current_ns[$this->xml_depth];
        foreach ($attr as $key => $value) {
            if (strstr($key, ":")) {
                $key = explode(':', $key);
                $key = $key[1];
                $this->ns_map[$key] = $value;
            }
        }
        if (!strstr($name, ":") === false) {
            $name = explode(':', $name);
            $ns = $this->ns_map[$name[0]];
            $name = $name[1];
        }
        $obj = new XMLObj($name, $ns, $attr);
        if ($this->xml_depth > 1) {
            $this->xmlobj[$this->xml_depth - 1]->subs[] = $obj;
        }
        $this->xmlobj[$this->xml_depth] = $obj;
    }

    /**
     * XML end callback
     *
     * @param resource $parser
     * @param string $name
     * @throws Exception
     * @see xml_set_element_handler
     *
     */
    public function endXML($parser, $name)
    {
        #$this->log->log("Ending $name",  Log::LEVEL_DEBUG);
        #print "$name\n";
        if ($this->been_reset) {
            $this->been_reset = false;
            $this->xml_depth = 0;
        }
        $this->xml_depth--;
        if ($this->xml_depth == 1) {
            #clean-up old objects
            #$found = false; #FIXME This didn't appear to be in use --Gar
            foreach ($this->xpathhandlers as $handler) {
                if (is_array($this->xmlobj) && array_key_exists(2, $this->xmlobj)) {
                    $searchxml = $this->xmlobj[2];
                    $nstag = array_shift($handler[0]);
                    if (($nstag[0] == null or $searchxml->ns == $nstag[0]) and ($nstag[1] == "*" or $nstag[1] == $searchxml->name)) {
                        foreach ($handler[0] as $nstag) {
                            if ($searchxml !== null and $searchxml->hasSub($nstag[1], $ns = $nstag[0])) {
                                $searchxml = $searchxml->sub($nstag[1], $ns = $nstag[0]);
                            } else {
                                $searchxml = null;
                                break;
                            }
                        }
                        if ($searchxml !== null) {
                            if ($handler[2] === null) $handler[2] = $this;
                            $this->log->log("Calling {$handler[1]}", Log::LEVEL_DEBUG);
                            $handler[2]->{$handler[1]}($this->xmlobj[2]);
                        }
                    }
                }
            }
            foreach ($this->nshandlers as $handler) {
                if ($handler[4] != 1 and array_key_exists(2, $this->xmlobj) and $this->xmlobj[2]->hasSub($handler[0])) {
                    $searchxml = $this->xmlobj[2]->sub($handler[0]);
                } elseif (is_array($this->xmlobj) and array_key_exists(2, $this->xmlobj)) {
                    $searchxml = $this->xmlobj[2];
                }
                if ($searchxml !== null and $searchxml->name == $handler[0] and ($searchxml->ns == $handler[1] or (!$handler[1] and $searchxml->ns == $this->default_ns))) {
                    if ($handler[3] === null) $handler[3] = $this;
                    $this->log->log("Calling {$handler[2]}", Log::LEVEL_DEBUG);
                    $handler[3]->{$handler[2]}($this->xmlobj[2]);
                }
            }
            foreach ($this->idhandlers as $id => $handler) {
                if (array_key_exists('id', $this->xmlobj[2]->attrs) and $this->xmlobj[2]->attrs['id'] == $id) {
                    if ($handler[1] === null) $handler[1] = $this;
                    $handler[1]->{$handler[0]}($this->xmlobj[2]);
                    #id handlers are only used once
                    unset($this->idhandlers[$id]);
                    break;
                }
            }
            if (is_array($this->xmlobj)) {
                $this->xmlobj = array_slice($this->xmlobj, 0, 1);
                if (isset($this->xmlobj[0]) && $this->xmlobj[0] instanceof XMLObj) {
                    $this->xmlobj[0]->subs = null;
                }
            }
            unset($this->xmlobj[2]);
        }
        if ($this->xml_depth == 0 and !$this->been_reset) {
            if (!$this->disconnected) {
                if (!$this->sent_disconnect) {
                    $this->send($this->stream_end);
                }
                $this->disconnected = true;
                $this->sent_disconnect = true;
                fclose($this->socket);
                if ($this->reconnect) {
                    $this->doReconnect();
                }
            }
            $this->event('end_stream');
        }
    }

    /**
     * XML character callback
     * @param resource $parser
     * @param string $data
     * @see xml_set_character_data_handler
     *
     */
    public function charXML($parser, $data)
    {
        if (array_key_exists($this->xml_depth, $this->xmlobj)) {
            $this->xmlobj[$this->xml_depth]->data .= $data;
        }
    }

    /**
     * Read from socket
     */
    public function read()
    {
        $buff = @fread($this->socket, 1024);
        if (!$buff) {
            if ($this->reconnect) {
                $this->doReconnect();
            } else {
                fclose($this->socket);
                return false;
            }
        }
        $this->log->log("RECV: $buff", Log::LEVEL_VERBOSE);
        xml_parse($this->parser, $buff, false);
    }

    public function time()
    {
        list($usec, $sec) = explode(" ", microtime());
        return (float)$sec + (float)$usec;
    }

    public function readyToProcess()
    {
        $read = array($this->socket);
        $write = array();
        $except = array();
        $updated = @stream_select($read, $write, $except, 0);
        return (($updated !== false) && ($updated > 0));
    }
}


code:
<?php

/**
 * XMPPHP: The PHP XMPP Library
 * Copyright (C) 2008  Nathanael C. Fritz
 * This file is part of SleekXMPP.
 *
 * XMPPHP 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 2 of the License, or
 * (at your option) any later version.
 *
 * XMPPHP 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 XMPPHP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   xmpphp
 * @package    XMPPHP
 * @author     Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author     Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author     Michael Garvin <JID: gar@netflint.net>
 * @author     Alexander Birkner (https://github.com/BirknerAlex)
 * @author     zorn-v (https://github.com/zorn-v/xmpphp/)
 * @author     GNU social
 * @copyright  2008 Nathanael C. Fritz
 */

namespace XMPPHP;

/** XMPPHP_XMLStream */
require_once __DIR__ . DIRECTORY_SEPARATOR . 'XMLStream.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'Roster.php';

/**
 * XMPPHP XMPP
 *
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 * @version   $Id$
 */
class XMPP extends XMLStream
{
    /**
     * @var string
     */
    public $server;

    /**
     * @var string
     */
    public $user;
    /**
     * @var boolean
     */
    public $track_presence = true;
    /**
     * @var object
     */
    public $roster;
    /**
     * @var string
     */
    protected $password;
    /**
     * @var string
     */
    protected $resource;
    /**
     * @var string
     */
    protected $fulljid;
    /**
     * @var string
     */
    protected $basejid;
    /**
     * @var boolean
     */
    protected $authed = false;
    protected $session_started = false;
    /**
     * @var boolean
     */
    protected $auto_subscribe = false;
    /**
     * @var boolean
     */
    protected $use_encryption = true;

    /**
     * Constructor
     *
     * @param string $host
     * @param integer $port
     * @param string $user
     * @param string $password
     * @param string $resource
     * @param string $server
     * @param boolean $printlog
     * @param string $loglevel
     */
    public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null)
    {
        parent::__construct($host, $port, $printlog, $loglevel);

        $this->user = $user;
        $this->password = $password;
        $this->resource = $resource;
        if (!$server) {
            $server = $host;
        }
        $this->server = $server;
        $this->basejid = $this->user . '@' . $this->host;

        $this->roster = new Roster();
        $this->track_presence = true;

        $this->stream_start = '<stream:stream to="' . $server . '" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" version="1.0">';
        $this->stream_end = '</stream:stream>';
        $this->default_ns = 'jabber:client';

        $this->addXPathHandler('{http://etherx.jabber.org/streams}features', 'features_handler');
        $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}success', 'sasl_success_handler');
        $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-sasl}failure', 'sasl_failure_handler');
        $this->addXPathHandler('{urn:ietf:params:xml:ns:xmpp-tls}proceed', 'tls_proceed_handler');
        $this->addXPathHandler('{jabber:client}message', 'message_handler');
        $this->addXPathHandler('{jabber:client}presence', 'presence_handler');
        $this->addXPathHandler('iq/{jabber:iq:roster}query', 'roster_iq_handler');
    }

    /**
     * Turn encryption on/ff
     *
     * @param boolean $useEncryption
     */
    public function useEncryption($useEncryption = true)
    {
        $this->use_encryption = $useEncryption;
    }

    /**
     * Turn on auto-authorization of subscription requests.
     *
     * @param boolean $autoSubscribe
     */
    public function autoSubscribe($autoSubscribe = true)
    {
        $this->auto_subscribe = $autoSubscribe;
    }

    /**
     * Send XMPP Message
     *
     * @param string $to
     * @param string $body
     * @param string $type
     * @param string $subject
     * @param null $payload
     * @throws Exception
     */
    public function message($to, $body, $type = 'chat', $subject = null, $payload = null)
    {
        if ($this->disconnected) {
            throw new Exception('You need to connect first');
        }

        if (empty($type)) {
            $type = 'chat';
        }

        $to      = htmlspecialchars($to);
        $body    = htmlspecialchars($body);
        $subject = htmlspecialchars($subject);
        $subject = ($subject) ? '<subject>' . $subject . '</subject>' : '';
        $payload = ($payload) ? $payload : '';
        $sprintf = '<message from="%s" to="%s" type="%s">%s<body>%s</body>%s</message>';
        $output  = sprintf($sprintf, $this->fulljid, $to, $type, $subject, $body, $payload);
        $this->send($output);
    }

    /**
     * Set Presence
     *
     * @param string $status
     * @param string $show
     * @param string $to
     * @param string $type
     * @param null $priority
     * @throws Exception
     */
    public function presence($status = null, $show = 'available', $to = null, $type = 'available', $priority = null)
    {
        if ($this->disconnected) {
            throw new Exception('You need to connect first');
        }

        if ($type == 'available') {
            $type = '';
        }
        $to = htmlspecialchars($to);
        $status = htmlspecialchars($status);
        if ($show == 'unavailable') {
            $type = 'unavailable';
        }

        $out = "<presence";
        if ($to) {
            $out .= " to=\"$to\"";
        }
        if ($type) {
            $out .= " type='$type'";
        }
        if ($show == 'available' and !$status and $priority !== null) {
            $out .= "/>";
        } else {
            $out .= ">";
            if ($show != 'available') {
                $out .= "<show>$show</show>";
            }
            if ($status) {
                $out .= "<status>$status</status>";
            }
            if ($priority !== null) {
                $out .= "<priority>$priority</priority>";
            }
            $out .= "</presence>";
        }

        $this->send($out);
    }

    /**
     * Send Auth request
     *
     * @param string $jid
     */
    public function subscribe($jid)
    {
        $this->send("<presence type='subscribe' to='{$jid}' from='{$this->fulljid}' />");
        #$this->send("<presence type='subscribed' to='{$jid}' from='{$this->fulljid}' />");
    }

    /**
     * Message handler
     *
     * @param string $xml
     */
    public function message_handler($xml)
    {
        if (isset($xml->attrs['type'])) {
            $payload['type'] = $xml->attrs['type'];
        } else {
            $payload['type'] = 'chat';
        }
        $body = $xml->sub('body');
        $payload['from'] = $xml->attrs['from'];
        $payload['body'] = is_object($body) ? $body->data : false; // $xml->sub('body')->data;
        $payload['xml'] = $xml;
        $this->log->log("Message: {$payload['body']}", Log::LEVEL_DEBUG);
        $this->event('message', $payload);
    }

    /**
     * Presence handler
     *
     * @param string $xml
     */
    public function presence_handler($xml)
    {
        $payload['type'] = (isset($xml->attrs['type'])) ? $xml->attrs['type'] : 'available';
        $payload['show'] = (isset($xml->sub('show')->data)) ? $xml->sub('show')->data : $payload['type'];
        $payload['from'] = $xml->attrs['from'];
        $payload['status'] = (isset($xml->sub('status')->data)) ? $xml->sub('status')->data : '';
        $payload['priority'] = (isset($xml->sub('priority')->data)) ? intval($xml->sub('priority')->data) : 0;
        $payload['xml'] = $xml;
        if ($this->track_presence) {
            $this->roster->setPresence($payload['from'], $payload['priority'], $payload['show'], $payload['status']);
        }
        $this->log->log("Presence: {$payload['from']} [{$payload['show']}] {$payload['status']}", Log::LEVEL_DEBUG);
        if (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribe') {
            if ($this->auto_subscribe) {
                $this->send("<presence type='subscribed' to='{$xml->attrs['from']}' from='{$this->fulljid}' />");
                $this->send("<presence type='subscribe' to='{$xml->attrs['from']}' from='{$this->fulljid}' />");
            }
            $this->event('subscription_requested', $payload);
        } elseif (array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribed') {
            $this->event('subscription_accepted', $payload);
        } else {
            $this->event('presence', $payload);
        }
    }

    /**
     * Retrieves the roster
     *
     */
    public function getRoster()
    {
        $id = $this->getID();
        $this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>");
    }

    /**
     * Retrieves the vcard
     * @param null $jid
     */
    public function getVCard($jid = null)
    {
        $id = $this->getID();
        $this->addIdHandler($id, 'vcard_get_handler');
        if ($jid) {
            $this->send("<iq type='get' id='$id' to='$jid'><vCard xmlns='vcard-temp' /></iq>");
        } else {
            $this->send("<iq type='get' id='$id'><vCard xmlns='vcard-temp' /></iq>");
        }
    }

    /**
     * Features handler
     *
     * @param string $xml
     */
    protected function features_handler($xml)
    {
        if ($xml->hasSub('starttls') and $this->use_encryption) {
            $this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>");
        } elseif ($xml->hasSub('bind') and $this->authed) {
            $id = $this->getId();
            $this->addIdHandler($id, 'resource_bind_handler');
            $this->send("<iq xmlns=\"jabber:client\" type=\"set\" id=\"$id\"><bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"><resource>{$this->resource}</resource></bind></iq>");
        } else {
            $this->log->log("Attempting Auth...");
            if ($this->password) {
                $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>" . base64_encode("\x00" . $this->user . "\x00" . $this->password) . "</auth>");
            } else {
                $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
            }
        }
    }

    /**
     * SASL success handler
     *
     * @param string $xml
     */
    protected function sasl_success_handler($xml)
    {
        $this->log->log("Auth success!");
        $this->authed = true;
        $this->reset();
    }

    /**
     * SASL feature handler
     *
     * @param string $xml
     * @throws Exception
     */
    protected function sasl_failure_handler($xml)
    {
        $this->log->log("Auth failed!", Log::LEVEL_ERROR);
        $this->disconnect();

        throw new Exception('Auth failed!');
    }

    /**
     * Resource bind handler
     *
     * @param string $xml
     */
    protected function resource_bind_handler($xml)
    {
        if ($xml->attrs['type'] == 'result') {
            $this->log->log("Bound to " . $xml->sub('bind')->sub('jid')->data);
            $this->fulljid = $xml->sub('bind')->sub('jid')->data;
            $jidarray = explode('/', $this->fulljid);
            $this->jid = $jidarray[0];
        }
        $id = $this->getId();
        $this->addIdHandler($id, 'session_start_handler');
        $this->send("<iq xmlns='jabber:client' type='set' id='$id'><session xmlns='urn:ietf:params:xml:ns:xmpp-session' /></iq>");
    }

    /**
     * Roster iq handler
     * Gets all packets matching XPath "iq/{jabber:iq:roster}query'
     *
     * @param string $xml
     */
    protected function roster_iq_handler($xml)
    {
        $status = "result";
        $xmlroster = $xml->sub('query');
        foreach ($xmlroster->subs as $item) {
            $groups = array();
            if ($item->name == 'item') {
                $jid = $item->attrs['jid']; //REQUIRED
                $name = $item->attrs['name']; //MAY
                $subscription = $item->attrs['subscription'];
                foreach ($item->subs as $subitem) {
                    if ($subitem->name == 'group') {
                        $groups[] = $subitem->data;
                    }
                }
                $contacts[] = array($jid, $subscription, $name, $groups); //Store for action if no errors happen
            } else {
                $status = "error";
            }
        }
        if ($status == "result") { //No errors, add contacts
            foreach ($contacts as $contact) {
                $this->roster->addContact($contact[0], $contact[1], $contact[2], $contact[3]);
            }
        }
        if ($xml->attrs['type'] == 'set') {
            $this->send("<iq type=\"reply\" id=\"{$xml->attrs['id']}\" to=\"{$xml->attrs['from']}\" />");
        }
    }

    /**
     * Session start handler
     *
     * @param string $xml
     */
    protected function session_start_handler($xml)
    {
        $this->log->log("Session started");
        $this->session_started = true;
        $this->event('session_start');
    }

    /**
     * TLS proceed handler
     *
     * @param string $xml
     */
    protected function tls_proceed_handler($xml)
    {
        $this->log->log("Starting TLS encryption");
        stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
        $this->reset();
    }

    /**
     * VCard retrieval handler
     *
     * @param XMLObj $xml
     */
    protected function vcard_get_handler($xml)
    {
        $vcard_array = array();
        $vcard = $xml->sub('vcard');
        // go through all of the sub elements and add them to the vcard array
        foreach ($vcard->subs as $sub) {
            if ($sub->subs) {
                $vcard_array[$sub->name] = array();
                foreach ($sub->subs as $sub_child) {
                    $vcard_array[$sub->name][$sub_child->name] = $sub_child->data;
                }
            } else {
                $vcard_array[$sub->name] = $sub->data;
            }
        }
        $vcard_array['from'] = $xml->attrs['from'];
        $this->event('vcard', $vcard_array);
    }
}

repo_name: andremichelle/gnu

license: mit


diogocomposer/xmpphp

description: XMPP PHP Library

type: library

keywords: jabber xmpphp xmpp

XMPPHP\: XMPPHP


code:
<?php

/**
 * @file: XMPPHP Cli example
 *
 * @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
 */

/**
 * Activate full error reporting
 * error_reporting(E_ALL & E_STRICT);
 *
 * XMPPHP Log levels:
 *
 * LEVEL_ERROR   = 0;
 * LEVEL_WARNING = 1;
 * LEVEL_INFO    = 2;
 * LEVEL_DEBUG   = 3;
 * LEVEL_VERBOSE = 4;
 */

require '../vendor/autoload.php';

$conf = array(
  'server'   => 'talk.google.com',
  'port'     => 5222,
  'username' => 'username',
  'password' => 'password',
  'proto'    => 'xmpphp',
  'domain'   => 'gmail.com',
  'printlog' => true,
  'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);

// Easy and simple for access to variables with their names
extract($conf);

$conn = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel);
$conn->autoSubscribe();

$vcard_request = array();

try {
    $conn->connect();

    while (!$conn->isDisconnected()) {
        $events   = array('message', 'presence', 'end_stream', 'session_start', 'vcard');
        $payloads = $conn->processUntil($events);

        foreach ($payloads as $result) {
            list($event, $data) = $result;

            if (isset($data)) {
                extract($data);
            }

            switch ($event) {

        case 'message':

          if (!$body) {
              break;
          }

          echo str_repeat('-', 80);
          echo "Message from: $from";

          if (isset($subject)) {
              echo "Subject: $subject";
          }

          echo $body;
          echo str_repeat('-', 80);

          $cmd  = explode(' ', $body);
          $body = "Mi no entender! '$body'";
          $conn->message($from, $body, $type);

          if (isset($cmd[0])) {
              if ($cmd[0] == 'quit') {
                  $conn->disconnect();
              }

              if ($cmd[0] == 'break') {
                  $conn->send('</end>');
              }

              if ($cmd[0] == 'vcard') {
                  if (!isset($cmd[1])) {
                      $cmd[1] = $conn->user;
                  }

                  // Take a note which user requested which vcard
                  $vcard_request[$from] = $cmd[1];
                  // Request the vcard
                  $conn->getVCard($cmd[1]);
              }
          }
          break;

        case 'presence':

          echo "Presence: $from [$show] $status\n";
          break;

        case 'session_start':

          echo "Session start\n";
          $conn->getRoster();
          $conn->presence('Quasar!');
          break;

        case 'vcard':

          $deliver = array_keys($vcard_request, $from);
          $msg     = '';

          foreach ($data as $key => $item) {
              $msg .= $key . ': ';

              if (is_array($item)) {
                  $msg .= "\n";
                  foreach ($item as $subkey => $subitem) {
                      $msg .= ' ' . $subkey . ':' . $subitem . "\n";
                  }
              } else {
                  $msg .= $item . "\n";
              }
          }

          foreach ($deliver as $sendjid) {
              unset($vcard_request[$sendjid]);
              $conn->message($sendjid, $msg, 'chat');
          }
          break;
      }
        }
    }
} catch (XMPPHP\Exception $e) {
    die($e->getMessage());
}


code:
<?php

/**
 * @file: XMPPHP Cli example BOSH
 *
 * @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
 */

/**
 * Activate full error reporting
 * error_reporting(E_ALL & E_STRICT);
 *
 * XMPPHP Log levels:
 *
 * LEVEL_ERROR   = 0;
 * LEVEL_WARNING = 1;
 * LEVEL_INFO    = 2;
 * LEVEL_DEBUG   = 3;
 * LEVEL_VERBOSE = 4;
 */

require '../vendor/autoload.php';

$conf = array(
  'server'   => 'server.tld',
  'port'     => 5280,
  'username' => 'username',
  'password' => 'password',
  'proto'    => 'xmpphp',
  'domain'   => 'server.tld',
  'printlog' => true,
  'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);

// Easy and simple for access to variables with their names
extract($conf);

$conn = new XMPPHP\BOSH($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel);
$conn->autoSubscribe();

try {
    $conn->connect('http://server.tld:5280/xmpp-httpbind');

    while (!$conn->isDisconnected()) {
        $events   = array('message', 'presence', 'end_stream', 'session_start');
        $payloads = $conn->processUntil($events);

        foreach ($payloads as $result) {
            list($event, $data) = $result;

            if (isset($data)) {
                extract($data);
            }

            switch ($event) {

        case 'message':

          if (!$body) {
              break;
          }

          echo str_repeat('-', 80);
          echo "Message from: $from";

          if (isset($subject)) {
              echo "Subject: $subject";
          }

          echo $body;
          echo str_repeat('-', 80);

          $cmd  = explode(' ', $body);
          $body = "Mi no entender! '$body'";
          $conn->message($from, $body, $type);

          if (isset($cmd[0])) {
              if ($cmd[0] == 'quit') {
                  $conn->disconnect();
              }

              if ($cmd[0] == 'break') {
                  $conn->send('</end>');
              }
          }
          break;

        case 'presence':

          echo "Presence: $from [$show] $status\n";
          break;

        case 'session_start':

          echo "Session start\n";
          $conn->getRoster();
          $conn->presence('Quasar!');
          break;
      }
        }
    }
} catch (XMPPHP\Exception $e) {
    die($e->getMessage());
}


code:
<?php

/**
 * @file: XMPPHP Send message example
 *
 * @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
 */
/**
 * Activate full error reporting
 * error_reporting(E_ALL & E_STRICT);
 *
 * XMPPHP Log levels:
 *
 * LEVEL_ERROR   = 0;
 * LEVEL_WARNING = 1;
 * LEVEL_INFO    = 2;
 * LEVEL_DEBUG   = 3;
 * LEVEL_VERBOSE = 4;
 */

require_once __DIR__.'/../vendor/autoload.php';

$conf = array(
  'server'   => 'talk.google.com',
  'port'     => 5222,
  'username' => 'username',
  'password' => 'password',
  'proto'    => 'xmpphp',
  'domain'   => 'gmail.com',
  'printlog' => true,
  'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);

// Easy and simple for access to variables with their names
extract($conf);

$XMPP = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel);

try {
    $XMPP->connect();
    $XMPP->processUntil('session_start', 10);
    $XMPP->presence();
    $XMPP->message('target.user@jabber.domain.com', 'Hello, how are you?', 'chat');
    $XMPP->disconnect();
} catch (XMPPHP\Exception $e) {
    die($e->getMessage());
}


code:
<?php

/**
 * @file: XMPPHP Cli example
 *
 * @info: If this script doesn't work, are you running 64-bit PHP with < 5.2.6?
 */

/**
 * Activate full error reporting
 * error_reporting(E_ALL & E_STRICT);
 *
 * XMPPHP Log levels:
 *
 * LEVEL_ERROR   = 0;
 * LEVEL_WARNING = 1;
 * LEVEL_INFO    = 2;
 * LEVEL_DEBUG   = 3;
 * LEVEL_VERBOSE = 4;
 */

session_start();
header('content-type', 'plain/text');

require '../vendor/autoload.php';

$conf = array(
  'server'   => 'talk.google.com',
  'port'     => 5222,
  'username' => 'username',
  'password' => 'password',
  'proto'    => 'xmpphp',
  'domain'   => 'gmail.com',
  'printlog' => true,
  'loglevel' => XMPPHP\Log::LEVEL_VERBOSE,
);

// Easy and simple for access to variables with their names
extract($conf);

$conn = new XMPPHP\XMPP($server, $port, $username, $password, $proto, $domain, $printlog, $loglevel);
$conn->autoSubscribe();

try {
    if (isset($_SESSION['messages'])) {
        foreach ($_SESSION['messages'] as $message) {
            echo $message;
            flush();
        }
    } else {
        $_SESSION['messages'] = array();
    }

    $conn->connect('http://server.tld:5280/xmpp-httpbind', 1, true);
    $events   = array('message', 'presence', 'end_stream', 'session_start', 'vcard');
    $payloads = $conn->processUntil($events);

    foreach ($payloads as $result) {
        list($event, $data) = $result;

        if (isset($data)) {
            extract($data);
        }

        switch ($event) {

      case 'message':

        if (!$body) {
            break;
        }

        $cmd  = explode(' ', $body);
        $msg  = str_repeat('-', 80);
        $msg .= "\nMessage from: $from\n";

        if (isset($subject)) {
            $msg .= "Subject: $subject\n";
        }

        $msg .= $body . "\n";
        $msg .= str_repeat('-', 80);
        echo "
$msg
";

        if (isset($cmd[0])) {
            if ($cmd[0] == 'quit') {
                $conn->disconnect();
            }

            if ($cmd[0] == 'break') {
                $conn->send('</end>');
            }
        }
        $_SESSION['messages'][] = $msg;
        flush();
        break;

      case 'presence':

        echo "Presence: $from [$show] $status\n";
        break;

      case 'session_start':

        echo "Session start\n";
        $conn->getRoster();
        $conn->presence('Quasar!');
        break;
    }
    }
} catch (XMPPHP\Exception $e) {
    die($e->getMessage());
}

$conn->saveSession();

echo '';


code:
<?php

/**
 * XMPPHP: The PHP XMPP Library
 * Copyright (C) 2008  Nathanael C. Fritz
 * This file is part of SleekXMPP.
 *
 * XMPPHP 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 2 of the License, or
 * (at your option) any later version.
 *
 * XMPPHP 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 XMPPHP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category  xmpphp
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 */

// Get current working directory with trailing slash
define('TESTS_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR);

// Get class directory with trailing slash
define('CLASS_DIR', dirname(TESTS_DIR) . DIRECTORY_SEPARATOR);

/** XMPPHP_LogTest */
require_once TESTS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'LogTest.php';

/** XMPPHP_XMLObjTest */
require_once TESTS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMLObjTest.php';

/** XMPPHP_XMPPTest */
require_once TESTS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMPPTest.php';

if (!defined('PHPUnit_MAIN_METHOD')) {
    define('PHPUnit_MAIN_METHOD', 'AllTests::main');
}

/**
 * XMPPHP AllTests
 *
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 * @version   $Id$
 */
class AllTests
{
    public static function main()
    {
        PHPUnit_TextUI_TestRunner::run(self::suite());
    }

    public static function suite()
    {
        $suite = new PHPUnit_Framework_TestSuite();
        $suite->addTestSuite('XMPPHP_LogTest');
        $suite->addTestSuite('XMPPHP_XMLObjTest');
        $suite->addTestSuite('XMPPHP_XMPPTest');

        return $suite;
    }
}

if (PHPUnit_MAIN_METHOD == 'AllTests::main') {
    AllTests::main();
}


code:
<?php

/**
 * XMPPHP: The PHP XMPP Library
 * Copyright (C) 2008  Nathanael C. Fritz
 * This file is part of SleekXMPP.
 *
 * XMPPHP 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 2 of the License, or
 * (at your option) any later version.
 *
 * XMPPHP 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 XMPPHP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category  xmpphp
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 */

/** XMPPHP_Log */
require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'Log.php';

/**
 * XMPPHP LogTest
 *
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 * @version   $Id$
 */
class XMPPHP_LogTest extends PHPUnit_Framework_TestCase
{
    public function testPrintoutNoOutput()
    {
        $log = new XMPPHP_Log();
        $msg = 'I am a test log message';

        ob_start();
        $log->log('test');
        $result = ob_get_clean();

        $this->assertEquals('', $result);
    }

    public function testPrintoutOutput()
    {
        $log = new XMPPHP_Log(true);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg);
        $result = ob_get_clean();

        $this->assertContains($msg, $result);
    }

    public function testPrintoutNoOutputWithDefaultLevel()
    {
        $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_ERROR);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg);
        $result = ob_get_clean();

        $this->assertSame('', $result);
    }

    public function testPrintoutOutputWithDefaultLevel()
    {
        $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg);
        $result = ob_get_clean();

        $this->assertContains($msg, $result);
    }

    public function testPrintoutNoOutputWithCustomLevel()
    {
        $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg, XMPPHP_Log::LEVEL_DEBUG);
        $result = ob_get_clean();

        $this->assertSame('', $result);
    }

    public function testPrintoutOutputWithCustomLevel()
    {
        $log = new XMPPHP_Log(true, XMPPHP_Log::LEVEL_INFO);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg, XMPPHP_Log::LEVEL_INFO);
        $result = ob_get_clean();

        $this->assertContains($msg, $result);
    }

    public function testExplicitPrintout()
    {
        $log = new XMPPHP_Log(false);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg);
        $result = ob_get_clean();

        $this->assertSame('', $result);
    }

    public function testExplicitPrintoutResult()
    {
        $log = new XMPPHP_Log(false);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg);
        $result = ob_get_clean();

        $this->assertSame('', $result);

        ob_start();
        $log->printout();
        $result = ob_get_clean();

        $this->assertContains($msg, $result);
    }

    public function testExplicitPrintoutClear()
    {
        $log = new XMPPHP_Log(false);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg);
        $result = ob_get_clean();

        $this->assertSame('', $result);

        ob_start();
        $log->printout();
        $result = ob_get_clean();

        $this->assertContains($msg, $result);

        ob_start();
        $log->printout();
        $result = ob_get_clean();

        $this->assertSame('', $result);
    }

    public function testExplicitPrintoutLevel()
    {
        $log = new XMPPHP_Log(false, XMPPHP_Log::LEVEL_ERROR);
        $msg = 'I am a test log message';

        ob_start();
        $log->log($msg);
        $result = ob_get_clean();

        $this->assertSame('', $result);

        ob_start();
        $log->printout(true, XMPPHP_Log::LEVEL_INFO);
        $result = ob_get_clean();

        $this->assertSame('', $result);
    }
}


code:
<?php

/**
 * XMPPHP: The PHP XMPP Library
 * Copyright (C) 2008  Nathanael C. Fritz
 * This file is part of SleekXMPP.
 *
 * XMPPHP 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 2 of the License, or
 * (at your option) any later version.
 *
 * XMPPHP 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 XMPPHP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category  xmpphp
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 */

/** XMPPHP_XMLObj */
require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMLObj.php';

/**
 * XMPPHP XMLObjectTest
 *
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 * @version   $Id$
 */
class XMPPHP_XMLObjTest extends PHPUnit_Framework_TestCase
{
    public function testToStringNameNamespace()
    {
        $xmlobj   = new XMPPHP_XMLObj('testname', 'testNameSpace');
        $expected = '<testname xmlns="testNameSpace"></testname>';
        $result   = $xmlobj->toString();
        $this->assertSame($expected, $result);
    }

    public function testToStringNameNamespaceAttr()
    {
        $xmlobj   = new XMPPHP_XMLObj('testName', 'testNameSpace', array('attr1' => 'valA', 'attr2' => 'valB'));
        $expected = '<testname xmlns="testNameSpace" attr1="valA" attr2="valB"></testname>';
        $result   = $xmlobj->toString();
        $this->assertSame($expected, $result);
    }

    public function testToStringNameNamespaceData()
    {
        $xmlobj   = new XMPPHP_XMLObj('testName', 'testNameSpace', array(), 'I am test data');
        $expected = '<testname xmlns="testNameSpace">I am test data</testname>';
        $result   = $xmlobj->toString();
        $this->assertSame($expected, $result);
    }

    public function testToStringNameNamespaceSub()
    {
        $xmlobj       = new XMPPHP_XMLObj('testName', 'testNameSpace');
        $sub1         = new XMPPHP_XMLObj('subName', 'subNameSpace');
        $xmlobj->subs = array($sub1);
        $expected     = '<testname xmlns="testNameSpace"><subname xmlns="subNameSpace"></subname></testname>';
        $result       = $xmlobj->toString();
        $this->assertSame($expected, $result);
    }
}


code:
<?php

/**
 * XMPPHP: The PHP XMPP Library
 * Copyright (C) 2008  Nathanael C. Fritz
 * This file is part of SleekXMPP.
 *
 * XMPPHP 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 2 of the License, or
 * (at your option) any later version.
 *
 * XMPPHP 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 XMPPHP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category  xmpphp
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 */

/** XMPPHP_XMPP */
require_once CLASS_DIR . 'XMPPHP' . DIRECTORY_SEPARATOR . 'XMPP.php';

/**
 * XMPPHP XMPPTest
 *
 * @package   XMPPHP
 * @author    Nathanael C. Fritz <JID: fritzy@netflint.net>
 * @author    Stephan Wentz <JID: stephan@jabber.wentz.it>
 * @author    Michael Garvin <JID: gar@netflint.net>
 * @copyright 2008 Nathanael C. Fritz
 * @version   $Id$
 */
class XMPPHP_XMPPTest extends PHPUnit_Framework_TestCase
{
    public function testConnectException()
    {
        try {
            $xmpp = new XMPPHP_XMPP('talk.google.com', 1234, 'invalidusername', 'invalidpassword', 'xmpphp', 'talk.google.com', false, XMPPHP_Log::LEVEL_VERBOSE);
            $xmpp->useEncryption(false);
            $xmpp->connect(10);
            $xmpp->processUntil('session_start');
            $xmpp->presence();
            $xmpp->message('stephan@jabber.wentz.it', 'This is a test message!');
            $xmpp->disconnect();
        } catch (XMPPHP_Exception $e) {
            return;
        } catch (Exception $e) {
            $this->fail('Unexpected Exception thrown: '.$e->getMessage());
        }

        $this->fail('Expected XMPPHP_Exception not thrown!');
    }

    public function testAuthException()
    {
        try {
            $xmpp = new XMPPHP_XMPP('jabber.wentz.it', 5222, 'invalidusername', 'invalidpassword', 'xmpphp', 'jabber.wentz.it', true, XMPPHP_Log::LEVEL_VERBOSE);
            $xmpp->useEncryption(false);
            $xmpp->connect(10);
            $xmpp->processUntil('session_start');
            $xmpp->presence();
            $xmpp->message('stephan@jabber.wentz.it', 'This is a test message!');
            $xmpp->disconnect();
        } catch (XMPPHP_Exception $e) {
            return;
        } catch (Exception $e) {
            $this->fail('Unexpected Exception thrown: '.$e->getMessage());
        }

        $this->fail('Expected XMPPHP_Exception not thrown!');
    }
}


code:
CREDITS

Almost everything written by Edward Z. Yang (Ambush Commander).  Lots of thanks
to the DevNetwork Community for their help (see docs/ref-devnetwork.html for
more details), Feyd especially (namely IPv6 and optimization).  Thanks to RSnake
for letting me package his fantastic XSS cheatsheet for a smoketest.

    vim: et sw=4 sts=4

path: vendor/ezyang/htmlpurifier/CREDITS


code:
Install
    How to install HTML Purifier

HTML Purifier is designed to run out of the box, so actually using the
library is extremely easy.  (Although... if you were looking for a
step-by-step installation GUI, you've downloaded the wrong software!)

While the impatient can get going immediately with some of the sample
code at the bottom of this library, it's well worth reading this entire
document--most of the other documentation assumes that you are familiar
with these contents.

---------------------------------------------------------------------------
1.  Compatibility

HTML Purifier is PHP 5 and PHP 7, and is actively tested from PHP 5.0.5
and up. It has no core dependencies with other libraries.

These optional extensions can enhance the capabilities of HTML Purifier:

    * iconv  : Converts text to and from non-UTF-8 encodings
    * bcmath : Used for unit conversion and imagecrash protection
    * tidy   : Used for pretty-printing HTML

These optional libraries can enhance the capabilities of HTML Purifier:

    * CSSTidy : Clean CSS stylesheets using %Core.ExtractStyleBlocks
        Note: You should use the modernized fork of CSSTidy available
        at https://github.com/Cerdic/CSSTidy
    * Net_IDNA2 (PEAR) : IRI support using %Core.EnableIDNA
        Note: This is not necessary for PHP 5.3 or later

---------------------------------------------------------------------------
2.  Reconnaissance

A big plus of HTML Purifier is its inerrant support of standards, so
your web-pages should be standards-compliant.  (They should also use
semantic markup, but that's another issue altogether, one HTML Purifier
cannot fix without reading your mind.)

HTML Purifier can process these doctypes:

* XHTML 1.0 Transitional (default)
* XHTML 1.0 Strict
* HTML 4.01 Transitional
* HTML 4.01 Strict
* XHTML 1.1

...and these character encodings:

* UTF-8 (default)
* Any encoding iconv supports (with crippled internationalization support)

These defaults reflect what my choices would be if I were authoring an
HTML document, however, what you choose depends on the nature of your
codebase.  If you don't know what doctype you are using, you can determine
the doctype from this identifier at the top of your source code:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

...and the character encoding from this code:

    <meta http-equiv="Content-type" content="text/html;charset=ENCODING">

If the character encoding declaration is missing, STOP NOW, and
read 'docs/enduser-utf8.html' (web accessible at
http://htmlpurifier.org/docs/enduser-utf8.html).  In fact, even if it is
present, read this document anyway, as many websites specify their
document's character encoding incorrectly.

---------------------------------------------------------------------------
3.  Including the library

The procedure is quite simple:

    require_once '/path/to/library/HTMLPurifier.auto.php';

This will setup an autoloader, so the library's files are only included
when you use them.

Only the contents in the library/ folder are necessary, so you can remove
everything else when using HTML Purifier in a production environment.

If you installed HTML Purifier via PEAR, all you need to do is:

    require_once 'HTMLPurifier.auto.php';

Please note that the usual PEAR practice of including just the classes you
want will not work with HTML Purifier's autoloading scheme.

Advanced users, read on; other users can skip to section 4.

Autoload compatibility
----------------------

    HTML Purifier attempts to be as smart as possible when registering an
    autoloader, but there are some cases where you will need to change
    your own code to accomodate HTML Purifier. These are those cases:

    PHP VERSION IS LESS THAN 5.1.2, AND YOU'VE DEFINED __autoload
        Because spl_autoload_register() doesn't exist in early versions
        of PHP 5, HTML Purifier has no way of adding itself to the autoload
        stack. Modify your __autoload function to test
        HTMLPurifier_Bootstrap::autoload($class)

        For example, suppose your autoload function looks like this:

            function __autoload($class) {
                require str_replace('_', '/', $class) . '.php';
                return true;
            }

        A modified version with HTML Purifier would look like this:

            function __autoload($class) {
                if (HTMLPurifier_Bootstrap::autoload($class)) return true;
                require str_replace('_', '/', $class) . '.php';
                return true;
            }

        Note that there *is* some custom behavior in our autoloader; the
        original autoloader in our example would work for 99% of the time,
        but would fail when including language files.

    AN __autoload FUNCTION IS DECLARED AFTER OUR AUTOLOADER IS REGISTERED
        spl_autoload_register() has the curious behavior of disabling
        the existing __autoload() handler. Users need to explicitly
        spl_autoload_register('__autoload'). Because we use SPL when it
        is available, __autoload() will ALWAYS be disabled. If __autoload()
        is declared before HTML Purifier is loaded, this is not a problem:
        HTML Purifier will register the function for you. But if it is
        declared afterwards, it will mysteriously not work. This
        snippet of code (after your autoloader is defined) will fix it:

            spl_autoload_register('__autoload')

    Users should also be on guard if they use a version of PHP previous
    to 5.1.2 without an autoloader--HTML Purifier will define __autoload()
    for you, which can collide with an autoloader that was added by *you*
    later.

For better performance
----------------------

    Opcode caches, which greatly speed up PHP initialization for scripts
    with large amounts of code (HTML Purifier included), don't like
    autoloaders. We offer an include file that includes all of HTML Purifier's
    files in one go in an opcode cache friendly manner:

        // If /path/to/library isn't already in your include path, uncomment
        // the below line:
        // require '/path/to/library/HTMLPurifier.path.php';

        require 'HTMLPurifier.includes.php';

    Optional components still need to be included--you'll know if you try to
    use a feature and you get a class doesn't exists error! The autoloader
    can be used in conjunction with this approach to catch classes that are
    missing. Simply add this afterwards:

        require 'HTMLPurifier.autoload.php';

Standalone version
------------------

    HTML Purifier has a standalone distribution; you can also generate
    a standalone file from the full version by running the script
    maintenance/generate-standalone.php . The standalone version has the
    benefit of having most of its code in one file, so parsing is much
    faster and the library is easier to manage.

    If HTMLPurifier.standalone.php exists in the library directory, you
    can use it like this:

        require '/path/to/HTMLPurifier.standalone.php';

    This is equivalent to including HTMLPurifier.includes.php, except that
    the contents of standalone/ will be added to your path. To override this
    behavior, specify a new HTMLPURIFIER_PREFIX where standalone files can
    be found (usually, this will be one directory up, the "true" library
    directory in full distributions). Don't forget to set your path too!

    The autoloader can be added to the end to ensure the classes are
    loaded when necessary; otherwise you can manually include them.
    To use the autoloader, use this:

        require 'HTMLPurifier.autoload.php';

For advanced users
------------------

    HTMLPurifier.auto.php performs a number of operations that can be done
    individually. These are:

        HTMLPurifier.path.php
            Puts /path/to/library in the include path. For high performance,
            this should be done in php.ini.

        HTMLPurifier.autoload.php
            Registers our autoload handler HTMLPurifier_Bootstrap::autoload($class).

    You can do these operations by yourself--in fact, you must modify your own
    autoload handler if you are using a version of PHP earlier than PHP 5.1.2
    (See "Autoload compatibility" above).

---------------------------------------------------------------------------
4. Configuration

HTML Purifier is designed to run out-of-the-box, but occasionally HTML
Purifier needs to be told what to do.  If you answer no to any of these
questions, read on; otherwise, you can skip to the next section (or, if you're
into configuring things just for the heck of it, skip to 4.3).

* Am I using UTF-8?
* Am I using XHTML 1.0 Transitional?

If you answered no to any of these questions, instantiate a configuration
object and read on:

    $config = HTMLPurifier_Config::createDefault();

4.1. Setting a different character encoding

You really shouldn't use any other encoding except UTF-8, especially if you
plan to support multilingual websites (read section three for more details).
However, switching to UTF-8 is not always immediately feasible, so we can
adapt.

HTML Purifier uses iconv to support other character encodings, as such,
any encoding that iconv supports <http://www.gnu.org/software/libiconv/>
HTML Purifier supports with this code:

    $config->set('Core.Encoding', /* put your encoding here */);

An example usage for Latin-1 websites (the most common encoding for English
websites):

    $config->set('Core.Encoding', 'ISO-8859-1');

Note that HTML Purifier's support for non-Unicode encodings is crippled by the
fact that any character not supported by that encoding will be silently
dropped, EVEN if it is ampersand escaped.  If you want to work around
this, you are welcome to read docs/enduser-utf8.html for a fix,
but please be cognizant of the issues the "solution" creates (for this
reason, I do not include the solution in this document).

4.2. Setting a different doctype

For those of you using HTML 4.01 Transitional, you can disable
XHTML output like this:

    $config->set('HTML.Doctype', 'HTML 4.01 Transitional');

Other supported doctypes include:

    * HTML 4.01 Strict
    * HTML 4.01 Transitional
    * XHTML 1.0 Strict
    * XHTML 1.0 Transitional
    * XHTML 1.1

4.3. Other settings

There are more configuration directives which can be read about
here: <http://htmlpurifier.org/live/configdoc/plain.html>  They're a bit boring,
but they can help out for those of you who like to exert maximum control over
your code.  Some of the more interesting ones are configurable at the
demo <http://htmlpurifier.org/demo.php> and are well worth looking into
for your own system.

For example, you can fine tune allowed elements and attributes, convert
relative URLs to absolute ones, and even autoparagraph input text! These
are, respectively, %HTML.Allowed, %URI.MakeAbsolute and %URI.Base, and
%AutoFormat.AutoParagraph. The %Namespace.Directive naming convention
translates to:

    $config->set('Namespace.Directive', $value);

E.g.

    $config->set('HTML.Allowed', 'p,b,a[href],i');
    $config->set('URI.Base', 'http://www.example.com');
    $config->set('URI.MakeAbsolute', true);
    $config->set('AutoFormat.AutoParagraph', true);

---------------------------------------------------------------------------
5. Caching

HTML Purifier generates some cache files (generally one or two) to speed up
its execution. For maximum performance, make sure that
library/HTMLPurifier/DefinitionCache/Serializer is writeable by the webserver.

If you are in the library/ folder of HTML Purifier, you can set the
appropriate permissions using:

    chmod -R 0755 HTMLPurifier/DefinitionCache/Serializer

If the above command doesn't work, you may need to assign write permissions
to group:

    chmod -R 0775 HTMLPurifier/DefinitionCache/Serializer

You can also chmod files via your FTP client; this option
is usually accessible by right clicking the corresponding directory and
then selecting "chmod" or "file permissions".

Starting with 2.0.1, HTML Purifier will generate friendly error messages
that will tell you exactly what you have to chmod the directory to, if in doubt,
follow its advice.

If you are unable or unwilling to give write permissions to the cache
directory, you can either disable the cache (and suffer a performance
hit):

    $config->set('Core.DefinitionCache', null);

Or move the cache directory somewhere else (no trailing slash):

    $config->set('Cache.SerializerPath', '/home/user/absolute/path');

---------------------------------------------------------------------------
6.   Using the code

The interface is mind-numbingly simple:

    $purifier = new HTMLPurifier($config);
    $clean_html = $purifier->purify( $dirty_html );

That's it!  For more examples, check out docs/examples/ (they aren't very
different though).  Also, docs/enduser-slow.html gives advice on what to
do if HTML Purifier is slowing down your application.

---------------------------------------------------------------------------
7.   Quick install

First, make sure library/HTMLPurifier/DefinitionCache/Serializer is
writable by the webserver (see Section 5: Caching above for details).
If your website is in UTF-8 and XHTML Transitional, use this code:

<?php
    require_once '/path/to/htmlpurifier/library/HTMLPurifier.auto.php';

    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    $clean_html = $purifier->purify($dirty_html);
?>

If your website is in a different encoding or doctype, use this code:

<?php
    require_once '/path/to/htmlpurifier/library/HTMLPurifier.auto.php';

    $config = HTMLPurifier_Config::createDefault();
    $config->set('Core.Encoding', 'ISO-8859-1'); // replace with your encoding
    $config->set('HTML.Doctype', 'HTML 4.01 Transitional'); // replace with your doctype
    $purifier = new HTMLPurifier($config);

    $clean_html = $purifier->purify($dirty_html);
?>

    vim: et sw=4 sts=4

path: vendor/ezyang/htmlpurifier/INSTALL


code:
Installation
    Comment installer HTML Purifier

Attention : Ce document est encodé en UTF-8, si les lettres avec des accents
ne s'affichent pas, prenez un meilleur éditeur de texte.

L'installation de HTML Purifier est très simple, parce qu'il n'a pas besoin
de configuration. Pour les utilisateurs impatients, le code se trouve dans le
pied de page, mais je recommande de lire le document.

1.  Compatibilité

HTML Purifier fonctionne avec PHP 5. PHP 5.0.5 est la dernière version testée.
Il ne dépend pas d'autres librairies.

Les extensions optionnelles sont iconv (généralement déjà installée) et tidy
(répendue aussi). Si vous utilisez UTF-8 et que vous ne voulez pas l'indentation,
vous pouvez utiliser HTML Purifier sans ces extensions.

2.  Inclure la librairie

Quand vous devez l'utilisez, incluez le :

    require_once('/path/to/library/HTMLPurifier.auto.php');

Ne pas l'inclure si ce n'est pas nécessaire, car HTML Purifier est lourd.

HTML Purifier utilise "autoload". Si vous avez défini la fonction __autoload,
vous devez ajouter cette fonction :

    spl_autoload_register('__autoload')

Plus d'informations dans le document "INSTALL".

3.  Installation rapide

Si votre site Web est en UTF-8 et XHTML Transitional, utilisez :

<?php
    require_once('/path/to/htmlpurifier/library/HTMLPurifier.auto.php');
    $purificateur = new HTMLPurifier();
    $html_propre = $purificateur->purify($html_a_purifier);
?>

Sinon, utilisez :

<?php
    require_once('/path/to/html/purifier/library/HTMLPurifier.auto.load');
    $config = $HTMLPurifier_Config::createDefault();
    $config->set('Core', 'Encoding', 'ISO-8859-1'); //Remplacez par votre
    encodage
    $config->set('Core', 'XHTML', true); //Remplacer par false si HTML 4.01
    $purificateur = new HTMLPurifier($config);
    $html_propre = $purificateur->purify($html_a_purifier);
?>

    vim: et sw=4 sts=4