diff options
Diffstat (limited to 'plugins')
29 files changed, 6017 insertions, 110 deletions
diff --git a/plugins/Aim/AimPlugin.php b/plugins/Aim/AimPlugin.php new file mode 100644 index 000000000..30da1dbc7 --- /dev/null +++ b/plugins/Aim/AimPlugin.php @@ -0,0 +1,169 @@ +<?php +/** + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2009, StatusNet, Inc. + * + * Send and receive notices using the AIM network + * + * PHP version 5 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @category IM + * @package StatusNet + * @author Craig Andrews <candrews@integralblue.com> + * @copyright 2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + // This check helps protect against security problems; + // your code file can't be executed directly from the web. + exit(1); +} +// We bundle the phptoclib library... +set_include_path(get_include_path() . PATH_SEPARATOR . dirname(__FILE__) . '/extlib/phptoclib'); + +/** + * Plugin for AIM + * + * @category Plugin + * @package StatusNet + * @author Craig Andrews <candrews@integralblue.com> + * @copyright 2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 + * @link http://status.net/ + */ + +class AimPlugin extends ImPlugin +{ + public $user = null; + public $password = null; + public $publicFeed = array(); + + public $transport = 'aim'; + + function getDisplayName() + { + return _m('AIM'); + } + + function normalize($screenname) + { + $screenname = str_replace(" ","", $screenname); + return strtolower($screenname); + } + + function daemon_screenname() + { + return $this->user; + } + + function validate($screenname) + { + if(preg_match('/^[a-z]\w{2,15}$/i', $screenname)) { + return true; + }else{ + return false; + } + } + + /** + * Load related modules when needed + * + * @param string $cls Name of the class to be loaded + * + * @return boolean hook value; true means continue processing, false means stop. + */ + function onAutoload($cls) + { + $dir = dirname(__FILE__); + + switch ($cls) + { + case 'Aim': + require_once(INSTALLDIR.'/plugins/Aim/extlib/phptoclib/aimclassw.php'); + return false; + case 'AimManager': + include_once $dir . '/'.strtolower($cls).'.php'; + return false; + case 'Fake_Aim': + include_once $dir . '/'. $cls .'.php'; + return false; + default: + return true; + } + } + + function onStartImDaemonIoManagers(&$classes) + { + parent::onStartImDaemonIoManagers(&$classes); + $classes[] = new AimManager($this); // handles sending/receiving + return true; + } + + function microiduri($screenname) + { + return 'aim:' . $screenname; + } + + function send_message($screenname, $body) + { + $this->fake_aim->sendIm($screenname, $body); + $this->enqueue_outgoing_raw($this->fake_aim->would_be_sent); + return true; + } + + /** + * Accept a queued input message. + * + * @return true if processing completed, false if message should be reprocessed + */ + function receive_raw_message($message) + { + $info=Aim::getMessageInfo($message); + $from = $info['from']; + $user = $this->get_user($from); + $notice_text = $info['message']; + + $this->handle_incoming($from, $notice_text); + + return true; + } + + function initialize(){ + if(!isset($this->user)){ + throw new Exception("must specify a user"); + } + if(!isset($this->password)){ + throw new Exception("must specify a password"); + } + + $this->fake_aim = new Fake_Aim($this->user,$this->password,4); + return true; + } + + function onPluginVersion(&$versions) + { + $versions[] = array('name' => 'AIM', + 'version' => STATUSNET_VERSION, + 'author' => 'Craig Andrews', + 'homepage' => 'http://status.net/wiki/Plugin:AIM', + 'rawdescription' => + _m('The AIM plugin allows users to send and receive notices over the AIM network.')); + return true; + } +} + diff --git a/plugins/Aim/Fake_Aim.php b/plugins/Aim/Fake_Aim.php new file mode 100644 index 000000000..139b68f82 --- /dev/null +++ b/plugins/Aim/Fake_Aim.php @@ -0,0 +1,43 @@ +<?php +/** + * StatusNet, the distributed open-source microblogging tool + * + * Instead of sending AIM messages, retrieve the raw data that would be sent + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @category Network + * @package StatusNet + * @author Craig Andrews <candrews@integralblue.com> + * @copyright 2010 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +class Fake_Aim extends Aim +{ + public $would_be_sent = null; + + function sflapSend($sflap_type, $sflap_data, $no_null, $formatted) + { + $this->would_be_sent = array($sflap_type, $sflap_data, $no_null, $formatted); + } +} + diff --git a/plugins/Aim/README b/plugins/Aim/README new file mode 100644 index 000000000..7d486a036 --- /dev/null +++ b/plugins/Aim/README @@ -0,0 +1,27 @@ +The AIM plugin allows users to send and receive notices over the AIM network. + +Installation +============ +add "addPlugin('aim', + array('setting'=>'value', 'setting2'=>'value2', ...);" +to the bottom of your config.php + +scripts/imdaemon.php included with StatusNet must be running. It will be started by +the plugin along with their other daemons when you run scripts/startdaemons.sh. +See the StatusNet README for more about queuing and daemons. + +Settings +======== +user*: username (screenname) to use when logging into AIM +password*: password for that user + +* required +default values are in (parenthesis) + +Example +======= +addPlugin('aim', array( + 'user=>'...', + 'password'=>'...' +)); + diff --git a/plugins/Aim/aimmanager.php b/plugins/Aim/aimmanager.php new file mode 100644 index 000000000..d9b7421fb --- /dev/null +++ b/plugins/Aim/aimmanager.php @@ -0,0 +1,100 @@ +<?php +/* + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2008, 2009, StatusNet, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +/** + * AIM background connection manager for AIM-using queue handlers, + * allowing them to send outgoing messages on the right connection. + * + * Input is handled during socket select loop, keepalive pings during idle. + * Any incoming messages will be handled. + * + * In a multi-site queuedaemon.php run, one connection will be instantiated + * for each site being handled by the current process that has XMPP enabled. + */ + +class AimManager extends ImManager +{ + + public $conn = null; + /** + * Initialize connection to server. + * @return boolean true on success + */ + public function start($master) + { + if(parent::start($master)) + { + $this->connect(); + return true; + }else{ + return false; + } + } + + public function getSockets() + { + $this->connect(); + if($this->conn){ + return array($this->conn->myConnection); + }else{ + return array(); + } + } + + /** + * Process AIM events that have come in over the wire. + * @param resource $socket + */ + public function handleInput($socket) + { + common_log(LOG_DEBUG, "Servicing the AIM queue."); + $this->stats('aim_process'); + $this->conn->receive(); + } + + function connect() + { + if (!$this->conn) { + $this->conn=new Aim($this->plugin->user,$this->plugin->password,4); + $this->conn->registerHandler("IMIn",array($this,"handle_aim_message")); + $this->conn->myServer="toc.oscar.aol.com"; + $this->conn->signon(); + $this->conn->setProfile(_m('Send me a message to post a notice'),false); + } + return $this->conn; + } + + function handle_aim_message($data) + { + $this->plugin->enqueue_incoming_raw($data); + return true; + } + + function send_raw_message($data) + { + $this->connect(); + if (!$this->conn) { + return false; + } + $this->conn->sflapSend($data[0],$data[1],$data[2],$data[3]); + return true; + } +} diff --git a/plugins/Aim/extlib/phptoclib/README.txt b/plugins/Aim/extlib/phptoclib/README.txt new file mode 100755 index 000000000..0eec13af8 --- /dev/null +++ b/plugins/Aim/extlib/phptoclib/README.txt @@ -0,0 +1,169 @@ +phpTOCLib version 1.0 RC1
+
+This is released under the LGPL. AIM,TOC,OSCAR, and all other related protocols/terms are
+copyright AOL/Time Warner. This project is in no way affiliated with them, nor is this
+project supported by them.
+
+Some of the code is loosely based off of a script by Jeffrey Grafton. Mainly the decoding of packets, and the
+function for roasting passwords is entirly his.
+
+TOC documentation used is available at http://simpleaim.sourceforge.net/docs/TOC.txt
+
+
+About:
+phpTOCLib aims to be a PHP equivalent to the PERL module NET::AIM. Due to some limitations,
+this is difficult. Many features have been excluded in the name of simplicity, and leaves
+you alot of room to code with externally, providing function access to the variables that
+need them.
+
+I have aimed to make this extensible, and easy to use, therefore taking away some built in
+functionality that I had originally out in. This project comes after several months of
+researching the TOC protocol.
+
+example.php is included with the class. It needs to be executed from the command line
+(ie:php -q testscript.php) and you need to call php.exe with the -q
+example is provided as a demonstaration only. Though it creats a very simple, functional bot, it lacks any sort of commands, it merely resends the message it recieves in reverse.
+
+
+Revisions:
+
+-----------------------------------
+by Rajiv Makhijani
+(02/24/04)
+ - Fixed Bug in Setting Permit/Deny Mode
+ - Fixes so Uninitialized string offset notice doesn't appear
+ - Replaced New Lines Outputed for Each Flap Read with " . " so
+ that you can still tell it is active but it does not take so much space
+ - Removed "eh?" message
+ - Added MySQL Database Connection Message
+ - New Functions:
+ update_profile(profile data string, powered by boolean)
+ * The profile data string is the text that goes in the profile.
+ * The powered by boolean if set to true displays a link to the
+ sourceforge page of the script.
+(02/28/04)
+ - Silent option added to set object not to output any information
+ - To follow silent rule use sEcho function instead of Echo
+-----------------------------------
+by Jeremy (pickleman78)
+(05/26/04) beta 1 release
+ -Complete overhaul of class design and message handling
+ -Fixed bug involving sign off after long periods of idling
+ -Added new function $Aim->registerHandler
+ -Added the capability to handle all AIM messages
+ -Processing the messages is still the users responsibility
+ -Did a little bit of code cleanup
+ -Added a few internal functions to make the classes internal life easier
+ -Improved AIM server error message processing
+ -Updated this document (hopefully Rajiv will clean it up some, since I'm a terrible documenter)
+-------------------------------------------------------------------------------------------------------------
+
+
+
+Functions:
+
+Several methods are provided in the class that allow for simple access to some of the
+common features of AIM. Below are details.
+
+$Aim->Aim($sn,$password,$pdmode, $silent=false)
+The constructor, it takes 4 arguments.
+$sn is your screen name
+$password is you password, in plain text
+$pdmode is the permit deny mode. This can be as follows:
+1 - Allow All
+2 - Deny All
+3 - Permit only those on your permit list
+4 - Permit all those not on your deny list
+$silent if set to true prints out nothing
+
+So, if your screen-name is JohnDoe746 and your password is fertu, and you want to allow
+all users of the AIM server to contact you, you would code as follows
+$myaim=new Aim("JohnDoe746","fertu",1);
+
+
+$Aim->add_permit($buddy)
+This adds the buddy passed to the function to your permit list.
+ie: $myaim->add_permit("My friend22");
+
+$Aim->block_buddy($buddy)
+Blocks a user. This will switch your pd mode to 4. After using this, for the user to remain
+out of contact with you, it is required to provide the constructor with a pd mode of 4
+ie:$myaim->block_buddy("Annoying guy 4");
+
+$Aim->send_im($to,$message,$auto=false)
+Sends $message to $user. If you set the 3rd argument to true, then the recipient will receive it in
+the same format as an away message. (Auto Response from me:)
+A message longer than 65535 will be truncated
+ie:$myaim->send_im("myfriend","This is a happy message");
+
+$Aim->set_my_info()
+Sends an update buddy command to the server and allows some internal values about yourself
+to be set.
+ie:$myaim->set_my_info();
+
+$Aim->signon()
+Call this to connect to the server. This must be called before any other methods will work
+properly
+ie:$mybot->signon();
+
+$Aim->getLastReceived()
+Returns $this->myLastReceived['decoded']. This should be the only peice of the gotten data
+you need to concern yourself with. This is a preferred method of accessing this variable to prevent
+accidental modification of $this->myLastReceived. Accidently modifying this variable can
+cause some internal failures.
+
+$Aim->read_from_aim()
+This is a wrapper for $Aim->sflap_read(), and only returns the $this->myLastReceived['data']
+portion of the message. It is preferred that you do not call $Aim->sflap_read() and use this
+function instead. This function has a return value. Calling this prevents the need to call
+$Aim->getLastReceived()
+
+$Aim->setWarning($wl)
+This allows you to update the bots warning level when warned.
+
+$Aim->getBuddies()
+Returns the $this->myBuddyList array. Use this instead of modifying the internal variable
+
+$Aim->getPermit()
+Returns the $this->myPermitList array. Use this instead of modifying the internal variable
+
+$Aim->getBlocked()
+Returns the $this->myBlockedList array. Use this instead of modifying the internal variable
+
+$Aim->warn_user($user,$anon=false)
+Warn $user. If anon is set to true, then it warns the user anonomously
+
+$Aim->update_profile($information, $poweredby=false)
+Updates Profile to $information. If $poweredby is true a link to
+sourceforge page for this script is appended to profile
+
+$Aim->registerHandler($function_name,$command)
+This is by far the best thing about the new release.
+For more information please reas supplement.txt. It is not included here because of the sheer size of the document.
+supplement.txt contains full details on using registerHandler and what to expect for each input.
+
+
+For convenience, I have provided some functions to simplify message processing.
+
+They can be read about in the file "supplement.txt". I chose not to include the text here because it
+is a huge document
+
+
+
+There are a few things you should note about AIM
+1)An incoming message has HTML tags in it. You are responsible for stripping those tags
+2)Outgoing messages can have HTML tags, but will work fine if they don't. To include things
+ in the time feild next to the users name, send it as a comment
+
+Conclusion:
+The class is released under the LGPL. If you have any bug reports, comments, questions
+feature requests, or want to help/show me what you've created with this(I am very interested in this),
+please drop me an email: pickleman78@users.sourceforge.net. This code was written by
+Jeremy(a.k.a pickleman78) and Rajiv M (a.k.a compwiz562).
+
+
+Special thanks:
+I'd like to thank all of the people who have contributed ideas, testing, bug reports, and code additions to
+this project. I'd like to especially thank Rajiv, who has done do much for the project, and has kept this documnet
+looking nice. He also has done alot of testing of this script too. I'd also like to thank SpazLink for his help in
+testing. And finally I'd like to thank Jeffery Grafton, whose script inspired me to start this project.
diff --git a/plugins/Aim/extlib/phptoclib/aimclassw.php b/plugins/Aim/extlib/phptoclib/aimclassw.php new file mode 100755 index 000000000..0657910d9 --- /dev/null +++ b/plugins/Aim/extlib/phptoclib/aimclassw.php @@ -0,0 +1,2370 @@ +<?php +/* +* PHPTOCLIB: A library for AIM connectivity through PHP using the TOC protocal. +* +* This library is free software; you can redistribute it and/or +* modify it under the terms of the GNU Lesser General Public +* License as published by the Free Software Foundation; either +* version 2.1 of the License, or (at your option) any later version. +* +* This library 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 +* Lesser General Public License for more details. +* +* You should have received a copy of the GNU Lesser General Public +* License along with this library; if not, write to the Free Software +* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +*/ +/** +* The version of PHPTOCLIB we are running right now +* +* @access private +* @var int +*/ +define("PHPTOCLIB_VERSION","1.0.0 RC1"); + +// Prevents Script from Timing Out +//set_time_limit(0); + +// Constant Declarations + +/** +* Maximum size for a direct connection IM in bytes +* +* @access private +* @var int +*/ + +define("MAX_DIM_SIZE",3072); //Default to 3kb + +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_WARN",74); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_MSG",75); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_UPDATEBUDDY",76); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_SIGNON",77); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_NICK",78); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_ERROR",79); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_CHATJ",80); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_CHATI",81); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_CHATUPDBUD",82); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_CHATINV",83); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_CHATLE",84); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_URL",85); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_NICKSTAT",86); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_PASSSTAT",87); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_RVOUSP",88); +/** +* Internally used for message type +* +* @access private +* @var int +*/ +define("AIM_TYPE_NOT_IMPLEMENTED",666); + + + +/** +* Internally used for connection type +* +* Internal type for a normal connection +* +* @access private +* @var int +*/ +define("CONN_TYPE_NORMAL",1); +/** +* Internally used for connection type +* +* Internal type of a Dirct Connection +* +* @access private +* @var int +*/ +define("CONN_TYPE_DC",2); +/** +* Internally used for connection type +* +*Internal type for a file transfer connection +* +* @access private +* @var int +*/ +define("CONN_TYPE_FT",3); +/** +* Internally used for connection type +* +*Internal type for a file get connection +* +* @access private +* @var int +*/ +define("CONN_TYPE_FTG",4); + +/** +* Maximum size for a TOC packet +* +* @access private +* @var int +*/ +define("MAX_PACKLENGTH",2048); + +/** +* TOC packet type +* +* @access private +* @var int +*/ +define("SFLAP_TYPE_SIGNON",1); +/** +* TOC packet type +* +* @access private +* @var int +*/ +define("SFLAP_TYPE_DATA",2); +/** +* TOC packet type +* +* @access private +* @var int +*/ +define("SFLAP_TYPE_ERROR",3); +/** +* TOC packet type +* +* @access private +* @var int +*/ +define("SFLAP_TYPE_SIGNOFF",4); +/** +* TOC packet type +* +* @access private +* @var int +*/ +define("SFLAP_TYPE_KEEPALIVE",5); +/** +* TOC packet type +* +* @access private +* @var int +*/ +define("SFLAP_MAX_LENGTH",1024); + + + +/** +* Service UID for a voice connection +* +* @access private +* @var int +*/ +define('VOICE_UID', '09461341-4C7F-11D1-8222-444553540000'); +/** +* Service UID for file sending +* +* @access private +* @var int +*/ +define('FILE_SEND_UID', '09461343-4C7F-11D1-8222-444553540000'); +/** +* Service UID for file getting +* +* @access private +* @var int +*/ +define('FILE_GET_UID', '09461348-4C7F-11D1-8222-444553540000'); +/** +* Service UID for Direct connections +* +* @access private +* @var int +*/ +define('IMAGE_UID', '09461345-4C7F-11D1-8222-444553540000'); +/** +* Service UID for Buddy Icons +* +* @access private +* @var int +*/ +define('BUDDY_ICON_UID', '09461346-4C7F-11D1-8222-444553540000'); +/** +* Service UID for stocks +* +* @access private +* @var int +*/ +define('STOCKS_UID', '09461347-4C7F-11D1-8222-444553540000'); +/** +* Service UID for games +* +* @access private +* @var int +*/ +define('GAMES_UID', '0946134a-4C7F-11D1-8222-444553540000'); + +/** +* FLAP return code +* +* @access private +* @var int +*/ +define("SFLAP_SUCCESS",0); +/** +* FLAP return code +* +* @access private +* @var int +*/ +define("SFLAP_ERR_UNKNOWN",1); +/** +* FLAP return code +* +* @access private +* @var int +*/ +define("SFLAP_ERR_ARGS",2); +/** +* FLAP return code +* +* @access private +* @var int +*/ +define("SFLAP_ERR_LENGTH",3); +/** +* FLAP return code +* +* @access private +* @var int +*/ +define("SFLAP_ERR_READ",4); +/** +* FLAP return code +* +* @access private +* @var int +*/ +define("SFLAP_ERR_SEND",5); + +/** +* FLAP version number +* +* @access private +* @var int +*/ +define("SFLAP_FLAP_VERSION",1); +/** +* FLAP TLV code +* +* @access private +* @var int +*/ +define("SFLAP_TLV_TAG",1); +/** +* Bytes in a FLAP header +* +* @access private +* @var int +*/ +define("SFLAP_HEADER_LEN",6); + +/** + * PHPTocLib AIM Class + * + * @author Jeremy Bryant <pickleman78@users.sourceforge.net> + * @author Rajiv Makhijani <rajiv@blue-tech.org> + * @package phptoclib + * @version 1.0RC1 + * @copyright 2005 + * @access public + * + */ +class Aim +{ + /** + * AIM ScreenName + * + * @var String + * @access private + */ + var $myScreenName; + + /** + * AIM Password (Plain Text) + * + * @var String + * @access private + */ + var $myPassword; + + + /** + * AIM TOC Server + * + * @var String + * @access public + */ + var $myServer="toc.oscar.aol.com"; + + /** + * AIM Formatted ScreenName + * + * @var String + * @access private + */ + var $myFormatSN; + + /** + * AIM TOC Server Port + * + * @var String + * @access public + */ + var $myPort="5190"; + + /** + * Profile Data + * Use setProfile() to update + * + * @var String + * @access private + */ + var $myProfile="Powered by phpTOCLib. Please visit http://sourceforge.net/projects/phptoclib for more information"; //The profile of the bot + + /** + * Socket Connection Resource ID + * + * @var Resource + * @access private + */ + var $myConnection; //Connection resource ID + + /** + * Roasted AIM Password + * + * @var String + * @access private + */ + var $myRoastedPass; + + /** + * Last Message Recieved From Server + * + * @var String + * @access private + */ + var $myLastReceived; + + /** + * Current Seq Number Used to Communicate with Server + * + * @var Integer + * @access private + */ + var $mySeqNum; + + /** + * Current Warning Level + * Getter: getWarning() + * Setter: setWarning() + * + * @var Integer + * @access private + */ + var $myWarnLevel; //Warning Level of the bot + + /** + * Auth Code + * + * @var Integer + * @access private + */ + var $myAuthCode; + + /** + * Buddies + * Getter: getBuddies() + * + * @var Array + * @access private + */ + var $myBuddyList; + + /** + * Blocked Buddies + * Getter: getBlocked() + * + * @var Array + * @access private + */ + var $myBlockedList; + + /** + * Permited Buddies + * Getter: getBlocked() + * + * @var Array + * @access private + */ + var $myPermitList; + + /** + * Permit/Deny Mode + * 1 - Allow All + * 2 - Deny All + * 3 - Permit only those on your permit list + * 4 - Permit all those not on your deny list + * + * @var Integer + * @access private + */ + var $myPdMode; + + //Below variables added 4-29 by Jeremy: Implementing chat + + /** + * Contains Chat Room Info + * $myChatRooms['roomid'] = people in room + * + * @var Array + * @access private + */ + var $myChatRooms; + + //End of chat implementation + + + /** + * Event Handler Functions + * + * @var Array + * @access private + */ + var $myEventHandlers = array(); + + /** + * Array of direct connection objects(including file transfers) + * + * @var Array + * @access private + */ + var $myDirectConnections = array(); + + /** + * Array of the actual connections + * + * @var Array + * @access private + */ + var $myConnections = array(); + + /** + * The current state of logging + * + * @var Boolean + * @access private + */ + + var $myLogging = false; + + /** + * Constructor + * + * Permit/Deny Mode Options + * 1 - Allow All + * 2 - Deny All + * 3 - Permit only those on your permit list + * 4 - Permit all those not on your deny list + * + * @param String $sn AIM Screenname + * @param String $password AIM Password + * @param Integer $pdmode Permit/Deny Mode + * @access public + */ + function Aim($sn, $password, $pdmode) + { + //Constructor assignment + $this->myScreenName = $this->normalize($sn); + $this->myPassword = $password; + $this->myRoastedPass = $this->roastPass($password); + $this->mySeqNum = 1; + $this->myConnection = 0; + $this->myWarnLevel = 0; + $this->myAuthCode = $this->makeCode(); + $this->myPdMode = $pdmode; + $this->myFormatSN = $this->myScreenName; + + $this->log("PHPTOCLIB v" . PHPTOCLIB_VERSION . " Object Created"); + + } + + /** + * Enables debug logging (Logging is disabled by default) + * + * + * @access public + * @return void + */ + + function setLogging($enable) + { + $this->myLogging=$enable; + } + + function log($data) + { + if($this->myLogging){ + error_log($data); + } + } + + /** + * Logs a packet + * + * + * @access private + * @param Array $packary Packet + * @param String $in Prepend + * @return void + */ + function logPacket($packary,$in) + { + if(!$this->myLogging || sizeof($packary)<=0 || (@strlen($packary['decoded'])<=0 && @isset($packary['decoded']))) + return; + $towrite=$in . ": "; + foreach($packary as $k=>$d) + { + $towrite.=$k . ":" . $d . "\r\n"; + } + $towrite.="\r\n\r\n"; + $this->log($towrite); + } + /** + * Roasts/Hashes Password + * + * @param String $password Password + * @access private + * @return String Roasted Password + */ + function roastPass($password) + { + $roaststring = 'Tic/Toc'; + $roasted_password = '0x'; + for ($i = 0; $i < strlen($password); $i++) + $roasted_password .= bin2hex($password[$i] ^ $roaststring[($i % 7)]); + return $roasted_password; + } + + /** + * Access Method for myScreenName + * + * @access public + * @param $formated Returns formatted Screenname if true as returned by server + * @return String Screenname + */ + function getMyScreenName($formated = false) + { + if ($formated) + { + return $this->myFormatSN; + } + else + { + return $this->normalize($this->myScreenName); + } + } + + /** + * Generated Authorization Code + * + * @access private + * @return Integer Auth Code + */ + function makeCode() + { + $sn = ord($this->myScreenName[0]) - 96; + $pw = ord($this->myPassword[0]) - 96; + $a = $sn * 7696 + 738816; + $b = $sn * 746512; + $c = $pw * $a; + + return $c - $a + $b + 71665152; + } + + + /** + * Reads from Socket + * + * @access private + * @return String Data + */ + function sflapRead() + { + if ($this->socketcheck($this->myConnection)) + { + $this->log("Disconnected.... Reconnecting in 60 seconds"); + sleep(60); + $this->signon(); + } + + $header = fread($this->myConnection,SFLAP_HEADER_LEN); + + if (strlen($header) == 0) + { + $this->myLastReceived = ""; + return ""; + } + $header_data = unpack("aast/Ctype/nseq/ndlen", $header); + $this->log(" . ", false); + $packet = fread($this->myConnection, $header_data['dlen']); + if (strlen($packet) <= 0 && $sockinfo['blocked']) + $this->derror("Could not read data"); + + if ($header_data['type'] == SFLAP_TYPE_SIGNON) + { + $packet_data=unpack("Ndecoded", $packet); + } + + if ($header_data['type'] == SFLAP_TYPE_KEEPALIVE) + { + $this->myLastReceived = ''; + return 0; + } + else if (strlen($packet)>0) + { + $packet_data = unpack("a*decoded", $packet); + } + $this->log("socketcheck check now"); + if ($this->socketcheck($this->myConnection)) + { + $this->derror("Connection ended unexpectedly"); + } + + $data = array_merge($header_data, $packet_data); + $this->myLastReceived = $data; + $this->logPacket($data,"in"); + return $data; + } + + /** + * Sends Data on Socket + * + * @param String $sflap_type Type + * @param String $sflap_data Data + * @param boolean $no_null No Null + * @param boolean $formatted Format + * @access private + * @return String Roasted Password + */ + function sflapSend($sflap_type, $sflap_data, $no_null, $formatted) + { + $packet = ""; + if (strlen($sflap_data) >= MAX_PACKLENGTH) + $sflap_data = substr($sflap_data,0,MAX_PACKLENGTH); + + if ($formatted) + { + $len = strlen($sflap_len); + $sflap_header = pack("aCnn",'*', $sflap_type, $this->mySeqNum, $len); + $packet = $sflap_header . $sflap_data; + } else { + if (!$no_null) + { + $sflap_data = str_replace("\0","", trim($sflap_data)); + $sflap_data .= "\0"; + } + $data = pack("a*", $sflap_data); + $len = strlen($sflap_data); + $header = pack("aCnn","*", $sflap_type, $this->mySeqNum, $len); + $packet = $header . $data; + } + + //Make sure we are still connected + if ($this->socketcheck($this->myConnection)) + { + $this->log("Disconnected.... reconnecting in 60 seconds"); + sleep(60); + $this->signon(); + } + $sent = fputs($this->myConnection, $packet) or $this->derror("Error sending packet to AIM"); + $this->mySeqNum++; + sleep(ceil($this->myWarnLevel/10)); + $this->logPacket(array($sflap_type,$sflap_data),"out"); + } + + /** + * Escape the thing that TOC doesn't like,that would be + * ",', $,{,},[,] + * + * @param String $data Data to Escape + * @see decodeData + * @access private + * @return String $data Escaped Data + */ + function encodeData($data) + { + $data = str_replace('"','\"', $data); + $data = str_replace('$','\$', $data); + $data = str_replace("'","\'", $data); + $data = str_replace('{','\{', $data); + $data = str_replace('}','\}', $data); + $data = str_replace('[','\[', $data); + $data = str_replace(']','\]', $data); + return $data; + } + + /** + * Unescape data TOC has escaped + * ",', $,{,},[,] + * + * @param String $data Data to Unescape + * @see encodeData + * @access private + * @return String $data Unescape Data + */ + function decodeData($data) + { + $data = str_replace('\"','"', $data); + $data = str_replace('\$','$', $data); + $data = str_replace("\'","'", $data); + $data = str_replace('\{','{', $data); + $data = str_replace('\}','}', $data); + $data = str_replace('\[','[', $data); + $data = str_replace('\]',']', $data); + $data = str_replace('"','"', $data); + $data = str_replace('&','&', $data); + return $data; + } + + /** + * Normalize ScreenName + * no spaces and all lowercase + * + * @param String $nick ScreenName + * @access public + * @return String $nick Normalized ScreenName + */ + function normalize($nick) + { + $nick = str_replace(" ","", $nick); + $nick = strtolower($nick); + return $nick; + } + + /** + * Sets internal info with update buddy + * Currently only sets warning level + * + * @access public + * @return void + */ + function setMyInfo() + { + //Sets internal values bvase on the update buddy command + $this->log("Setting my warning level ..."); + $this->sflapSend(SFLAP_TYPE_DATA,"toc_get_status " . $this->normalize($this->myScreenName),0,0); + //The rest of this will now be handled by the other functions. It is assumed + //that we may have other data queued in the socket, do we should just add this + //message to the queue instead of trying to set it in here + } + + /** + * Connects to AIM and Signs On Using Info Provided in Constructor + * + * @access public + * @return void + */ + function signon() + { + $this->log("Ready to sign on to the server"); + $this->myConnection = fsockopen($this->myServer, $this->myPort, $errno, $errstr,10) or die("$errorno:$errstr"); + $this->log("Connected to server"); + $this->mySeqNum = (time() % 65536); //Select an arbitrary starting point for + //sequence numbers + if (!$this->myConnection) + $this->derror("Error connecting to toc.oscar.aol.com"); + $this->log("Connected to AOL"); + //Send the flapon packet + fputs($this->myConnection,"FLAPON\r\n\n\0"); //send the initial handshake + $this->log("Sent flapon"); + $this->sflapRead(); //Make sure the server responds with what we expect + if (!$this->myLastReceived) + $this->derror("Error sending the initialization string"); + + //send the FLAP SIGNON packet back with what it needs + //There are 2 parts to the signon packet. They are sent in succession, there + //is no indication if either packet was correctly sent + $signon_packet = pack("Nnna".strlen($this->myScreenName),1,1,strlen($this->myScreenName), $this->myScreenName); + $this->sflapSend(SFLAP_TYPE_SIGNON, $signon_packet,1,0); + $this->log("sent signon packet part one"); + + $signon_packet_part2 = 'toc2_signon login.oscar.aol.com 29999 ' . $this->myScreenName . ' ' . $this->myRoastedPass . ' english-US "TIC:TOC2:REVISION" 160 ' . $this->myAuthCode; + $this->log($signon_packet_part2 . ""); + $this->sflapSend(SFLAP_TYPE_DATA, $signon_packet_part2,0,0); + $this->log("Sent signon packet part 2... Awaiting response..."); + + $this->sflapRead(); + $this->log("Received Sign on packet, beginning initilization..."); + $message = $this->getLastReceived(); + $this->log($message . "\n"); + if (strstr($message,"ERROR:")) + { + $this->onError($message); + die("Fatal signon error"); + } + stream_set_timeout($this->myConnection,2); + //The information sent before the config2 command is utterly useless to us + //So we will just skim through them until we reach it + + //Add the first entry to the connection array + $this->myConnections[] = $this->myConnection; + + + //UPDATED 4/12/03: Now this will use the receive function and send the + //received messaged to the assigned handlers. This is where the signon + //method has no more use + + $this->log("Done with signon proccess"); + //socket_set_blocking($this->myConnection,false); + } + + /** + * Sends Instant Message + * + * @param String $to Message Recipient SN + * @param String $message Message to Send + * @param boolean $auto Sent as Auto Response / Away Message Style + * @access public + * @return void + */ + function sendIM($to, $message, $auto = false) + { + if ($auto) $auto = "auto"; + else $auto = ""; + $to = $this->normalize($to); + $message = $this->encodeData($message); + $command = 'toc2_send_im "' . $to . '" "' . $message . '" ' . $auto; + $this->sflapSend(SFLAP_TYPE_DATA, trim($command),0,0); + $cleanedmessage = str_replace("<br>", " ", $this->decodeData($message)); + $cleanedmessage = strip_tags($cleanedmessage); + $this->log("TO - " . $to . " : " . $cleanedmessage); + } + + /** + * Set Away Message + * + * @param String $message Away message (some HTML supported). + * Use null to remove the away message + * @access public + * @return void + */ + function setAway($message) + { + $message = $this->encodeData($message); + $command = 'toc_set_away "' . $message . '"'; + $this->sflapSend(SFLAP_TYPE_DATA, trim($command),0,0); + $this->log("SET AWAY MESSAGE - " . $this->decodeData($message)); + } + + /** + * Fills Buddy List + * Not implemented fully yet + * + * @access public + * @return void + */ + function setBuddyList() + { + //This better be the right message + $message = $this->myLastReceived['decoded']; + if (strpos($message,"CONFIG2:") === false) + { + $this->log("setBuddyList cannot be called at this time because I got $message"); + return false; + } + $people = explode("\n",trim($message,"\n")); + //The first 3 elements of the array are who knows what, element 3 should be + //a letter followed by a person + for($i = 1; $i<sizeof($people); $i++) + { + @list($mode, $name) = explode(":", $people[$i]); + switch($mode) + { + case 'p': + $this->myPermitList[] = $name; + break; + case 'd': + $this->myBlockedList[] = $name; + break; + case 'b': + $this->myBuddyList[] = $name; + break; + case 'done': + break; + default: + // + } + } + } + + /** + * Adds buddy to Permit list + * + * @param String $buddy Buddy's Screenname + * @access public + * @return void + */ + function addPermit($buddy) + { + $this->sflapSend(SFLAP_TYPE_DATA,"toc2_add_permit " . $this->normalize($buddy),0,0); + $this->myPermitList[] = $this->normalize($buddy); + return 1; + } + + /** + * Blocks buddy + * + * @param String $buddy Buddy's Screenname + * @access public + * @return void + */ + function blockBuddy($buddy) + { + $this->sflapSend(SFLAP_TYPE_DATA,"toc2_add_deny " . $this->normalize($buddy),0,0); + $this->myBlockedList[] = $this->normalize($buddy); + return 1; + } + + /** + * Returns last message received from server + * + * @access private + * @return String Last Message from Server + */ + function getLastReceived() + { + if (@$instuff = $this->myLastReceived['decoded']){ + return $this->myLastReceived['decoded']; + }else{ + return; + } + } + + /** + * Returns Buddy List + * + * @access public + * @return array Buddy List + */ + function getBuddies() + { + return $this->myBuddyList; + } + + /** + * Returns Permit List + * + * @access public + * @return array Permit List + */ + function getPermit() + { + return $this->myPermitList; + } + + /** + * Returns Blocked Buddies + * + * @access public + * @return array Blocked List + */ + function getBlocked() + { + return $this->myBlockedList; + } + + + + + /** + * Reads and returns data from server + * + * This is a wrapper for $Aim->sflap_read(), and only returns the $this->myLastReceived['data'] + * portion of the message. It is preferred that you do not call $Aim->sflap_read() and use this + * function instead. This function has a return value. Calling this prevents the need to call + * $Aim->getLastReceived() + * + * @access public + * @return String Data recieved from server + */ + function read_from_aim() + { + $this->sflapRead(); + $returnme = $this->getLastReceived(); + return $returnme; + } + + /** + * Sets current internal warning level + * + * This allows you to update the bots warning level when warned. + * + * @param int Warning Level % + * @access private + * @return void + */ + function setWarningLevel($warnlevel) + { + $this->myWarnLevel = $warnlevel; + } + + /** + * Warns / "Evils" a User + * + * To successfully warn another user they must have sent you a message. + * There is a limit on how much and how often you can warn another user. + * Normally when you warn another user they are aware who warned them, + * however there is the option to warn anonymously. When warning anon. + * note that the warning is less severe. + * + * @param String $to Screenname to warn + * @param boolean $anon Warn's anonymously if true. (default = false) + * @access public + * @return void + */ + function warnUser($to, $anon = false) + { + if (!$anon) + $anon = '"norm"'; + + else + $anon = '"anon"'; + $this->sflapSend(SFLAP_TYPE_DATA,"toc_evil " . $this->normalize($to) . " $anon",0,0); + } + + /** + * Returns warning level of bot + * + * @access public + * @return void + */ + function getWarningLevel() + { + return $this->myWarningLevel; + } + + /** + * Sets bot's profile/info + * + * Limited to 1024 bytes. + * + * @param String $profiledata Profile Data (Can contain limited html: br,hr,font,b,i,u etc) + * @param boolean $poweredby If true, appends link to phpTOCLib project to profile + * @access public + * @return void + */ + function setProfile($profiledata, $poweredby = false) + { + if ($poweredby == false){ + $this->myProfile = $profiledata; + }else{ + $this->myProfile = $profiledata . "<font size=1 face=tahoma><br><br>Powered by phpTOCLib<br>http://sourceforge.net/projects/phptoclib</font>"; + } + + $this->sflapSend(SFLAP_TYPE_DATA,"toc_set_info \"" . $this->encodeData($this->myProfile) . "\"",0,0); + $this->setMyInfo(); + $this->log("Profile has been updated..."); + } + + //6/29/04 by Jeremy: + //Added mthod to accept a rvous,decline it, and + //read from the rvous socket + + //Decline + + /** + * Declines a direct connection request (rvous) + * + * @param String $nick ScreenName request was from + * @param String $cookie Request cookie (from server) + * @param String $uuid UUID + * + * @access public + * @return void + */ + function declineRvous($nick, $cookie, $uuid) + { + $nick = $this->normalize($nick); + $this->sflapSend(SFLAP_TYPE_DATA,"toc_rvous_cancel $nick $cookie $uuid",0,0); + } + + /** + * Accepts a direct connection request (rvous) + * + * @param String $nick ScreenName request was from + * @param String $cookie Request cookie (from server) + * @param String $uuid UUID + * @param String $vip IP of User DC with + * @param int $port Port number to connect to + * + * @access public + * @return void + */ + function acceptRvous($nick, $cookie, $uuid, $vip, $port) + { + $this->sflapSend(SFLAP_TYPE_DATA,"toc_rvous_accept $nick $cookie $uuid",0,0); + + //Now open the connection to that user + if ($uuid == IMAGE_UID) + { + $dcon = new Dconnect($vip, $port); + } + else if ($uuid == FILE_SEND_UID) + { + $dcon = new FileSendConnect($vip, $port); + } + if (!$dcon->connected) + { + $this->log("The connection failed"); + return false; + } + + //Place this dcon object inside the array + $this->myDirectConnections[] = $dcon; + //Place the socket in an array to + $this->myConnections[] = $dcon->sock; + + + //Get rid of the first packet because its worthless + //and confusing + $dcon->readDIM(); + //Assign the cookie + $dcon->cookie = $dcon->lastReceived['cookie']; + $dcon->connectedTo = $this->normalize($nick); + return $dcon; + } + + /** + * Sends a Message over a Direct Connection + * + * Only works if a direct connection is already established with user + * + * @param String $to Message Recipient SN + * @param String $message Message to Send + * + * @access public + * @return void + */ + function sendDim($to, $message) + { + //Find the connection + for($i = 0;$i<sizeof($this->myDirectConnections);$i++) + { + if ($this->normalize($to) == $this->myDirectConnections[$i]->connectedTo && $this->myDirectConnections[$i]->type == CONN_TYPE_DC) + { + $dcon = $this->myDirectConnections[$i]; + break; + } + } + if (!$dcon) + { + $this->log("Could not find a direct connection to $to"); + return false; + } + $dcon->sendMessage($message, $this->normalize($this->myScreenName)); + return true; + } + + /** + * Closes an established Direct Connection + * + * @param DConnect $dcon Direct Connection Object to Close + * + * @access public + * @return void + */ + function closeDcon($dcon) + { + + $nary = array(); + for($i = 0;$i<sizeof($this->myConnections);$i++) + { + if ($dcon->sock == $this->myConnections[$i]) + unset($this->myConnections[$i]); + } + + $this->myConnections = array_values($this->myConnections); + unset($nary); + $nary2 = array(); + + for($i = 0;$i<sizeof($this->myDirectConnections);$i++) + { + if ($dcon == $this->myDirectConnections[$i]) + unset($this->myDirectConnections[$i]); + } + $this->myDirectConnections = array_values($this->myDirectConnections); + $dcon->close(); + unset($dcon); + } + + //Added 4/29/04 by Jeremy: + //Various chat related methods + + /** + * Accepts a Chat Room Invitation (Joins room) + * + * @param String $chatid ID of Chat Room + * + * @access public + * @return void + */ + function joinChat($chatid) + { + $this->sflapSend(SFLAP_TYPE_DATA,"toc_chat_accept " . $chatid,0,0); + } + + /** + * Leaves a chat room + * + * @param String $chatid ID of Chat Room + * + * @access public + * @return void + */ + function leaveChat($chatid) + { + $this->sflapSend(SFLAP_TYPE_DATA,"toc_chat_leave " . $chatid,0,0); + } + + /** + * Sends a message in a chat room + * + * @param String $chatid ID of Chat Room + * @param String $message Message to send + * + * @access public + * @return void + */ + function chatSay($chatid, $message) + { + $this->sflapSend(SFLAP_TYPE_DATA,"toc_chat_send " . $chatid . " \"" . $this->encodeData($message) . "\"",0,0); + } + + /** + * Invites a user to a chat room + * + * @param String $chatid ID of Chat Room + * @param String $who Screenname of user + * @param String $message Note to include with invitiation + * + * @access public + * @return void + */ + function chatInvite($chatid, $who, $message) + { + $who = $this->normalize($who); + $this->sflapSend(SFLAP_TYPE_DATA,"toc_chat_invite " . $chatid . " \"" . $this->encodeData($message) . "\" " . $who,0,0); + } + + /** + * Joins/Creates a new chat room + * + * @param String $name Name of the new chat room + * @param String $exchange Exchange of new chat room + * + * @access public + * @return void + */ + function joinNewChat($name, $exchange) + { + //Creates a new chat + $this->sflapSend(SFLAP_TYPE_DATA,"toc_chat_join " . $exchange . " \"" . $name . "\"",0,0); + } + + /** + * Disconnect error handler, attempts to reconnect in 60 seconds + * + * @param String $message Error message (desc of where error encountered etc) + * + * @access private + * @return void + */ + function derror($message) + { + $this->log($message); + $this->log("Error"); + fclose($this->myConnection); + if ((time() - $GLOBALS['errortime']) < 600){ + $this->log("Reconnecting in 60 Seconds"); + sleep(60); + } + $this->signon(); + $GLOBALS['errortime'] = time(); + } + + /** + * Returns connection type of socket (main or rvous etc) + * + * Helper method for recieve() + * + * @param Resource $sock Socket to determine type for + * + * @access private + * @return void + * @see receive + */ + function connectionType($sock) + { + //Is it the main connection? + if ($sock == $this->myConnection) + return CONN_TYPE_NORMAL; + else + { + for($i = 0;$i<sizeof($this->myDirectConnections);$i++) + { + if ($sock == $this->myDirectConnections[$i]->sock) + return $this->myDirectConnections[$i]->type; + } + } + return false; + } + + /** + * Checks for new data and calls appropriate methods + * + * This method is usually called in an infinite loop to keep checking for new data + * + * @access public + * @return void + * @see connectionType + */ + function receive() + { + //This function will be used to get the incoming data + //and it will be used to call the event handlers + + //First, get an array of sockets that have data that is ready to be read + $ready = array(); + $ready = $this->myConnections; + $numrdy = stream_select($ready, $w = NULL, $x = NULL,NULL); + + //Now that we've waited for something, go through the $ready + //array and read appropriately + + for($i = 0;$i<sizeof($ready);$i++) + { + //Get the type + $type = $this->connectionType($ready[$i]); + if ($type == CONN_TYPE_NORMAL) + { + //Next step:Get the data sitting in the socket + $message = $this->read_from_aim(); + if (strlen($message) <= 0) + { + return; + } + + //Third step: Get the command from the server + @list($cmd, $rest) = explode(":", $message); + + //Fourth step, take the command, test the type, and pass it off + //to the correct internal handler. The internal handler will + //do what needs to be done on the class internals to allow + //it to work, then proceed to pass it off to the user created handle + //if there is one + $this->log($cmd); + switch($cmd) + { + case 'SIGN_ON': + $this->onSignOn($message); + break; + case 'CONFIG2': + $this->onConfig($message); + break; + case 'ERROR': + $this->onError($message); + break; + case 'NICK': + $this->onNick($message); + break; + case 'IM_IN2': + $this->onImIn($message); + break; + case 'UPDATE_BUDDY2': + $this->onUpdateBuddy($message); + break; + case 'EVILED': + $this->onWarn($message); + break; + case 'CHAT_JOIN': + $this->onChatJoin($message); + break; + case 'CHAT_IN': + $this->onChatIn($message); + break; + case 'CHAT_UPDATE_BUDDY': + $this->onChatUpdate($message); + break; + case 'CHAT_INVITE': + $this->onChatInvite($message); + break; + case 'CHAT_LEFT': + $this->onChatLeft($message); + break; + case 'GOTO_URL': + $this->onGotoURL($message); + break; + case 'DIR_STATUS': + $this->onDirStatus($message); + break; + case 'ADMIN_NICK_STATUS': + $this->onAdminNick($message); + break; + case 'ADMIN_PASSWD_STATUS': + $this->onAdminPasswd($message); + break; + case 'PAUSE': + $this->onPause($message); + break; + case 'RVOUS_PROPOSE': + $this->onRvous($message); + break; + default: + $this->log("Fell through: $message"); + $this->CatchAll($message); + break; + } + } + else + { + for($j = 0;$j<sizeof($this->myDirectConnections);$j++) + { + if ($this->myDirectConnections[$j]->sock == $ready[$i]) + { + $dcon = $this->myDirectConnections[$j]; + break; + } + } + //Now read from the dcon + if ($dcon->type == CONN_TYPE_DC) + { + if ($dcon->readDIM() == false) + { + $this->closeDcon($dcon); + continue; + } + + $message['message'] = $dcon->lastMessage; + if ($message['message'] == "too big") + { + $this->sendDim("Connection dropped because you sent a message larger that " . MAX_DCON_SIZE . " bytes.", $dcon->connectedTo); + $this->closeDcon($dcon); + continue; + } + $message['from'] = $dcon->connectedTo; + $this->onDimIn($message); + } + } + } + $this->conn->myLastReceived=""; + //Now get out of this function because the handlers should take care + //of everything + } + + //The next block of code is all the event handlers needed by the class + //Some are left blank and only call the users handler because the class + //either does not support the command, or cannot do anything with it + // --------------------------------------------------------------------- + + /** + * Direct IM In Event Handler + * + * Called when Direct IM is received. + * Call's user handler (if available) for DimIn. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onDimIn($data) + { + $this->callHandler("DimIn", $data); + } + + /** + * Sign On Event Handler + * + * Called when Sign On event occurs. + * Call's user handler (if available) for SIGN_ON. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onSignOn($data) + { + $this->callHandler("SignOn", $data); + } + + /** + * Config Event Handler + * + * Called when Config data received. + * Call's user handler (if available) for Config. + * + * Loads buddy list and other info + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onConfig($data) + { + $this->log("onConfig Message: " . $data); + + if (strpos($data,"CONFIG2:") === false) + { + $this->log("get_buddy_list cannot be called at this time because I got $data"); + //return false; + } + $people = explode("\n",trim($data,"\n")); + //The first 3 elements of the array are who knows what, element 3 should be + //a letter followed by a person + + //AIM decided to add this wonderful new feature, the recent buddy thing, this kind of + //messes this funtion up, so we need to adapt it... unfortuneately, its not really + //clear how this works, so we are just going to add their name to the permit list. + + //Recent buddies I believe are in the format + //number:name:number.... I think the first number counts down from 25 how long its + //been... but I don't know the second number,,,, + + //TODO: Figure out the new recent buddies system + + //Note: adding that at the bottom is a quick hack and may have adverse consequences... + for($i = 1;$i<sizeof($people);$i++) + { + @list($mode, $name) = explode(":", $people[$i]); + switch($mode) + { + case 'p': + $this->myPermitList[] = $name; + break; + case 'd': + $this->myBlockedList[] = $name; + break; + case 'b': + $this->myBuddyList[] = $name; + break; + case 'done': + break; + default: + //This is assumed to be recent buddies... + $this->myPermitList[]=$name; + } + } + + //We only get the config message once, so now we should send our pd mode + + $this->sflapSend(SFLAP_TYPE_DATA,"toc2_set_pdmode " . $this->myPdMode,0,0); + //Adds yourself to the permit list + //This is to fix an odd behavior if you have nobody on your list + //the server won't send the config command... so this takes care of it + $this->sflapSend(SFLAP_TYPE_DATA,"toc2_add_permit " . $this->normalize($this->myScreenName),0,0); + + //Now we allow the user to send a list, update anything they want, etc + $this->callHandler("Config", $data); + //Now that we have taken care of what the user wants, send the init_done message + $this->sflapSend(SFLAP_TYPE_DATA,"toc_init_done",0,0); + //'VOICE_UID' + //'FILE_GET_UID' + //'IMAGE_UID' + //'BUDDY_ICON_UID' + //'STOCKS_UID' + //'GAMES_UID' + $this->sflapSend(SFLAP_TYPE_DATA, "toc_set_caps " . IMAGE_UID . " " . FILE_SEND_UID ." " . FILE_GET_UID . " " . BUDDY_ICON_UID . "",0,0); + } + + + /** + * Error Event Handler + * + * Called when an Error occurs. + * Call's user handler (if available) for Error. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onError($data) + { + static $errarg = ''; + static $ERRORS = array(
+ 0=>'Success',
+ 901 =>'$errarg not currently available',
+ 902 =>'Warning of $errarg not currently available',
+ 903 =>'A message has been dropped, you are exceeding
+ the server speed limit',
+ 911 =>'Error validating input',
+ 912 =>'Invalid account',
+ 913 =>'Error encountered while processing request',
+ 914 =>'Service unavailable',
+ 950 =>'Chat in $errarg is unavailable.',
+ 960 =>'You are sending message too fast to $errarg',
+ 961 =>'You missed an im from $errarg because it was too big.',
+ 962 =>'You missed an im from $errarg because it was sent too fast.',
+ 970 =>'Failure',
+ 971 =>'Too many matches',
+ 972 =>'Need more qualifiers',
+ 973 =>'Dir service temporarily unavailable',
+ 974 =>'Email lookup restricted',
+ 975 =>'Keyword Ignored',
+ 976 =>'No Keywords',
+ 977 =>'Language not supported',
+ 978 =>'Country not supported',
+ 979 =>'Failure unknown $errarg',
+ 980 =>'Incorrect nickname or password.',
+ 981 =>'The service is temporarily unavailable.',
+ 982 =>'Your warning level is currently too high to sign on.',
+ 983 =>'You have been connecting and
+ disconnecting too frequently. Wait 10 minutes and try again.
+ If you continue to try, you will need to wait even longer.',
+ 989 =>'An unknown signon error has occurred $errarg'
+ ); + $data_array = explode(":", $data); + for($i=0; $i<count($data_array); $i++) + { + switch($i) + { + case 0: + $cmd = $data_array[$i]; + break; + case 1: + $errornum = $data_array[$i]; + break; + case 2: + $errargs = $data_array[$i]; + break; + } + } + eval("\$errorstring=\"\$ERRORS[" . $errornum . "]\";"); + $string = "\$errorstring=\"\$ERRORS[$errornum]\";"; + //This is important information! We need + // a A different outputter for errors + // b Just to echo it + //I'm just going to do a straight echo here, becuse we assume that + //the user will NEED to see this error. An option to supress it will + //come later I think. Perhaps if we did an error reporting level, similar + //to PHP's, and we could probably even use PHP's error outputting system + //I think that may be an idea.... + + $this->log($errorstring . "\n"); + + $this->callHandler("Error", $data); + } + + /** + * Nick Event Handler + * + * Called when formatted own ScreenName is receieved + * Call's user handler (if available) for Nick. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onNick($data) + { + //This is our nick, so set a field called "myFormatSN" which will represent + //the actual name given by the server to us, NOT the normalized screen name + @list($cmd, $nick) = explode(":", $data); + $this->myFormatSN = $nick; + + $this->callHandler("Nick", $data); + } + + /** + * IM In Event Handler + * + * Called when an Instant Message is received. + * Call's user handler (if available) for IMIn. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onImIn($data) + { + //Perhaps we should add an internal log for debugging purposes?? + //But now, this should probably be handled by the user purely + + $this->callHandler("IMIn", $data); + } + + /** + * UpdateBuddy Event Handler + * + * Called when a Buddy Update is receieved. + * Call's user handler (if available) for UpdateBuddy. + * If info is about self, updates self info (Currently ownly warning). + * + * ToDo: Keep track of idle, warning etc on Buddy List + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onUpdateBuddy($data) + { + //Again, since our class currently does not deal with other people without + //outside help, then this is also probably best left to the user. Though + //we should probably allow this to replace the setMyInfo function above + //by handling the input if and only if it is us + //Check and see that this is the command expected + if (strpos($data,"UPDATE_BUDDY2:") == -1) + { + $this->log("A different message than expected was received"); + return false; + } + + //@list($cmd, $info['sn'], $info['online'], $info['warnlevel'], $info['signon'], $info['idle'], $info['uc']) = explode(":", $command['incoming']); + + //@list($cmd, $sn, $online, $warning, $starttime, $idletime, $uc) = explode(":", $data); + $info = $this->getMessageInfo($data); + if ($this->normalize($info['sn']) == $this->normalize($this->myScreenName)) + { + $warning = rtrim($info['warnlevel'],"%"); + $this->myWarnLevel = $warning; + $this->log("My warning level is $this->myWarnLevel %"); + } + + $this->callHandler("UpdateBuddy", $data); + } + + /** + * Warning Event Handler + * + * Called when bot is warned. + * Call's user handler (if available) for Warn. + * Updates internal warning level + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onWarn($data) + { + /* + For reference: + $command['incoming'] .= ":0"; + $it = explode(":", $command['incoming']); + $info['warnlevel'] = $it[1]; + $info['from'] = $it[2]; + */ + //SImply update our warning level + //@list($cmd, $newwarn, $user) = explode(":", $data); + + $info = $this->getMessageInfo($data); + + $this->setWarningLevel(trim($info['warnlevel'],"%")); + $this->log("My warning level is $this->myWarnLevel %"); + + $this->callHandler("Warned", $data); + } + + /** + * Chat Join Handler + * + * Called when bot joins a chat room. + * Call's user handler (if available) for ChatJoin. + * Adds chat room to internal chat room list. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onChatJoin($data) + { + @list($cmd, $rmid, $rmname) = explode(":", $data); + $this->myChatRooms[$rmid] = 0; + + $this->callHandler("ChatJoin", $data); + } + + /** + * Returns number of chat rooms bot is in + * + * @access public + * @param String $data Raw message from server + * @return int + */ + function getNumChats() + { + return count($this->myChatRooms); + } + + /** + * Chat Update Handler + * + * Called when bot received chat room data (user update). + * Call's user handler (if available) for ChatUpdate. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onChatUpdate($data) + { + $stuff = explode(":", $data); + $people = sizeof($stuff); + $people -= 2; + + $this->callHandler("ChatUpdate", $data); + } + + /** + * Chat Message In Handler + * + * Called when chat room message is received. + * Call's user handler (if available) for ChatIn. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onChatIn($data) + { + $this->callHandler("ChatIn", $data); + } + + + /** + * Chat Invite Handler + * + * Called when bot is invited to a chat room. + * Call's user handler (if available) for ChatInvite. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onChatInvite($data) + { + //@list($cmd, $name, $id, $from, $data) = explode(":", $data,6); + //$data = explode(":",$data,6); + //$nm = array(); + //@list($nm['cmd'],$nm['name'],$nm['id'],$nm['from'],$nm['message']) = $data; + + + $this->callHandler("ChatInvite", $data); + } + + /** + * Chat Left Handler + * + * Called when bot leaves a chat room + * Call's user handler (if available) for ChatLeft. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onChatLeft($data) + { + $info = $this->getMessageInfo($data); + unset($this->myChatRooms[$info['chatid']]); + $this->callHandler("ChatLeft", $data); + } + + /** + * Goto URL Handler + * + * Called on GotoURL. + * Call's user handler (if available) for GotoURL. + * No detailed info available for this / Unsupported. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onGotoURL($data) + { + //This is of no use to the internal class + + $this->callHandler("GotoURL", $data); + } + + /** + * Dir Status Handler + * + * Called on DirStatus. + * Call's user handler (if available) for DirStatus. + * No detailed info available for this / Unsupported. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onDirStatus($data) + { + //This is not currently suported + + $this->callHandler("DirStatus", $data); + } + + /** + * AdminNick Handler + * + * Called on AdminNick. + * Call's user handler (if available) for AdminNick. + * No detailed info available for this / Unsupported. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onAdminNick($data) + { + //NOt particularly useful to us + $this->callHandler("AdminNick", $data); + } + + /** + * AdminPasswd Handler + * + * Called on AdminPasswd. + * Call's user handler (if available) for AdminPasswd. + * No detailed info available for this / Unsupported. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onAdminPasswd($data) + { + //Also not particlualry useful to the internals + $this->callHandler("AdminPasswd", $data); + } + + /** + * Pause Handler + * + * Called on Pause. + * Call's user handler (if available) for Pause. + * No detailed info available for this / Unsupported. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onPause($data) + { + //This is pretty useless to us too... + + $this->callHandler("Pause", $data); + } + + /** + * Direct Connection Handler + * + * Called on Direct Connection Request(Rvous). + * Call's user handler (if available) for Rvous. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function onRvous($data) + { + $this->callHandler("Rvous", $data); + } + + /** + * CatchAll Handler + * + * Called for unrecognized commands. + * Logs unsupported messages to array. + * Call's user handler (if available) for CatchAll. + * + * @access private + * @param String $data Raw message from server + * @return void + */ + function CatchAll($data) + { + //Add to a log of unsupported messages. + + $this->unsupported[] = $data; + //$this->log($data); + //print_r($data); + + $this->callHandler("CatchAll", $data); + } + + /** + * Calls User Handler + * + * Calls registered handler for a specific event. + * + * @access private + * @param String $event Command (event) name (Rvous etc) + * @param String $data Raw message from server + * @see registerHandler + * @return void + */ + function callHandler($event, $data) + { + + if (isset($this->myEventHandlers[$event])) + { + //$function = $this->myEventHandlers[$event] . "(\$data);"; + //eval($function); + call_user_func($this->myEventHandlers[$event], $data); + } + else + { + $this->noHandler($data); + } + } + + /** + * Registers a user handler + * + * Handler List + * SignOn, Config, ERROR, NICK, IMIn, UpdateBuddy, Eviled, Warned, ChatJoin + * ChatIn, ChatUpdate, ChatInvite, ChatLeft, GotoURL, DirStatus, AdminNick + * AdminPasswd, Pause, Rvous, DimIn, CatchAll + * + * @access private + * @param String $event Event name + * @param String $handler User function to call + * @see callHandler + * @return boolean Returns true if successful + */ + function registerHandler($event, $handler) + { + if (is_callable($handler)) + { + $this->myEventHandlers[$event] = $handler; + return true; + } + else + { + return false; + } + } + + /** + * No user handler method fall back. + * + * Does nothing with message. + * + * @access public + * @param String $message Raw server message + * @return void + */ + function noHandler($message) + { + //This function intentionally left blank + //This is where the handlers will fall to for now. I plan on including a more + //efficent check to avoid the apparent stack jumps that this code will produce + //But for now, just fall into here, and be happy + return; + } + + //GLOBAL FUNCTIONS + + /** + * Finds type, and returns as part of array ['type'] + * Puts message in ['incoming'] + * + * Helper method for getMessageInfo. + * + * @access public + * @param String $message Raw server message + * @see msg_parse + * @see getMessageInfo + * @return array + */ + static function msg_type($message) + { + $command = array(); + @list($cmd, $rest) = explode(":", $message); + switch($cmd) + { + case 'IM_IN2': + $type = AIM_TYPE_MSG; + break; + + case 'UPDATE_BUDDY2': + $type = AIM_TYPE_UPDATEBUDDY; + break; + + case 'EVILED': + $type = AIM_TYPE_WARN; + break; + + case 'SIGN_ON': + $type = AIM_TYPE_SIGNON; + break; + + case 'NICK': + $type = AIM_TYPE_NICK; + break; + + case 'ERROR': + $type = AIM_TYPE_ERROR; + break; + + case 'CHAT_JOIN': + $type = AIM_TYPE_CHATJ; + break; + + case 'CHAT_IN': + $type = AIM_TYPE_CHATI; + break; + + case 'CHAT_UPDATE_BUDDY': + $type = AIM_TYPE_CHATUPDBUD; + break; + + case 'CHAT_INVITE': + $type = AIM_TYPE_CHATINV; + break; + + case 'CHAT_LEFT': + $type = AIM_TYPE_CHATLE; + break; + + case 'GOTO_URL': + $type = AIM_TYPE_URL; + break; + + case 'ADMIN_NICK_STATUS': + $type = AIM_TYPE_NICKSTAT; + break; + + case 'ADMIN_PASSWD_STATUS': + $type = AIM_TYPE_PASSSTAT; + break; + + case 'RVOUS_PROPOSE': + $type = AIM_TYPE_RVOUSP; + break; + + default: + $type = AIM_TYPE_NOT_IMPLEMENTED; + break; + } + $command['type'] = $type; + $command['incoming'] = $message; + return $command; + } + + /** + * Parses message and splits into info array + * + * Helper method for getMessageInfo. + * + * @access public + * @param String $command Message and type (after msg_type) + * @see msg_type + * @see getMessageInfo + * @return array + */ + static function msg_parse($command) + { + $info = array(); + switch($command['type']) + { + case AIM_TYPE_WARN: + $command['incoming'] .= ":0"; + $it = explode(":", $command['incoming']); + $info['warnlevel'] = $it[1]; + $info['from'] = $it[2]; + + break; + + case AIM_TYPE_MSG: + $it = explode(":", $command['incoming'],5); + $info['auto'] = $it[2]; + $info['from'] = $it[1]; + $info['message'] = $it[4]; + break; + + case AIM_TYPE_UPDATEBUDDY: + @list($cmd, $info['sn'], $info['online'], $info['warnlevel'], $info['signon'], $info['idle'], $info['uc']) = explode(":", $command['incoming']); + break; + + case AIM_TYPE_SIGNON: + @list($cmd, $info['version']) = explode(":", $command['incoming']); + break; + + case AIM_TYPE_NICK: + @list($cmd, $info['nickname']) = explode(":", $command['incoming']); + break; + case AIM_TYPE_ERROR: + @list($cmd, $info['errorcode'], $info['args']) = explode(":", $command['incoming']); + break; + + case AIM_TYPE_CHATJ: + @list($cmd, $info['chatid'], $info['chatname']) = explode(":", $command['incoming']); + break; + + case AIM_TYPE_CHATI: + @list($cmd, $info['chatid'], $info['user'], $info['whisper'], $info['message']) = explode(":", $command['incoming'],5); + break; + + case AIM_TYPE_CHATUPDBUD: + @list($cmd, $info['chatid'], $info['inside'], $info['userlist']) = explode(":", $command['incoming'],3); + break; + + case AIM_TYPE_CHATINV: + @list($cmd, $info['chatname'], $info['chatid'], $info['from'], $info['message']) = explode(":", $command['incoming'],5); + break; + + case AIM_TYPE_CHATLE: + @list($cmd, $info['chatid']) = explode(":", $command['incoming']); + break; + + case AIM_TYPE_URL: + @list($cmd, $info['windowname'], $info['url']) = explode(":", $command['incoming'],3); + break; + + case AIM_TYPE_RVOUSP: + @list($cmd,$info['user'],$info['uuid'],$info['cookie'],$info['seq'],$info['rip'],$info['pip'],$info['vip'],$info['port'],$info['tlvs']) = explode(":",$command['incoming'],10); + break; + + case AIM_TYPE_NICKSTAT: + case AIM_TYPE_PASSSTAT: + @list($cmd, $info['returncode'], $info['opt']) = explode(":", $command['incoming'],3); + break; + + default: + $info['command'] = $command['incoming']; + } + return $info; + } + + /** + * Returns a parsed message + * + * Calls msg_parse(msg_type( to first determine message type and then parse accordingly + * + * @access public + * @param String $command Raw server message + * @see msg_type + * @see msg_parse + * @return array + */ + static function getMessageInfo($message) + { + return self::msg_parse(self::msg_type($message)); + } + + /** + * Checks socket for end of file + * + * @access public + * @param Resource $socket Socket to check + * @return boolean true if end of file (socket) + */ + static function socketcheck($socket){ + $info = stream_get_meta_data($socket); + return $info['eof']; + //return(feof($socket)); + } +} + +?> diff --git a/plugins/Aim/extlib/phptoclib/dconnection.php b/plugins/Aim/extlib/phptoclib/dconnection.php new file mode 100755 index 000000000..c6be25ffb --- /dev/null +++ b/plugins/Aim/extlib/phptoclib/dconnection.php @@ -0,0 +1,229 @@ +<?php + +//The following class was created June 30th 2004 by Jeremy(pickle) +//This class is designed to handle a direct connection + +class Dconnect +{ + var $sock; + var $lastReceived; + var $lastMessage; + var $connected; + var $cookie; + var $type=2; + var $connectedTo; + + + function Dconnect($ip,$port) + { + if(!$this->connect($ip,$port)) + { + sEcho("Connection failed constructor"); + $this->connected=false; + } + else + $this->connected=true; + + $this->lastMessage=""; + $this->lastReceived=""; + } + + function readDIM() + { + /* + if(!$this->stuffToRead()) + { + sEcho("Nothing to read"); + $this->lastMessage=$this->lastReceived=""; + return false; + } + */ + $head=fread($this->sock,6); + if(strlen($head)<=0) + { + sEcho("The direct connection has been closed"); + return false; + } + $minihead=unpack("a4ver/nsize",$head); + if($minihead['size'] <=0) + return; + $headerinfo=unpack("nchan/nsix/nzero/a6cookie/Npt1/Npt2/npt3/Nlen/Npt/npt0/ntype/Nzerom/a*sn",fread($this->sock,($minihead['size']-6))); + $allheader=array_merge($minihead,$headerinfo); + sEcho($allheader); + if($allheader['len']>0 && $allheader['len'] <= MAX_DIM_SIZE) + { + $left=$allheader['len']; + $stuff=""; + $nonin=0; + while(strlen($stuff) < $allheader['len'] && $nonin<3) + { + $stuffg=fread($this->sock,$left); + if(strlen($stuffg)<0) + { + $nonin++; + continue; + } + $left=$left - strlen($stuffg); + $stuff.=$stuffg; + } + $data=unpack("a*decoded",$stuff); + } + + else if($allheader['len'] > MAX_DIM_SIZE) + { + $data['decoded']="too big"; + } + + else + $data['decoded']=""; + $all=array_merge($allheader,$data); + + $this->lastReceived=$all; + $this->lastMessage=$all['decoded']; + + //$function=$this->DimInf . "(\$all);"; + //eval($function); + + return $all; + } + + function sendMessage($message,$sn) + { + //Make the "mini header" + $minihead=pack("a4n","ODC2",76); + $header=pack("nnna6NNnNNnnNa*",1,6,0,$this->cookie,0,0,0,strlen($message),0,0,96,0,$sn); + $bighead=$minihead . $header; + while(strlen($bighead)<76) + $bighead.=pack("c",0); + + $tosend=$bighead . pack("a*",$message); + $w=array($this->sock); + stream_select($r=NULL,$w,$e=NULL,NULL); + //Now send it all + fputs($this->sock,$tosend,strlen($tosend)); + } + function stuffToRead() + { + //$info=stream_get_meta_data($this->sock); + //sEcho($info); + $s=array($this->sock); + $changed=stream_select($s,$fds=NULL,$m=NULL,0,20000); + return ($changed>0); + } + + function close() + { + $this->connected=false; + return fclose($this->sock); + } + + function connect($ip,$port) + { + $this->sock=fsockopen($ip,$port,$en,$es,3); + if(!$this->sock) + { sEcho("Connection failed"); + $this->sock=null; + return false; + } + return true; + } +} + + +class FileSendConnect +{ + var $sock; + var $lastReceived; + var $lastMessage; + var $connected; + var $cookie; + var $tpye=3; + + + function FileSendConnect($ip,$port) + { + if(!$this->connect($ip,$port)) + { + sEcho("Connection failed constructor"); + $this->connected=false; + } + else + $this->connected=true; + + $this->lastMessage=""; + $this->lastReceived=""; + } + + function readDIM() + { + + if(!$this->stuffToRead()) + { + sEcho("Nothing to read"); + $this->lastMessage=$this->lastReceived=""; + return; + } + + $minihead=unpack("a4ver/nsize",fread($this->sock,6)); + if($minihead['size'] <=0) + return; + $headerinfo=unpack("nchan/nsix/nzero/a6cookie/Npt1/Npt2/npt3/Nlen/Npt/npt0/ntype/Nzerom/a*sn",fread($this->sock,($minihead['size']-6))); + $allheader=array_merge($minihead,$headerinfo); + sEcho($allheader); + if($allheader['len']>0) + $data=unpack("a*decoded",fread($this->sock,$allheader['len'])); + else + $data['decoded']=""; + $all=array_merge($allheader,$data); + + $this->lastReceived=$all; + $this->lastMessage=$all['decoded']; + + //$function=$this->DimInf . "(\$all);"; + //eval($function); + + return $all; + } + + function sendMessage($message,$sn) + { + //Make the "mini header" + $minihead=pack("a4n","ODC2",76); + $header=pack("nnna6NNnNNnnNa*",1,6,0,$this->cookie,0,0,0,strlen($message),0,0,96,0,$sn); + $bighead=$minihead . $header; + while(strlen($bighead)<76) + $bighead.=pack("c",0); + + $tosend=$bighead . pack("a*",$message); + + //Now send it all + fwrite($this->sock,$tosend,strlen($tosend)); + } + function stuffToRead() + { + //$info=stream_get_meta_data($this->sock); + //sEcho($info); + $s=array($this->sock); + $changed=stream_select($s,$fds=NULL,$m=NULL,1); + return ($changed>0); + } + + function close() + { + $this->connected=false; + fclose($this->sock); + unset($this->sock); + return true; + } + + function connect($ip,$port) + { + $this->sock=fsockopen($ip,$port,$en,$es,3); + if(!$this->sock) + { sEcho("Connection failed to" . $ip . ":" . $port); + $this->sock=null; + return false; + } + return true; + } +} diff --git a/plugins/BitlyUrl/BitlyUrlPlugin.php b/plugins/BitlyUrl/BitlyUrlPlugin.php index f7f28b4d6..b649d3d0b 100644 --- a/plugins/BitlyUrl/BitlyUrlPlugin.php +++ b/plugins/BitlyUrl/BitlyUrlPlugin.php @@ -31,8 +31,6 @@ if (!defined('STATUSNET')) { exit(1); } -require_once INSTALLDIR.'/plugins/UrlShortener/UrlShortenerPlugin.php'; - class BitlyUrlPlugin extends UrlShortenerPlugin { public $serviceUrl; diff --git a/plugins/ClientSideShorten/ClientSideShortenPlugin.php b/plugins/ClientSideShorten/ClientSideShortenPlugin.php index ba1f7d3a7..454bedb08 100644 --- a/plugins/ClientSideShorten/ClientSideShortenPlugin.php +++ b/plugins/ClientSideShorten/ClientSideShortenPlugin.php @@ -51,8 +51,10 @@ class ClientSideShortenPlugin extends Plugin } function onEndShowScripts($action){ - $action->inlineScript('var Notice_maxContent = ' . Notice::maxContent()); if (common_logged_in()) { + $user = common_current_user(); + $action->inlineScript('var maxNoticeLength = ' . User_urlshortener_prefs::maxNoticeLength($user)); + $action->inlineScript('var maxUrlLength = ' . User_urlshortener_prefs::maxUrlLength($user)); $action->script('plugins/ClientSideShorten/shorten.js'); } } diff --git a/plugins/ClientSideShorten/shorten.js b/plugins/ClientSideShorten/shorten.js index 856c7f05f..bdffb81e2 100644 --- a/plugins/ClientSideShorten/shorten.js +++ b/plugins/ClientSideShorten/shorten.js @@ -31,10 +31,21 @@ })(jQuery,'smartkeypress'); + function longestWordInString(string) + { + var words = string.split(/\s/); + var longestWord = 0; + for(var i=0;i<words.length;i++) + if(words[i].length > longestWord) longestWord = words[i].length; + return longestWord; + } + function shorten() { - $noticeDataText = $('#'+SN.C.S.NoticeDataText); - if(Notice_maxContent > 0 && $noticeDataText.val().length > Notice_maxContent){ + var $noticeDataText = $('#'+SN.C.S.NoticeDataText); + var noticeText = $noticeDataText.val(); + + if(noticeText.length > maxNoticeLength || longestWordInString(noticeText) > maxUrlLength) { var original = $noticeDataText.val(); shortenAjax = $.ajax({ url: $('address .url')[0].href+'/plugins/ClientSideShorten/shorten', diff --git a/plugins/Imap/imapmanager.php b/plugins/Imap/imapmanager.php index e4fda5809..4c0edeaa1 100644 --- a/plugins/Imap/imapmanager.php +++ b/plugins/Imap/imapmanager.php @@ -57,12 +57,14 @@ class ImapManager extends IoManager } /** - * Tell the i/o master we need one instance for each supporting site - * being handled in this process. + * Tell the i/o master we need one instance globally. + * Since this is a plugin manager, the plugin class itself will + * create one instance per site. This prevents the IoMaster from + * making more instances. */ public static function multiSite() { - return IoManager::INSTANCE_PER_SITE; + return IoManager::GLOBAL_SINGLE_ONLY; } /** diff --git a/plugins/LilUrl/LilUrlPlugin.php b/plugins/LilUrl/LilUrlPlugin.php index c3e37c0c0..cdff9f4e6 100644 --- a/plugins/LilUrl/LilUrlPlugin.php +++ b/plugins/LilUrl/LilUrlPlugin.php @@ -31,8 +31,6 @@ if (!defined('STATUSNET')) { exit(1); } -require_once INSTALLDIR.'/plugins/UrlShortener/UrlShortenerPlugin.php'; - class LilUrlPlugin extends UrlShortenerPlugin { public $serviceUrl; diff --git a/plugins/PtitUrl/PtitUrlPlugin.php b/plugins/PtitUrl/PtitUrlPlugin.php index ddba942e6..cdf46846b 100644 --- a/plugins/PtitUrl/PtitUrlPlugin.php +++ b/plugins/PtitUrl/PtitUrlPlugin.php @@ -30,7 +30,6 @@ if (!defined('STATUSNET')) { exit(1); } -require_once INSTALLDIR.'/plugins/UrlShortener/UrlShortenerPlugin.php'; class PtitUrlPlugin extends UrlShortenerPlugin { diff --git a/plugins/SimpleUrl/SimpleUrlPlugin.php b/plugins/SimpleUrl/SimpleUrlPlugin.php index 6eac7dbb1..5d3f97d33 100644 --- a/plugins/SimpleUrl/SimpleUrlPlugin.php +++ b/plugins/SimpleUrl/SimpleUrlPlugin.php @@ -31,8 +31,6 @@ if (!defined('STATUSNET')) { exit(1); } -require_once INSTALLDIR.'/plugins/UrlShortener/UrlShortenerPlugin.php'; - class SimpleUrlPlugin extends UrlShortenerPlugin { public $serviceUrl; diff --git a/plugins/TightUrl/TightUrlPlugin.php b/plugins/TightUrl/TightUrlPlugin.php index e2d494a7b..f242db6c8 100644 --- a/plugins/TightUrl/TightUrlPlugin.php +++ b/plugins/TightUrl/TightUrlPlugin.php @@ -31,8 +31,6 @@ if (!defined('STATUSNET')) { exit(1); } -require_once INSTALLDIR.'/plugins/UrlShortener/UrlShortenerPlugin.php'; - class TightUrlPlugin extends UrlShortenerPlugin { public $serviceUrl; diff --git a/plugins/UrlShortener/UrlShortenerPlugin.php b/plugins/UrlShortener/UrlShortenerPlugin.php deleted file mode 100644 index 027624b7a..000000000 --- a/plugins/UrlShortener/UrlShortenerPlugin.php +++ /dev/null @@ -1,95 +0,0 @@ -<?php -/** - * StatusNet, the distributed open-source microblogging tool - * - * Superclass for plugins that do URL shortening - * - * PHP version 5 - * - * LICENCE: This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program 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 Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * @category Plugin - * @package StatusNet - * @author Craig Andrews <candrews@integralblue.com> - * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 - * @link http://status.net/ - */ - -if (!defined('STATUSNET') && !defined('LACONICA')) { - exit(1); -} - -/** - * Superclass for plugins that do URL shortening - * - * @category Plugin - * @package StatusNet - * @author Craig Andrews <candrews@integralblue.com> - * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 - * @link http://status.net/ - */ - -abstract class UrlShortenerPlugin extends Plugin -{ - public $shortenerName; - public $freeService=false; - //------------Url Shortener plugin should implement some (or all) of these methods------------\\ - - /** - * Short a URL - * @param url - * @return string shortened version of the url, or null if URL shortening failed - */ - protected abstract function shorten($url); - - //------------These methods may help you implement your plugin------------\\ - protected function http_get($url) - { - $request = HTTPClient::start(); - $response = $request->get($url); - return $response->getBody(); - } - - protected function http_post($url,$data) - { - $request = HTTPClient::start(); - $response = $request->post($url, null, $data); - return $response->getBody(); - } - - //------------Below are the methods that connect StatusNet to the implementing Url Shortener plugin------------\\ - - function onInitializePlugin(){ - if(!isset($this->shortenerName)){ - throw new Exception("must specify a shortenerName"); - } - } - - function onGetUrlShorteners(&$shorteners) - { - $shorteners[$this->shortenerName]=array('freeService'=>$this->freeService); - } - - function onStartShortenUrl($url,$shortenerName,&$shortenedUrl) - { - if($shortenerName == $this->shortenerName && strlen($url) >= common_config('site', 'shorturllength')){ - $result = $this->shorten($url); - if(isset($result) && $result != null && $result !== false){ - $shortenedUrl=$result; - common_log(LOG_INFO, __CLASS__ . ": $this->shortenerName shortened $url to $shortenedUrl"); - return false; - } - } - } -} diff --git a/plugins/Xmpp/Queued_XMPP.php b/plugins/Xmpp/Queued_XMPP.php new file mode 100644 index 000000000..73eff2246 --- /dev/null +++ b/plugins/Xmpp/Queued_XMPP.php @@ -0,0 +1,121 @@ +<?php +/** + * StatusNet, the distributed open-source microblogging tool + * + * Queue-mediated proxy class for outgoing XMPP messages. + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @category Network + * @package StatusNet + * @author Brion Vibber <brion@status.net> + * @copyright 2010 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { + exit(1); +} + +class Queued_XMPP extends XMPPHP_XMPP +{ + /** + * Reference to the XmppPlugin object we're hooked up to. + */ + public $plugin; + + /** + * Constructor + * + * @param XmppPlugin $plugin + * @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($plugin, $host, $port, $user, $password, $resource, $server = null, $printlog = false, $loglevel = null) + { + $this->plugin = $plugin; + + parent::__construct($host, $port, $user, $password, $resource, $server, $printlog, $loglevel); + + // We use $host to connect, but $server to build JIDs if specified. + // This seems to fix an upstream bug where $host was used to build + // $this->basejid, never seen since it isn't actually used in the base + // classes. + if (!$server) { + $server = $this->host; + } + $this->basejid = $this->user . '@' . $server; + + // Normally the fulljid is filled out by the server at resource binding + // time, but we need to do it since we're not talking to a real server. + $this->fulljid = "{$this->basejid}/{$this->resource}"; + } + + /** + * Send a formatted message to the outgoing queue for later forwarding + * to a real XMPP connection. + * + * @param string $msg + */ + public function send($msg, $timeout=NULL) + { + $this->plugin->enqueue_outgoing_raw($msg); + } + + //@{ + /** + * Stream i/o functions disabled; only do output + */ + public function connect($timeout = 30, $persistent = false, $sendinit = true) + { + throw new Exception("Can't connect to server from fake XMPP."); + } + + public function disconnect() + { + throw new Exception("Can't connect to server from fake XMPP."); + } + + public function process() + { + throw new Exception("Can't read stream from fake XMPP."); + } + + public function processUntil($event, $timeout=-1) + { + throw new Exception("Can't read stream from fake XMPP."); + } + + public function read() + { + throw new Exception("Can't read stream from fake XMPP."); + } + + public function readyToProcess() + { + throw new Exception("Can't read stream from fake XMPP."); + } + //@} + +} + diff --git a/plugins/Xmpp/README b/plugins/Xmpp/README new file mode 100644 index 000000000..9bd71e980 --- /dev/null +++ b/plugins/Xmpp/README @@ -0,0 +1,35 @@ +The XMPP plugin allows users to send and receive notices over the XMPP/Jabber/GTalk network. + +Installation +============ +add "addPlugin('xmpp', + array('setting'=>'value', 'setting2'=>'value2', ...);" +to the bottom of your config.php + +The daemon included with this plugin must be running. It will be started by +the plugin along with their other daemons when you run scripts/startdaemons.sh. +See the StatusNet README for more about queuing and daemons. + +Settings +======== +user*: user part of the jid +server*: server part of the jid +resource: resource part of the jid +port (5222): port on which to connect to the server +encryption (true): use encryption on the connection +host (same as server): host to connect to. Usually, you won't set this. +debug (false): log extra debug info +public: list of jid's that should get the public feed (firehose) + +* required +default values are in (parenthesis) + +Example +======= +addPlugin('xmpp', array( + 'user=>'update', + 'server=>'identi.ca', + 'password'=>'...', + 'public'=>array('bob@aol.com', 'sue@google.com') +)); + diff --git a/plugins/Xmpp/Sharing_XMPP.php b/plugins/Xmpp/Sharing_XMPP.php new file mode 100644 index 000000000..4b69125da --- /dev/null +++ b/plugins/Xmpp/Sharing_XMPP.php @@ -0,0 +1,43 @@ +<?php +/** + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2009, StatusNet, Inc. + * + * Send and receive notices using the Jabber network + * + * PHP version 5 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @category Jabber + * @package StatusNet + * @author Evan Prodromou <evan@status.net> + * @copyright 2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + // This check helps protect against security problems; + // your code file can't be executed directly from the web. + exit(1); +} + +class Sharing_XMPP extends XMPPHP_XMPP +{ + function getSocket() + { + return $this->socket; + } +} diff --git a/plugins/Xmpp/XmppPlugin.php b/plugins/Xmpp/XmppPlugin.php new file mode 100644 index 000000000..66468b5f2 --- /dev/null +++ b/plugins/Xmpp/XmppPlugin.php @@ -0,0 +1,433 @@ +<?php +/** + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2009, StatusNet, Inc. + * + * Send and receive notices using the XMPP network + * + * PHP version 5 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @category IM + * @package StatusNet + * @author Evan Prodromou <evan@status.net> + * @copyright 2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 + * @link http://status.net/ + */ + +if (!defined('STATUSNET')) { + // This check helps protect against security problems; + // your code file can't be executed directly from the web. + exit(1); +} + +/** + * Plugin for XMPP + * + * @category Plugin + * @package StatusNet + * @author Evan Prodromou <evan@status.net> + * @copyright 2009 StatusNet, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0 + * @link http://status.net/ + */ + +class XmppPlugin extends ImPlugin +{ + public $server = null; + public $port = 5222; + public $user = 'update'; + public $resource = null; + public $encryption = true; + public $password = null; + public $host = null; // only set if != server + public $debug = false; // print extra debug info + + public $transport = 'xmpp'; + + function getDisplayName(){ + return _m('XMPP/Jabber/GTalk'); + } + + /** + * Splits a Jabber ID (JID) into node, domain, and resource portions. + * + * Based on validation routine submitted by: + * @copyright 2009 Patrick Georgi <patrick@georgi-clan.de> + * @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact. + * + * @param string $jid string to check + * + * @return array with "node", "domain", and "resource" indices + * @throws Exception if input is not valid + */ + + protected function splitJid($jid) + { + $chars = ''; + /* the following definitions come from stringprep, Appendix C, + which is used in its entirety by nodeprop, Chapter 5, "Prohibited Output" */ + /* C1.1 ASCII space characters */ + $chars .= "\x{20}"; + /* C1.2 Non-ASCII space characters */ + $chars .= "\x{a0}\x{1680}\x{2000}-\x{200b}\x{202f}\x{205f}\x{3000a}"; + /* C2.1 ASCII control characters */ + $chars .= "\x{00}-\x{1f}\x{7f}"; + /* C2.2 Non-ASCII control characters */ + $chars .= "\x{80}-\x{9f}\x{6dd}\x{70f}\x{180e}\x{200c}\x{200d}\x{2028}\x{2029}\x{2060}-\x{2063}\x{206a}-\x{206f}\x{feff}\x{fff9}-\x{fffc}\x{1d173}-\x{1d17a}"; + /* C3 - Private Use */ + $chars .= "\x{e000}-\x{f8ff}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}"; + /* C4 - Non-character code points */ + $chars .= "\x{fdd0}-\x{fdef}\x{fffe}\x{ffff}\x{1fffe}\x{1ffff}\x{2fffe}\x{2ffff}\x{3fffe}\x{3ffff}\x{4fffe}\x{4ffff}\x{5fffe}\x{5ffff}\x{6fffe}\x{6ffff}\x{7fffe}\x{7ffff}\x{8fffe}\x{8ffff}\x{9fffe}\x{9ffff}\x{afffe}\x{affff}\x{bfffe}\x{bffff}\x{cfffe}\x{cffff}\x{dfffe}\x{dffff}\x{efffe}\x{effff}\x{ffffe}\x{fffff}\x{10fffe}\x{10ffff}"; + /* C5 - Surrogate codes */ + $chars .= "\x{d800}-\x{dfff}"; + /* C6 - Inappropriate for plain text */ + $chars .= "\x{fff9}-\x{fffd}"; + /* C7 - Inappropriate for canonical representation */ + $chars .= "\x{2ff0}-\x{2ffb}"; + /* C8 - Change display properties or are deprecated */ + $chars .= "\x{340}\x{341}\x{200e}\x{200f}\x{202a}-\x{202e}\x{206a}-\x{206f}"; + /* C9 - Tagging characters */ + $chars .= "\x{e0001}\x{e0020}-\x{e007f}"; + + /* Nodeprep forbids some more characters */ + $nodeprepchars = $chars; + $nodeprepchars .= "\x{22}\x{26}\x{27}\x{2f}\x{3a}\x{3c}\x{3e}\x{40}"; + + $parts = explode("/", $jid, 2); + if (count($parts) > 1) { + $resource = $parts[1]; + if ($resource == '') { + // Warning: empty resource isn't legit. + // But if we're normalizing, we may as well take it... + } + } else { + $resource = null; + } + + $node = explode("@", $parts[0]); + if ((count($node) > 2) || (count($node) == 0)) { + throw new Exception("Invalid JID: too many @s"); + } else if (count($node) == 1) { + $domain = $node[0]; + $node = null; + } else { + $domain = $node[1]; + $node = $node[0]; + if ($node == '') { + throw new Exception("Invalid JID: @ but no node"); + } + } + + // Length limits per http://xmpp.org/rfcs/rfc3920.html#addressing + if ($node !== null) { + if (strlen($node) > 1023) { + throw new Exception("Invalid JID: node too long."); + } + if (preg_match("/[".$nodeprepchars."]/u", $node)) { + throw new Exception("Invalid JID node '$node'"); + } + } + + if (strlen($domain) > 1023) { + throw new Exception("Invalid JID: domain too long."); + } + if (!common_valid_domain($domain)) { + throw new Exception("Invalid JID domain name '$domain'"); + } + + if ($resource !== null) { + if (strlen($resource) > 1023) { + throw new Exception("Invalid JID: resource too long."); + } + if (preg_match("/[".$chars."]/u", $resource)) { + throw new Exception("Invalid JID resource '$resource'"); + } + } + + return array('node' => is_null($node) ? null : mb_strtolower($node), + 'domain' => is_null($domain) ? null : mb_strtolower($domain), + 'resource' => $resource); + } + + /** + * Checks whether a string is a syntactically valid Jabber ID (JID), + * either with or without a resource. + * + * Note that a bare domain can be a valid JID. + * + * @param string $jid string to check + * @param bool $check_domain whether we should validate that domain... + * + * @return boolean whether the string is a valid JID + */ + protected function validateFullJid($jid, $check_domain=false) + { + try { + $parts = $this->splitJid($jid); + if ($check_domain) { + if (!$this->checkDomain($parts['domain'])) { + return false; + } + } + return $parts['resource'] !== ''; // missing or present; empty ain't kosher + } catch (Exception $e) { + return false; + } + } + + /** + * Checks whether a string is a syntactically valid base Jabber ID (JID). + * A base JID won't include a resource specifier on the end; since we + * take it off when reading input we can't really use them reliably + * to direct outgoing messages yet (sorry guys!) + * + * Note that a bare domain can be a valid JID. + * + * @param string $jid string to check + * @param bool $check_domain whether we should validate that domain... + * + * @return boolean whether the string is a valid JID + */ + protected function validateBaseJid($jid, $check_domain=false) + { + try { + $parts = $this->splitJid($jid); + if ($check_domain) { + if (!$this->checkDomain($parts['domain'])) { + return false; + } + } + return ($parts['resource'] === null); // missing; empty ain't kosher + } catch (Exception $e) { + return false; + } + } + + /** + * Normalizes a Jabber ID for comparison, dropping the resource component if any. + * + * @param string $jid JID to check + * @param bool $check_domain if true, reject if the domain isn't findable + * + * @return string an equivalent JID in normalized (lowercase) form + */ + + function normalize($jid) + { + try { + $parts = $this->splitJid($jid); + if ($parts['node'] !== null) { + return $parts['node'] . '@' . $parts['domain']; + } else { + return $parts['domain']; + } + } catch (Exception $e) { + return null; + } + } + + /** + * Check if this domain's got some legit DNS record + */ + protected function checkDomain($domain) + { + if (checkdnsrr("_xmpp-server._tcp." . $domain, "SRV")) { + return true; + } + if (checkdnsrr($domain, "ANY")) { + return true; + } + return false; + } + + function daemon_screenname() + { + $ret = $this->user . '@' . $this->server; + if($this->resource) + { + return $ret . '/' . $this->resource; + }else{ + return $ret; + } + } + + function validate($screenname) + { + return $this->validateBaseJid($screenname, common_config('email', 'check_domain')); + } + + /** + * Load related modules when needed + * + * @param string $cls Name of the class to be loaded + * + * @return boolean hook value; true means continue processing, false means stop. + */ + + function onAutoload($cls) + { + $dir = dirname(__FILE__); + + switch ($cls) + { + case 'XMPPHP_XMPP': + require_once $dir . '/extlib/XMPPHP/XMPP.php'; + return false; + case 'Sharing_XMPP': + case 'Queued_XMPP': + require_once $dir . '/'.$cls.'.php'; + return false; + case 'XmppManager': + require_once $dir . '/'.strtolower($cls).'.php'; + return false; + default: + return true; + } + } + + function onStartImDaemonIoManagers(&$classes) + { + parent::onStartImDaemonIoManagers(&$classes); + $classes[] = new XmppManager($this); // handles pings/reconnects + return true; + } + + function microiduri($screenname) + { + return 'xmpp:' . $screenname; + } + + function send_message($screenname, $body) + { + $this->queuedConnection()->message($screenname, $body, 'chat'); + } + + function send_notice($screenname, $notice) + { + $msg = $this->format_notice($notice); + $entry = $this->format_entry($notice); + + $this->queuedConnection()->message($screenname, $msg, 'chat', null, $entry); + return true; + } + + /** + * extra information for XMPP messages, as defined by Twitter + * + * @param Profile $profile Profile of the sending user + * @param Notice $notice Notice being sent + * + * @return string Extra information (Atom, HTML, addresses) in string format + */ + + function format_entry($notice) + { + $profile = $notice->getProfile(); + + $entry = $notice->asAtomEntry(true, true); + + $xs = new XMLStringer(); + $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im')); + $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml')); + $xs->element('a', array('href' => $profile->profileurl), + $profile->nickname); + $xs->text(": "); + if (!empty($notice->rendered)) { + $xs->raw($notice->rendered); + } else { + $xs->raw(common_render_content($notice->content, $notice)); + } + $xs->text(" "); + $xs->element('a', array( + 'href'=>common_local_url('conversation', + array('id' => $notice->conversation)).'#notice-'.$notice->id + ),sprintf(_('[%s]'),$notice->id)); + $xs->elementEnd('body'); + $xs->elementEnd('html'); + + $html = $xs->getString(); + + return $html . ' ' . $entry; + } + + function receive_raw_message($pl) + { + $from = $this->normalize($pl['from']); + + if ($pl['type'] != 'chat') { + $this->log(LOG_WARNING, "Ignoring message of type ".$pl['type']." from $from: " . $pl['xml']->toString()); + return; + } + + if (mb_strlen($pl['body']) == 0) { + $this->log(LOG_WARNING, "Ignoring message with empty body from $from: " . $pl['xml']->toString()); + return; + } + + $this->handle_incoming($from, $pl['body']); + + return true; + } + + /** + * Build a queue-proxied XMPP interface object. Any outgoing messages + * will be run back through us for enqueing rather than sent directly. + * + * @return Queued_XMPP + * @throws Exception if server settings are invalid. + */ + function queuedConnection(){ + if(!isset($this->server)){ + throw new Exception("must specify a server"); + } + if(!isset($this->port)){ + throw new Exception("must specify a port"); + } + if(!isset($this->user)){ + throw new Exception("must specify a user"); + } + if(!isset($this->password)){ + throw new Exception("must specify a password"); + } + + return new Queued_XMPP($this, $this->host ? + $this->host : + $this->server, + $this->port, + $this->user, + $this->password, + $this->resource, + $this->server, + $this->debug ? + true : false, + $this->debug ? + XMPPHP_Log::LEVEL_VERBOSE : null + ); + } + + function onPluginVersion(&$versions) + { + $versions[] = array('name' => 'XMPP', + 'version' => STATUSNET_VERSION, + 'author' => 'Craig Andrews, Evan Prodromou', + 'homepage' => 'http://status.net/wiki/Plugin:XMPP', + 'rawdescription' => + _m('The XMPP plugin allows users to send and receive notices over the XMPP/Jabber network.')); + return true; + } +} + diff --git a/plugins/Xmpp/extlib/XMPPHP/BOSH.php b/plugins/Xmpp/extlib/XMPPHP/BOSH.php new file mode 100644 index 000000000..befaf60a7 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/BOSH.php @@ -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; + } +} diff --git a/plugins/Xmpp/extlib/XMPPHP/Exception.php b/plugins/Xmpp/extlib/XMPPHP/Exception.php new file mode 100644 index 000000000..da59bc791 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/Exception.php @@ -0,0 +1,41 @@ +<?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 Exception + * + * @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_Exception extends Exception { +} diff --git a/plugins/Xmpp/extlib/XMPPHP/Log.php b/plugins/Xmpp/extlib/XMPPHP/Log.php new file mode 100644 index 000000000..a9bce3d84 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/Log.php @@ -0,0 +1,119 @@ +<?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 + * + * @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_Log { + + const LEVEL_ERROR = 0; + const LEVEL_WARNING = 1; + const LEVEL_INFO = 2; + const LEVEL_DEBUG = 3; + const LEVEL_VERBOSE = 4; + + /** + * @var array + */ + protected $data = array(); + + /** + * @var array + */ + protected $names = array('ERROR', 'WARNING', 'INFO', 'DEBUG', 'VERBOSE'); + + /** + * @var integer + */ + protected $runlevel; + + /** + * @var boolean + */ + protected $printout; + + /** + * Constructor + * + * @param boolean $printout + * @param string $runlevel + */ + public function __construct($printout = false, $runlevel = self::LEVEL_INFO) { + $this->printout = (boolean)$printout; + $this->runlevel = (int)$runlevel; + } + + /** + * Add a message to the log data array + * If printout in this instance is set to true, directly output the message + * + * @param string $msg + * @param integer $runlevel + */ + public function log($msg, $runlevel = self::LEVEL_INFO) { + $time = time(); + #$this->data[] = array($this->runlevel, $msg, $time); + if($this->printout and $runlevel <= $this->runlevel) { + $this->writeLine($msg, $runlevel, $time); + } + } + + /** + * Output the complete log. + * Log will be cleared if $clear = true + * + * @param boolean $clear + * @param integer $runlevel + */ + public function printout($clear = true, $runlevel = null) { + if($runlevel === null) { + $runlevel = $this->runlevel; + } + foreach($this->data as $data) { + if($runlevel <= $data[0]) { + $this->writeLine($data[1], $runlevel, $data[2]); + } + } + if($clear) { + $this->data = array(); + } + } + + 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(); + } +} diff --git a/plugins/Xmpp/extlib/XMPPHP/Roster.php b/plugins/Xmpp/extlib/XMPPHP/Roster.php new file mode 100644 index 000000000..2e459e2a2 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/Roster.php @@ -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; + } +} +?> diff --git a/plugins/Xmpp/extlib/XMPPHP/XMLObj.php b/plugins/Xmpp/extlib/XMPPHP/XMLObj.php new file mode 100644 index 000000000..0d3e21991 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/XMLObj.php @@ -0,0 +1,158 @@ +<?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 XML 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 XMPPHP_XMLObj { + /** + * Tag name + * + * @var string + */ + public $name; + + /** + * Namespace + * + * @var string + */ + public $ns; + + /** + * Attributes + * + * @var array + */ + public $attrs = array(); + + /** + * Subs? + * + * @var array + */ + public $subs = array(); + + /** + * Node data + * + * @var string + */ + public $data = ''; + + /** + * Constructor + * + * @param string $name + * @param string $ns + * @param array $attrs + * @param string $data + */ + public function __construct($name, $ns = '', $attrs = array(), $data = '') { + $this->name = strtolower($name); + $this->ns = $ns; + if(is_array($attrs) && count($attrs)) { + foreach($attrs as $key => $value) { + $this->attrs[strtolower($key)] = $value; + } + } + $this->data = $data; + } + + /** + * Dump this XML Object to output. + * + * @param integer $depth + */ + public function printObj($depth = 0) { + print str_repeat("\t", $depth) . $this->name . " " . $this->ns . ' ' . $this->data; + print "\n"; + foreach($this->subs as $sub) { + $sub->printObj($depth + 1); + } + } + + /** + * Return this XML Object in xml notation + * + * @param string $str + */ + public function toString($str = '') { + $str .= "<{$this->name} xmlns='{$this->ns}' "; + foreach($this->attrs as $key => $value) { + if($key != 'xmlns') { + $value = htmlspecialchars($value); + $str .= "$key='$value' "; + } + } + $str .= ">"; + foreach($this->subs as $sub) { + $str .= $sub->toString(); + } + $body = htmlspecialchars($this->data); + $str .= "$body</{$this->name}>"; + return $str; + } + + /** + * Has this XML Object the given sub? + * + * @param string $name + * @return boolean + */ + public function hasSub($name, $ns = null) { + foreach($this->subs as $sub) { + if(($name == "*" or $sub->name == $name) and ($ns == null or $sub->ns == $ns)) return true; + } + return false; + } + + /** + * Return a sub + * + * @param string $name + * @param string $attrs + * @param string $ns + */ + public function sub($name, $attrs = null, $ns = null) { + #TODO attrs is ignored + foreach($this->subs as $sub) { + if($sub->name == $name and ($ns == null or $sub->ns == $ns)) { + return $sub; + } + } + } +} diff --git a/plugins/Xmpp/extlib/XMPPHP/XMLStream.php b/plugins/Xmpp/extlib/XMPPHP/XMLStream.php new file mode 100644 index 000000000..d33411ec5 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/XMLStream.php @@ -0,0 +1,763 @@ +<?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_Exception */ +require_once dirname(__FILE__) . '/Exception.php'; + +/** XMPPHP_XMLObj */ +require_once dirname(__FILE__) . '/XMLObj.php'; + +/** XMPPHP_Log */ +require_once dirname(__FILE__) . '/Log.php'; + +/** + * XMPPHP XML Stream + * + * @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_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 string + */ + protected $until_count = ''; + /** + * @var array + */ + protected $until_happened = false; + /** + * @var array + */ + protected $until_payload = array(); + /** + * @var XMPPHP_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 XMPPHP_Log($printlog, $loglevel); + } + + /** + * Destructor + * Cleanup connection + */ + public function __destruct() { + if(!$this->disconnected && $this->socket) { + $this->disconnect(); + } + } + + /** + * Return the log instance + * + * @return XMPPHP_Log + */ + public function getLog() { + return $this->log; + } + + /** + * Get next ID + * + * @return integer + */ + public function getId() { + $this->lastid++; + return $this->lastid; + } + + /** + * Set SSL + * + * @return integer + */ + 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) = 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->eventhandlers[] = array($name, $pointer, $obj); + } + + /** + * Connect to XMPP Host + * + * @param integer $timeout + * @param boolean $persistent + * @param boolean $sendinit + */ + 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}"); + 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 { + throw new XMPPHP_Exception("Could not connect before timeout."); + } + } + + /** + * Reconnect XMPP Host + */ + public function doReconnect() { + if(!$this->is_server) { + $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; + $this->processUntil('end_stream', 5); + $this->disconnected = true; + } + + /** + * Are we are disconnected? + * + * @return boolean + */ + public function isDisconnected() { + return $this->disconnected; + } + + /** + * 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. + } + $endtime = (microtime(true)*1000000); + $time_past = $endtime - $starttime; + $remaining = $remaining - $time_past; + } while (is_null($maximum) || $remaining > 0); + return true; + } + + /** + * Process + * + * @return string + */ + public function process() { + $this->__process(NULL); + } + + /** + * Process until a timeout occurs + * + * @param integer $timeout + * @return string + */ + public function processTime($timeout=NULL) { + if (is_null($timeout)) { + return $this->__process(NULL); + } else { + return $this->__process($timeout * 1000000); + } + } + + /** + * Process until a specified event or a timeout occurs + * + * @param string|array $event + * @param integer $timeout + * @return string + */ + 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; + $updated = ''; + 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; + } + + /** + * Obsolete? + */ + public function Xapply_socket($socket) { + $this->socket = $socket; + } + + /** + * XML start callback + * + * @see xml_set_element_handler + * + * @param resource $parser + * @param string $name + */ + 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 XMPPHP_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 + * + * @see xml_set_element_handler + * + * @param resource $parser + * @param string $name + */ + public function endXML($parser, $name) { + #$this->log->log("Ending $name", XMPPHP_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]}", XMPPHP_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]}", XMPPHP_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 XMPPHP_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 + * @see xml_set_character_data_handler + * + * @param resource $parser + * @param string $data + */ + public function charXML($parser, $data) { + if(array_key_exists($this->xml_depth, $this->xmlobj)) { + $this->xmlobj[$this->xml_depth]->data .= $data; + } + } + + /** + * Event? + * + * @param string $name + * @param string $payload + */ + public function event($name, $payload = null) { + $this->log->log("EVENT: $name", XMPPHP_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; + } + } + } + } + + /** + * 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", XMPPHP_Log::LEVEL_VERBOSE); + xml_parse($this->parser, $buff, false); + } + + /** + * Send to socket + * + * @param string $msg + */ + 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.", XMPPHP_Log::LEVEL_VERBOSE); + } else { + $this->log->log("Socket is not ready; break.", XMPPHP_Log::LEVEL_ERROR); + return false; + } + + $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(); + return false; + } + $this->log->log("Successfully sent $sentbytes bytes.", XMPPHP_Log::LEVEL_VERBOSE); + return $sentbytes; + } + + public function time() { + list($usec, $sec) = explode(" ", microtime()); + return (float)$sec + (float)$usec; + } + + /** + * 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; + } + + /** + * 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'); + } + + public function readyToProcess() { + $read = array($this->socket); + $write = array(); + $except = array(); + $updated = @stream_select($read, $write, $except, 0); + return (($updated !== false) && ($updated > 0)); + } +} diff --git a/plugins/Xmpp/extlib/XMPPHP/XMPP.php b/plugins/Xmpp/extlib/XMPPHP/XMPP.php new file mode 100644 index 000000000..c0f896339 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/XMPP.php @@ -0,0 +1,432 @@ +<?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__) . "/XMLStream.php"; +require_once dirname(__FILE__) . "/Roster.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_XMPP extends XMPPHP_XMLStream { + /** + * @var string + */ + public $server; + + /** + * @var string + */ + public $user; + + /** + * @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; + + /** + * @var boolean + */ + public $track_presence = true; + + /** + * @var object + */ + public $roster; + + /** + * 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->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 + */ + 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'>"; + if($subject) $out .= "<subject>$subject</subject>"; + $out .= "<body>$body</body>"; + if($payload) $out .= $payload; + $out .= "</message>"; + + $this->send($out); + } + + /** + * Set Presence + * + * @param string $status + * @param string $show + * @param string $to + */ + 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($type) $out .= " type='$type'"; + if($show == 'available' and !$status) { + $out .= "/>"; + } else { + $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 + * + * @param string $xml + */ + public function message_handler($xml) { + if(isset($xml->attrs['type'])) { + $payload['type'] = $xml->attrs['type']; + } else { + $payload['type'] = 'chat'; + } + $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); + } + + /** + * 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']}", XMPPHP_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); + } + } + + /** + * 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 + */ + protected function sasl_failure_handler($xml) { + $this->log->log("Auth failed!", XMPPHP_Log::LEVEL_ERROR); + $this->disconnect(); + + throw new XMPPHP_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>"); + } + + /** + * 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>"); + } + + /** + * 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(); + } + + /** + * 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); + } +} diff --git a/plugins/Xmpp/extlib/XMPPHP/XMPP_Old.php b/plugins/Xmpp/extlib/XMPPHP/XMPP_Old.php new file mode 100644 index 000000000..43f56b154 --- /dev/null +++ b/plugins/Xmpp/extlib/XMPPHP/XMPP_Old.php @@ -0,0 +1,114 @@ +<?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 + * + * This file is unnecessary unless you need to connect to older, non-XMPP-compliant servers like Dreamhost's. + * In this case, use instead of XMPPHP_XMPP, otherwise feel free to delete it. + * The old Jabber protocol wasn't standardized, so use at your own risk. + * + */ +require_once "XMPP.php"; + + class XMPPHP_XMPPOld extends XMPPHP_XMPP { + /** + * + * @var string + */ + protected $session_id; + + 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}"; + } + + /** + * Override XMLStream's startXML + * + * @param parser $parser + * @param string $name + * @param array $attr + */ + public function startXML($parser, $name, $attr) { + if($this->xml_depth == 0) { + $this->session_id = $attr['ID']; + $this->authenticate(); + } + parent::startXML($parser, $name, $attr); + } + + /** + * Send Authenticate Info Request + * + */ + public function authenticate() { + $id = $this->getId(); + $this->addidhandler($id, 'authfieldshandler'); + $this->send("<iq type='get' id='$id'><query xmlns='jabber:iq:auth'><username>{$this->user}</username></query></iq>"); + } + + /** + * Retrieve auth fields and send auth attempt + * + * @param XMLObj $xml + */ + public function authFieldsHandler($xml) { + $id = $this->getId(); + $this->addidhandler($id, 'oldAuthResultHandler'); + if($xml->sub('query')->hasSub('digest')) { + $hash = sha1($this->session_id . $this->password); + 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><password>{$this->password}</password><resource>{$this->resource}</resource></query></iq>"; + } + $this->send($out); + + } + + /** + * Determine authenticated or failure + * + * @param XMLObj $xml + */ + public function oldAuthResultHandler($xml) { + if($xml->attrs['type'] != 'result') { + $this->log->log("Auth failed!", XMPPHP_Log::LEVEL_ERROR); + $this->disconnect(); + throw new XMPPHP_Exception('Auth failed!'); + } else { + $this->log->log("Session started"); + $this->event('session_start'); + } + } + } + + +?> diff --git a/plugins/Xmpp/xmppmanager.php b/plugins/Xmpp/xmppmanager.php new file mode 100644 index 000000000..87d818668 --- /dev/null +++ b/plugins/Xmpp/xmppmanager.php @@ -0,0 +1,279 @@ +<?php +/* + * StatusNet - the distributed open-source microblogging tool + * Copyright (C) 2008, 2009, StatusNet, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); } + +/** + * XMPP background connection manager for XMPP-using queue handlers, + * allowing them to send outgoing messages on the right connection. + * + * Input is handled during socket select loop, keepalive pings during idle. + * Any incoming messages will be handled. + * + * In a multi-site queuedaemon.php run, one connection will be instantiated + * for each site being handled by the current process that has XMPP enabled. + */ + +class XmppManager extends ImManager +{ + protected $lastping = null; + protected $pingid = null; + + public $conn = null; + + const PING_INTERVAL = 120; + + + /** + * Initialize connection to server. + * @return boolean true on success + */ + public function start($master) + { + if(parent::start($master)) + { + $this->connect(); + return true; + }else{ + return false; + } + } + + function send_raw_message($data) + { + $this->connect(); + if (!$this->conn || $this->conn->isDisconnected()) { + return false; + } + $this->conn->send($data); + return true; + } + + /** + * Message pump is triggered on socket input, so we only need an idle() + * call often enough to trigger our outgoing pings. + */ + function timeout() + { + return self::PING_INTERVAL; + } + + /** + * Process XMPP events that have come in over the wire. + * @fixme may kill process on XMPP error + * @param resource $socket + */ + public function handleInput($socket) + { + # Process the queue for as long as needed + try { + common_log(LOG_DEBUG, "Servicing the XMPP queue."); + $this->stats('xmpp_process'); + $this->conn->processTime(0); + } catch (XMPPHP_Exception $e) { + common_log(LOG_ERR, "Got an XMPPHP_Exception: " . $e->getMessage()); + die($e->getMessage()); + } + } + + /** + * Lists the IM connection socket to allow i/o master to wake + * when input comes in here as well as from the queue source. + * + * @return array of resources + */ + public function getSockets() + { + $this->connect(); + if($this->conn){ + return array($this->conn->getSocket()); + }else{ + return array(); + } + } + + /** + * Idle processing for io manager's execution loop. + * Send keepalive pings to server. + * + * Side effect: kills process on exception from XMPP library. + * + * @fixme non-dying error handling + */ + public function idle($timeout=0) + { + $now = time(); + if (empty($this->lastping) || $now - $this->lastping > self::PING_INTERVAL) { + try { + $this->send_ping(); + } catch (XMPPHP_Exception $e) { + common_log(LOG_ERR, "Got an XMPPHP_Exception: " . $e->getMessage()); + die($e->getMessage()); + } + } + } + + function connect() + { + if (!$this->conn || $this->conn->isDisconnected()) { + $resource = 'queue' . posix_getpid(); + $this->conn = new Sharing_XMPP($this->plugin->host ? + $this->plugin->host : + $this->plugin->server, + $this->plugin->port, + $this->plugin->user, + $this->plugin->password, + $this->plugin->resource, + $this->plugin->server, + $this->plugin->debug ? + true : false, + $this->plugin->debug ? + XMPPHP_Log::LEVEL_VERBOSE : null + ); + + if (!$this->conn) { + return false; + } + $this->conn->addEventHandler('message', 'handle_xmpp_message', $this); + $this->conn->addEventHandler('reconnect', 'handle_xmpp_reconnect', $this); + $this->conn->setReconnectTimeout(600); + + $this->conn->autoSubscribe(); + $this->conn->useEncryption($this->plugin->encryption); + + try { + $this->conn->connect(true); // true = persistent connection + } catch (XMPPHP_Exception $e) { + common_log(LOG_ERR, $e->getMessage()); + return false; + } + + $this->conn->processUntil('session_start'); + $this->send_presence(_m('Send me a message to post a notice'), 'available', null, 'available', 100); + } + return $this->conn; + } + + function send_ping() + { + $this->connect(); + if (!$this->conn || $this->conn->isDisconnected()) { + return false; + } + $now = time(); + if (!isset($this->pingid)) { + $this->pingid = 0; + } else { + $this->pingid++; + } + + common_log(LOG_DEBUG, "Sending ping #{$this->pingid}"); + $this->conn->send("<iq from='{" . $this->plugin->daemon_screenname() . "}' to='{$this->plugin->server}' id='ping_{$this->pingid}' type='get'><ping xmlns='urn:xmpp:ping'/></iq>"); + $this->lastping = $now; + return true; + } + + function handle_xmpp_message(&$pl) + { + $this->plugin->enqueue_incoming_raw($pl); + return true; + } + + /** + * Callback for Jabber reconnect event + * @param $pl + */ + function handle_xmpp_reconnect(&$pl) + { + common_log(LOG_NOTICE, 'XMPP reconnected'); + + $this->conn->processUntil('session_start'); + $this->send_presence(_m('Send me a message to post a notice'), 'available', null, 'available', 100); + } + + /** + * sends a presence stanza on the XMPP network + * + * @param string $status current status, free-form string + * @param string $show structured status value + * @param string $to recipient of presence, null for general + * @param string $type type of status message, related to $show + * @param int $priority priority of the presence + * + * @return boolean success value + */ + + function send_presence($status, $show='available', $to=null, + $type = 'available', $priority=null) + { + $this->connect(); + if (!$this->conn || $this->conn->isDisconnected()) { + return false; + } + $this->conn->presence($status, $show, $to, $type, $priority); + return true; + } + + /** + * sends a "special" presence stanza on the XMPP network + * + * @param string $type Type of presence + * @param string $to JID to send presence to + * @param string $show show value for presence + * @param string $status status value for presence + * + * @return boolean success flag + * + * @see send_presence() + */ + + function special_presence($type, $to=null, $show=null, $status=null) + { + // FIXME: why use this instead of send_presence()? + $this->connect(); + if (!$this->conn || $this->conn->isDisconnected()) { + return false; + } + + $to = htmlspecialchars($to); + $status = htmlspecialchars($status); + + $out = "<presence"; + if ($to) { + $out .= " to='$to'"; + } + if ($type) { + $out .= " type='$type'"; + } + if ($show == 'available' and !$status) { + $out .= "/>"; + } else { + $out .= ">"; + if ($show && ($show != 'available')) { + $out .= "<show>$show</show>"; + } + if ($status) { + $out .= "<status>$status</status>"; + } + $out .= "</presence>"; + } + $this->conn->send($out); + return true; + } +} |