]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-20743 imported latest jabber library 0.1rc2-r77
authorPetr Skoda <skodak@moodle.org>
Wed, 4 Nov 2009 20:23:33 +0000 (20:23 +0000)
committerPetr Skoda <skodak@moodle.org>
Wed, 4 Nov 2009 20:23:33 +0000 (20:23 +0000)
lib/jabber/XMPP/BOSH.php [new file with mode: 0644]
lib/jabber/XMPP/Exception.php
lib/jabber/XMPP/Log.php
lib/jabber/XMPP/README.txt
lib/jabber/XMPP/Roster.php [new file with mode: 0644]
lib/jabber/XMPP/XMLObj.php
lib/jabber/XMPP/XMLStream.php
lib/jabber/XMPP/XMPP.php
lib/jabber/XMPP/XMPP_Old.php
lib/jabber/readme_moodle.txt [new file with mode: 0644]

diff --git a/lib/jabber/XMPP/BOSH.php b/lib/jabber/XMPP/BOSH.php
new file mode 100644 (file)
index 0000000..befaf60
--- /dev/null
@@ -0,0 +1,188 @@
+<?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_XMLStream */
+require_once dirname(__FILE__) . "/XMPP.php";
+
+/**
+ * XMPPHP Main Class
+ * 
+ * @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
+ * @version    $Id$
+ */
+class XMPPHP_BOSH extends XMPPHP_XMPP {
+
+               protected $rid;
+               protected $sid;
+               protected $http_server;
+               protected $http_buffer = Array();
+               protected $session = false;
+
+               public function connect($server, $wait='1', $session=false) {
+                       $this->http_server = $server;
+                       $this->use_encryption = false;
+                       $this->session = $session;
+
+                       $this->rid = 3001;
+                       $this->sid = null;
+                       if($session)
+                       {
+                               $this->loadSession();
+                       }
+                       if(!$this->sid) {
+                               $body = $this->__buildBody();
+                               $body->addAttribute('hold','1');
+                               $body->addAttribute('to', $this->host);
+                               $body->addAttribute('route', "xmpp:{$this->host}:{$this->port}");
+                               $body->addAttribute('secure','true');
+                               $body->addAttribute('xmpp:version','1.6', 'urn:xmpp:xbosh');
+                               $body->addAttribute('wait', strval($wait));
+                               $body->addAttribute('ack','1');
+                               $body->addAttribute('xmlns:xmpp','urn:xmpp:xbosh');
+                               $buff = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>";
+                               xml_parse($this->parser, $buff, false);
+                               $response = $this->__sendBody($body);
+                               $rxml = new SimpleXMLElement($response);
+                               $this->sid = $rxml['sid'];
+
+                       } else {
+                               $buff = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>";
+                               xml_parse($this->parser, $buff, false);
+                       }
+               }
+
+               public function __sendBody($body=null, $recv=true) {
+                       if(!$body) {
+                               $body = $this->__buildBody();
+                       }
+                       $ch = curl_init($this->http_server);
+                       curl_setopt($ch, CURLOPT_HEADER, 0);
+                       curl_setopt($ch, CURLOPT_POST, 1);
+                       curl_setopt($ch, CURLOPT_POSTFIELDS, $body->asXML());
+                       curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
+                       $header = array('Accept-Encoding: gzip, deflate','Content-Type: text/xml; charset=utf-8');
+                       curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
+                       curl_setopt($ch, CURLOPT_VERBOSE, 0);
+                       $output = '';
+                       if($recv) {
+                               curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+                               $output = curl_exec($ch);
+                               $this->http_buffer[] = $output;
+                       }
+                       curl_close($ch);
+                       return $output;
+               }
+
+               public function __buildBody($sub=null) {
+                       $xml = new SimpleXMLElement("<body xmlns='http://jabber.org/protocol/httpbind' xmlns:xmpp='urn:xmpp:xbosh' />");
+                       $xml->addAttribute('content', 'text/xml; charset=utf-8');
+                       $xml->addAttribute('rid', $this->rid);
+                       $this->rid += 1;
+                       if($this->sid) $xml->addAttribute('sid', $this->sid);
+                       #if($this->sid) $xml->addAttribute('xmlns', 'http://jabber.org/protocol/httpbind');
+                       $xml->addAttribute('xml:lang', 'en');
+                       if($sub) { // ok, so simplexml is lame
+                               $p = dom_import_simplexml($xml);
+                               $c = dom_import_simplexml($sub);
+                               $cn = $p->ownerDocument->importNode($c, true);
+                               $p->appendChild($cn);
+                               $xml = simplexml_import_dom($p);
+                       }
+                       return $xml;
+               }
+
+               public function __process() {
+                       if($this->http_buffer) {
+                               $this->__parseBuffer();
+                       } else {
+                               $this->__sendBody();
+                               $this->__parseBuffer();
+                       }
+               }
+
+               public function __parseBuffer() {
+                       while ($this->http_buffer) {
+                               $idx = key($this->http_buffer);
+                               $buffer = $this->http_buffer[$idx];
+                               unset($this->http_buffer[$idx]);
+                               if($buffer) {
+                                       $xml = new SimpleXMLElement($buffer);
+                                       $children = $xml->xpath('child::node()');
+                                       foreach ($children as $child) {
+                                               $buff = $child->asXML();
+                                               $this->log->log("RECV: $buff",  XMPPHP_Log::LEVEL_VERBOSE);
+                                               xml_parse($this->parser, $buff, false);
+                                       }
+                               }
+                       }
+               }
+
+               public function send($msg) {
+                       $this->log->log("SEND: $msg",  XMPPHP_Log::LEVEL_VERBOSE);
+                       $msg = new SimpleXMLElement($msg);
+                       #$msg->addAttribute('xmlns', 'jabber:client');
+                       $this->__sendBody($this->__buildBody($msg), true);
+                       #$this->__parseBuffer();
+               }
+
+               public function reset() {
+                       $this->xml_depth = 0;
+                       unset($this->xmlobj);
+                       $this->xmlobj = array();
+                       $this->setupParser();
+                       #$this->send($this->stream_start);
+                       $body = $this->__buildBody();
+                       $body->addAttribute('to', $this->host);
+                       $body->addAttribute('xmpp:restart', 'true', 'urn:xmpp:xbosh');
+                       $buff = "<stream:stream xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>";
+                       $response = $this->__sendBody($body);
+                       $this->been_reset = true;
+                       xml_parse($this->parser, $buff, false);
+               }
+
+               public function loadSession() {
+                       if(isset($_SESSION['XMPPHP_BOSH_RID'])) $this->rid = $_SESSION['XMPPHP_BOSH_RID'];
+                       if(isset($_SESSION['XMPPHP_BOSH_SID'])) $this->sid = $_SESSION['XMPPHP_BOSH_SID'];
+                       if(isset($_SESSION['XMPPHP_BOSH_authed'])) $this->authed = $_SESSION['XMPPHP_BOSH_authed'];
+                       if(isset($_SESSION['XMPPHP_BOSH_jid'])) $this->jid = $_SESSION['XMPPHP_BOSH_jid'];
+                       if(isset($_SESSION['XMPPHP_BOSH_fulljid'])) $this->fulljid = $_SESSION['XMPPHP_BOSH_fulljid'];
+               }
+
+               public function saveSession() {
+                       $_SESSION['XMPPHP_BOSH_RID'] = (string) $this->rid;
+                       $_SESSION['XMPPHP_BOSH_SID'] = (string) $this->sid;
+                       $_SESSION['XMPPHP_BOSH_authed'] = (boolean) $this->authed;
+                       $_SESSION['XMPPHP_BOSH_jid'] = (string) $this->jid;
+                       $_SESSION['XMPPHP_BOSH_fulljid'] = (string) $this->fulljid;
+               }
+}
index 32b2e0924059fb60fc275301e763a65e3323260c..da59bc7918b3f14f67352f95a6510beb0b5d931a 100755 (executable)
@@ -22,6 +22,7 @@
  * @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
  */
 
@@ -32,6 +33,7 @@
  * @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$
  */
index 635e68da475cada8b4cc8c00c76b2a077cbc0943..a9bce3d8410056612b2f20095e11390d78169a8c 100644 (file)
@@ -22,6 +22,7 @@
  * @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
  */
 
@@ -31,6 +32,7 @@
  * @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$
  */
@@ -82,7 +84,7 @@ class XMPPHP_Log {
         */
        public function log($msg, $runlevel = self::LEVEL_INFO) {
                $time = time();
-               $this->data[] = array($this->runlevel, $msg, $time);
+               #$this->data[] = array($this->runlevel, $msg, $time);
                if($this->printout and $runlevel <= $this->runlevel) {
                        $this->writeLine($msg, $runlevel, $time);
                }
@@ -112,5 +114,6 @@ class XMPPHP_Log {
        protected function writeLine($msg, $runlevel, $time) {
                //echo date('Y-m-d H:i:s', $time)." [".$this->names[$runlevel]."]: ".$msg."\n";
                echo $time." [".$this->names[$runlevel]."]: ".$msg."\n";
+               flush();
        }
 }
index 808a61f1d28d0633cdf9312277f1c00a6f7f437c..0c2f53df6d9bc0146b2d3fb5ad59d04deb6ed2ef 100644 (file)
@@ -31,9 +31,13 @@ documentation on the website.
 
 TODO
 ================================================================================
-* Rosters (I know, a big one)
 * Documentation
-* TLS Cert Inspection (Even possible in PHP?)
 * MUC Support
-* Plugins
-* XML Masking Handlers
+
+License Exception
+===============================================================================
+Please contact Nathan Fritz for library exceptions if you would like to
+distribute XMPPHP with a non-GPL compatible license.
+
+Also, if you would like to distribute XMPPHP as part of a commercial package,
+I sell commercial licenses.
diff --git a/lib/jabber/XMPP/Roster.php b/lib/jabber/XMPP/Roster.php
new file mode 100644 (file)
index 0000000..2e459e2
--- /dev/null
@@ -0,0 +1,163 @@
+<?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 Roster Object
+ * 
+ * @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
+ * @version    $Id$
+ */
+
+class Roster {
+       /**
+        * Roster array, handles contacts and presence.  Indexed by jid.
+        * Contains array with potentially two indexes 'contact' and 'presence'
+        * @var array
+        */
+       protected $roster_array = array();
+       /**
+        * Constructor
+        * 
+        */
+       public function __construct($roster_array = array()) {
+               if ($this->verifyRoster($roster_array)) {
+                       $this->roster_array = $roster_array; //Allow for prepopulation with existing roster
+               } else {
+                       $this->roster_array = array();
+               }
+       }
+
+       /**
+        *
+        * Check that a given roster array is of a valid structure (empty is still valid)
+        *
+        * @param array $roster_array
+        */
+       protected function verifyRoster($roster_array) {
+               #TODO once we know *what* a valid roster array looks like
+               return True;
+       }
+
+       /**
+        *
+        * Add given contact to roster
+        *
+        * @param string $jid
+        * @param string $subscription
+        * @param string $name
+        * @param array $groups
+        */
+       public function addContact($jid, $subscription, $name='', $groups=array()) {
+               $contact = array('jid' => $jid, 'subscription' => $subscription, 'name' => $name, 'groups' => $groups);
+               if ($this->isContact($jid)) {
+                       $this->roster_array[$jid]['contact'] = $contact;
+               } else {
+                       $this->roster_array[$jid] = array('contact' => $contact);
+               }
+       }
+
+       /**
+        * 
+        * Retrieve contact via jid
+        *
+        * @param string $jid
+        */
+       public function getContact($jid) {
+               if ($this->isContact($jid)) {
+                       return $this->roster_array[$jid]['contact'];
+               }
+       }
+
+       /**
+        *
+        * Discover if a contact exists in the roster via jid
+        *
+        * @param string $jid
+        */
+       public function isContact($jid) {
+               return (array_key_exists($jid, $this->roster_array));
+       }
+
+       /**
+        *
+        * Set presence
+        *
+        * @param string $presence
+        * @param integer $priority
+        * @param string $show
+        * @param string $status
+       */
+       public function setPresence($presence, $priority, $show, $status) {
+               list($jid, $resource) = split("/", $presence);
+               if ($show != 'unavailable') {
+                       if (!$this->isContact($jid)) {
+                               $this->addContact($jid, 'not-in-roster');
+                       }
+                       $resource = $resource ? $resource : '';
+                       $this->roster_array[$jid]['presence'][$resource] = array('priority' => $priority, 'show' => $show, 'status' => $status);
+               } else { //Nuke unavailable resources to save memory
+                       unset($this->roster_array[$jid]['resource'][$resource]);
+               }
+       }
+
+       /*
+        *
+        * Return best presence for jid
+        *
+        * @param string $jid
+        */
+       public function getPresence($jid) {
+               $split = split("/", $jid);
+               $jid = $split[0];
+               if($this->isContact($jid)) {
+                       $current = array('resource' => '', 'active' => '', 'priority' => -129, 'show' => '', 'status' => ''); //Priorities can only be -128 = 127
+                       foreach($this->roster_array[$jid]['presence'] as $resource => $presence) {
+                               //Highest available priority or just highest priority
+                               if ($presence['priority'] > $current['priority'] and (($presence['show'] == "chat" or $presence['show'] == "available") or ($current['show'] != "chat" or $current['show'] != "available"))) {
+                                       $current = $presence;
+                                       $current['resource'] = $resource;
+                               }
+                       }
+                       return $current;
+               }
+       }
+       /**
+        *
+        * Get roster
+        *
+        */
+       public function getRoster() {
+               return $this->roster_array;
+       }
+}
+?>
index 79fef9b243c718a2f9af2823be509b6414188fad..0d3e21991204d32b3752f4bab9d7f30d9263af27 100644 (file)
@@ -22,6 +22,7 @@
  * @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
  */
 
@@ -32,6 +33,7 @@
  * @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$
  */
@@ -131,9 +133,9 @@ class XMPPHP_XMLObj {
         * @param string $name
         * @return boolean
         */
-       public function hasSub($name) {
+       public function hasSub($name, $ns = null) {
                foreach($this->subs as $sub) {
-                       if($sub->name == $name) return true;
+                       if(($name == "*" or $sub->name == $name) and ($ns == null or $sub->ns == $ns)) return true;
                }
                return false;
        }
@@ -146,8 +148,9 @@ class XMPPHP_XMLObj {
         * @param string $ns
         */
        public function sub($name, $attrs = null, $ns = null) {
+               #TODO attrs is ignored
                foreach($this->subs as $sub) {
-                       if($sub->name == $name) {
+                       if($sub->name == $name and ($ns == null or $sub->ns == $ns)) {
                                return $sub;
                        }
                }
index d3c59de53e5a4e1667759a23539965957fd7062e..d33411ec54140dafc1c527c946d05cbc931807c9 100644 (file)
  * @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_Exception */
-require_once 'Exception.php';
+require_once dirname(__FILE__) . '/Exception.php';
 
 /** XMPPHP_XMLObj */
-require_once 'XMLObj.php';
+require_once dirname(__FILE__) . '/XMLObj.php';
 
 /** XMPPHP_Log */
-require_once 'Log.php';
+require_once dirname(__FILE__) . '/Log.php';
 
 /**
  * XMPPHP XML Stream
@@ -41,6 +42,7 @@ require_once 'Log.php';
  * @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$
  */
@@ -101,6 +103,10 @@ class XMPPHP_XMLStream {
         * @var array
         */
        protected $nshandlers = array();
+       /**
+        * @var array
+        */
+       protected $xpathhandlers = array();
        /**
         * @var array
         */
@@ -121,6 +127,10 @@ class XMPPHP_XMLStream {
         * @var string
         */
        protected $until = '';
+       /**
+        * @var string
+        */
+       protected $until_count = '';
        /**
         * @var array
         */
@@ -149,6 +159,14 @@ class XMPPHP_XMLStream {
         * @var float
         */
        protected $last_send = 0;
+       /**
+        * @var boolean
+        */
+       protected $use_ssl = false;
+       /**
+        * @var integer
+        */
+       protected $reconnectTimeout = 30;
 
        /**
         * Constructor
@@ -197,6 +215,15 @@ class XMPPHP_XMLStream {
                return $this->lastid;
        }
 
+       /**
+        * Set SSL
+        *
+        * @return integer
+        */
+       public function useSSL($use=true) {
+               $this->use_ssl = $use;
+       }
+
        /**
         * Add ID Handler
         *
@@ -211,25 +238,51 @@ class XMPPHP_XMLStream {
        /**
         * Add Handler
         *
-        * @param integer $id
+        * @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 Evemt Handler
+        * 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) = split("}", $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 integer $id
         * @param string  $pointer
         * @param string  $obj
         */
        public function addEventHandler($name, $pointer, $obj) {
-               $this->eventhanders[] = array($name, $pointer, $obj);
+               $this->eventhandlers[] = array($name, $pointer, $obj);
        }
 
        /**
@@ -240,27 +293,39 @@ class XMPPHP_XMLStream {
         * @param boolean $sendinit
         */
        public function connect($timeout = 30, $persistent = false, $sendinit = true) {
-               $this->disconnected = false;
                $this->sent_disconnect = false;
-               if($persistent) {
-                       $conflag = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
+               $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}");
+                       try {
+                               $this->socket = @stream_socket_client("$conntype://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
+                       } catch (Exception $e) {
+                               throw new XMPPHP_Exception($e->getMessage());
+                       }
+                       if(!$this->socket) {
+                               $this->log->log("Could not connect.",  XMPPHP_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 {
-                       $conflag = STREAM_CLIENT_CONNECT;
-               }
-               $this->log->log("Connecting to tcp://{$this->host}:{$this->port}");
-               try {
-                       $this->socket = @stream_socket_client("tcp://{$this->host}:{$this->port}", $errno, $errstr, $timeout, $conflag);
-               } catch (Exception $e) {
-                       throw new XMPPHP_Exception($e->getMessage());
+                       throw new XMPPHP_Exception("Could not connect before timeout.");
                }
-               if(!$this->socket) {
-                       $this->log->log("Could not connect.",  XMPPHP_Log::LEVEL_ERROR);
-                       $this->disconnected = true;
-                       
-                       throw new XMPPHP_Exception('Could not connect.');
-               }
-               stream_set_blocking($this->socket, 1);
-               if($sendinit) $this->send($this->stream_start);
        }
 
        /**
@@ -268,17 +333,25 @@ class XMPPHP_XMLStream {
         */
        public function doReconnect() {
                if(!$this->is_server) {
-                       $this->log->log("Reconnecting...",  XMPPHP_Log::LEVEL_WARNING);
-                       $this->connect(30, false, false);
+                       $this->log->log("Reconnecting ($this->reconnectTimeout)...",  XMPPHP_Log::LEVEL_WARNING);
+                       $this->connect($this->reconnectTimeout, false, false);
                        $this->reset();
+                       $this->event('reconnect');
                }
        }
 
+       public function setReconnectTimeout($timeout) {
+               $this->reconnectTimeout = $timeout;
+       }
+       
        /**
         * Disconnect from XMPP Host
         */
        public function disconnect() {
                $this->log->log("Disconnecting...",  XMPPHP_Log::LEVEL_VERBOSE);
+               if(false == (bool) $this->socket) {
+                       return;
+               }
                $this->reconnect = false;
                $this->send($this->stream_end);
                $this->sent_disconnect = true;
@@ -295,24 +368,64 @@ class XMPPHP_XMLStream {
                return $this->disconnected;
        }
 
-       private function __process() {
-               $read = array($this->socket);
-               $write = null;
-               $except = null;
-               $updated = @stream_select($read, $write, $except, 1);
-               if ($updated > 0) {
-                       $buff = @fread($this->socket, 1024);
-                       if(!$buff) { 
-                               if($this->reconnect) {
+       /**
+        * Core reading tool
+        * 0 -> only read if data is immediately ready
+        * NULL -> wait forever and ever
+        * integer -> process for this amount of time 
+        */
+       
+       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()",  XMPPHP_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",  XMPPHP_Log::LEVEL_VERBOSE);
+                               xml_parse($this->parser, $buff, false);
+                       } else {
+                               # $updated == 0 means no changes during timeout.
                        }
-                       $this->log->log("RECV: $buff",  XMPPHP_Log::LEVEL_VERBOSE);
-                       xml_parse($this->parser, $buff, false);
-               }
+                       $endtime = (microtime(true)*1000000);
+                       $time_past = $endtime - $starttime;
+                       $remaining = $remaining - $time_past;
+               } while (is_null($maximum) || $remaining > 0);
+               return true;
        }
        
        /**
@@ -321,10 +434,7 @@ class XMPPHP_XMLStream {
         * @return string
         */
        public function process() {
-               $updated = '';
-               while(!$this->disconnect) {
-                       $this->__process();
-               }
+               $this->__process(NULL);
        }
 
        /**
@@ -333,11 +443,11 @@ class XMPPHP_XMLStream {
         * @param integer $timeout
         * @return string
         */
-       public function processTime($timeout = -1) {
-               $start = time();
-               $updated = '';
-               while(!$this->disconnected and ($timeout == -1 or time() - $start < $timeout)) {
-                       $this->__process();
+       public function processTime($timeout=NULL) {
+               if (is_null($timeout)) {
+                       return $this->__process(NULL);
+               } else {
+                       return $this->__process($timeout * 1000000);
                }
        }
 
@@ -355,16 +465,19 @@ class XMPPHP_XMLStream {
                end($this->until);
                $event_key = key($this->until);
                reset($this->until);
+               $this->until_count[$event_key] = 0;
                $updated = '';
-               while(!$this->disconnected and $this->until[$event_key] and (time() - $start < $timeout or $timeout == -1)) {
+               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();
                }
-               unset($this->until_payload[$event_key]);
                return $payload;
        }
 
@@ -434,9 +547,30 @@ class XMPPHP_XMLStream {
                $this->xml_depth--;
                if($this->xml_depth == 1) {
                        #clean-up old objects
-                       $found = false;
+                       #$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]}",  XMPPHP_Log::LEVEL_DEBUG);
+                                                       $handler[2]->$handler[1]($this->xmlobj[2]);
+                                               }
+                                       }
+                               }
+                       }
                        foreach($this->nshandlers as $handler) {
-                               if($handler[4] != 1 and $this->xmlobj[2]->hasSub($handler[0])) {
+                               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];
@@ -513,7 +647,11 @@ class XMPPHP_XMLStream {
                        if(is_array($until)) {
                                if(in_array($name, $until)) {
                                        $this->until_payload[$key][] = array($name, $payload);
-                                       $this->until[$key] = false;
+                                       if(!isset($this->until_count[$key])) {
+                                               $this->until_count[$key] = 0;
+                                       }
+                                       $this->until_count[$key] += 1;
+                                       #$this->until[$key] = false;
                                }
                        }
                }
@@ -541,34 +679,47 @@ class XMPPHP_XMLStream {
         *
         * @param string $msg
         */
-       public function send($msg, $rec=false) {
-               if($this->time() - $this->last_send < .1) {
-                       usleep(100000);
+       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);
                }
-               $wait = true;
-               while($wait) {
-                       $read = null;
-                       $write = array($this->socket);
-                       $except = null;
-                       $select = @stream_select($read, $write, $except, 0, 0);
-                       if($select === False) {
-                               $this->doReconnect();
-                               return false;
-                       } elseif ($select > 0) {
-                               $wait = false;
-                       } else {
-                               usleep(100000);
-                               //$this->processTime(.25);
-                       }
+               
+               $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.", XMPPHP_Log::LEVEL_VERBOSE);
+               } else {
+                       $this->log->log("Socket is not ready; break.", XMPPHP_Log::LEVEL_ERROR);
+                       return false;
                }
-               $sentbytes = @fwrite($this->socket, $msg, 1024);
-               $this->last_send = $this->time();
-               $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'),  XMPPHP_Log::LEVEL_VERBOSE);
+               
+               $sentbytes = @fwrite($this->socket, $msg);
+               $this->log->log("SENT: " . mb_substr($msg, 0, $sentbytes, '8bit'), XMPPHP_Log::LEVEL_VERBOSE);
                if($sentbytes === FALSE) {
+                       $this->log->log("ERROR sending message; reconnecting.", XMPPHP_Log::LEVEL_ERROR);
                        $this->doReconnect();
-               } elseif ($sentbytes != mb_strlen($msg, '8bit')) {
-                       $this->send(mb_substr($msg, $sentbytes, mb_strlen($msg, '8bit'), '8bit'), true);
+                       return false;
                }
+               $this->log->log("Successfully sent $sentbytes bytes.", XMPPHP_Log::LEVEL_VERBOSE);
+               return $sentbytes;
        }
 
        public function time() {
@@ -601,4 +752,12 @@ class XMPPHP_XMLStream {
                xml_set_element_handler($this->parser, 'startXML', 'endXML');
                xml_set_character_data_handler($this->parser, 'charXML');
        }
+
+       public function readyToProcess() {
+               $read = array($this->socket);
+               $write = array();
+               $except = array();
+               $updated = @stream_select($read, $write, $except, 0);
+               return (($updated !== false) && ($updated > 0));
+       }
 }
index 5ba409513392f20cd029fa93444a1a3ee6d770cb..c0f8963396bdb5e2e6d298480bf36ca35988fac8 100644 (file)
  * @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_XMLStream */
-require_once "XMLStream.php";
+require_once dirname(__FILE__) . "/XMLStream.php";
+require_once dirname(__FILE__) . "/Roster.php";
 
 /**
  * XMPPHP Main Class
@@ -35,6 +37,7 @@ require_once "XMLStream.php";
  * @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$
  */
@@ -42,12 +45,12 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
        /**
         * @var string
         */
-       protected $server;
+       public $server;
 
        /**
         * @var string
         */
-       protected $user;
+       public $user;
        
        /**
         * @var string
@@ -73,6 +76,7 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
         * @var boolean
         */
        protected $authed = false;
+       protected $session_started = false;
        
        /**
         * @var boolean
@@ -84,6 +88,16 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
         */
        protected $use_encryption = true;
        
+       /**
+        * @var boolean
+        */
+       public $track_presence = true;
+       
+       /**
+        * @var object
+        */
+       public $roster;
+
        /**
         * Constructor
         *
@@ -105,16 +119,20 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
                if(!$server) $server = $host;
                $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->addHandler('features', 'http://etherx.jabber.org/streams', 'features_handler');
-               $this->addHandler('success', 'urn:ietf:params:xml:ns:xmpp-sasl', 'sasl_success_handler');
-               $this->addHandler('failure', 'urn:ietf:params:xml:ns:xmpp-sasl', 'sasl_failure_handler');
-               $this->addHandler('proceed', 'urn:ietf:params:xml:ns:xmpp-tls', 'tls_proceed_handler');
-               $this->addHandler('message', 'jabber:client', 'message_handler');
-               $this->addHandler('presence', 'jabber:client', 'presence_handler');
+               $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');
        }
 
        /**
@@ -144,11 +162,16 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
         * @param string $subject
         */
        public function message($to, $body, $type = 'chat', $subject = null, $payload = null) {
+           if(is_null($type))
+           {
+               $type = 'chat';
+           }
+           
                $to       = htmlspecialchars($to);
                $body   = htmlspecialchars($body);
                $subject = htmlspecialchars($subject);
                
-               $out = "<message from='{$this->fulljid}' to='$to' type='$type'>";
+               $out = "<message from=\"{$this->fulljid}\" to=\"$to\" type='$type'>";
                if($subject) $out .= "<subject>$subject</subject>";
                $out .= "<body>$body</body>";
                if($payload) $out .= $payload;
@@ -164,14 +187,14 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
         * @param string $show
         * @param string $to
         */
-       public function presence($status = null, $show = 'available', $to = null, $type='available') {
+       public function presence($status = null, $show = 'available', $to = null, $type='available', $priority=0) {
                if($type == 'available') $type = '';
                $to      = htmlspecialchars($to);
                $status = htmlspecialchars($status);
                if($show == 'unavailable') $type = 'unavailable';
                
                $out = "<presence";
-               if($to) $out .= " to='$to'";
+               if($to) $out .= " to=\"$to\"";
                if($type) $out .= " type='$type'";
                if($show == 'available' and !$status) {
                        $out .= "/>";
@@ -179,11 +202,21 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
                        $out .= ">";
                        if($show != 'available') $out .= "<show>$show</show>";
                        if($status) $out .= "<status>$status</status>";
+                       if($priority) $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
@@ -198,6 +231,7 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
                }
                $payload['from'] = $xml->attrs['from'];
                $payload['body'] = $xml->sub('body')->data;
+               $payload['xml'] = $xml;
                $this->log->log("Message: {$xml->sub('body')->data}", XMPPHP_Log::LEVEL_DEBUG);
                $this->event('message', $payload);
        }
@@ -212,11 +246,19 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
                $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']}",  XMPPHP_Log::LEVEL_DEBUG);
-               if($xml->attrs['type'] == 'subscribe') {
-                       if($this->auto_subscribe) $this->send("<presence type='subscribed' to='{$xml->attrs['from']}' from='{$this->fulljid}' /><presence type='subscribe' to='{$xml->attrs['from']}' from='{$this->fulljid}' />");
+               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($xml->attrs['type'] == 'subscribed') {
+               } elseif(array_key_exists('type', $xml->attrs) and $xml->attrs['type'] == 'subscribed') {
                        $this->event('subscription_accepted', $payload);
                } else {
                        $this->event('presence', $payload);
@@ -231,13 +273,17 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
        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')) {
+               } 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'/>");
+                       }       
                }
        }
 
@@ -273,6 +319,8 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
                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');
@@ -285,17 +333,42 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
        */
        public function getRoster() {
                $id = $this->getID();
-               $this->addIdHandler($id, 'roster_get_handler');
                $this->send("<iq xmlns='jabber:client' type='get' id='$id'><query xmlns='jabber:iq:roster' /></iq>");
        }
 
        /**
-       * Roster retrieval handler
+       * Roster iq handler
+       * Gets all packets matching XPath "iq/{jabber:iq:roster}query'
        *
        * @param string $xml
        */
-       protected function roster_get_handler($xml) {
-               // TODO: make this work
+       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']}\" />");
+               }
        }
 
        /**
@@ -305,6 +378,7 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
         */
        protected function session_start_handler($xml) {
                $this->log->log("Session started");
+               $this->session_started = true;
                $this->event('session_start');
        }
 
@@ -318,4 +392,41 @@ class XMPPHP_XMPP extends XMPPHP_XMLStream {
                stream_socket_enable_crypto($this->socket, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
                $this->reset();
        }
+
+       /**
+       * Retrieves the vcard
+       *
+       */
+       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>");
+               }
+       }
+
+       /**
+       * VCard retrieval handler
+       *
+       * @param XML Object $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);
+       }
 }
index ab0466e7d887f57d56ffac177f9afc3ba37e660c..43f56b15466d1f6f4242b5219ec49eb4382a0d3d 100644 (file)
@@ -22,6 +22,7 @@
  * @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
  */
 
@@ -43,7 +44,9 @@ require_once "XMPP.php";
 
                public function __construct($host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null) {
                        parent::__construct($host, $port, $user, $password, $resource, $server, $printlog, $loglevel);
-
+                       if(!$server) $server = $host;
+                       $this->stream_start = '<stream:stream to="' . $server . '" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client">';
+                       $this->fulljid = "{$user}@{$server}/{$resource}";
                }
        
                /**
@@ -53,8 +56,8 @@ require_once "XMPP.php";
                 * @param string $name
                 * @param array $attr
                 */
-               protected function startXML($parser, $name, $attr) {
-                       if($this->xml_depth == 0 and $attr['version'] != '1.0') {
+               public function startXML($parser, $name, $attr) {
+                       if($this->xml_depth == 0) {
                                $this->session_id = $attr['ID'];
                                $this->authenticate();
                        }
@@ -84,7 +87,7 @@ require_once "XMPP.php";
                                print "{$this->session_id} {$this->password}\n";
                                $out = "<iq type='set' id='$id'><query xmlns='jabber:iq:auth'><username>{$this->user}</username><digest>{$hash}</digest><resource>{$this->resource}</resource></query></iq>";
                        } else {
-                               $out = "<iq type='set' id='$id'><query xmlns='jabber:iq:auth'><username>{$this->user}</username><digest>{$this->password}</digest><resource>{$this->resource}</resource></query></iq>";
+                               $out = "<iq type='set' id='$id'><query xmlns='jabber:iq:auth'><username>{$this->user}</username><password>{$this->password}</password><resource>{$this->resource}</resource></query></iq>";
                        }
                        $this->send($out);
 
diff --git a/lib/jabber/readme_moodle.txt b/lib/jabber/readme_moodle.txt
new file mode 100644 (file)
index 0000000..3f7d63f
--- /dev/null
@@ -0,0 +1,4 @@
+Description of XMPPHP (aka jabber) version 0.1rc2-r77 library import into Moodle
+
+Changes: none
+