3 * StatusNet, the distributed open-source microblogging tool
5 * Superclass for plugins that do instant messaging
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
26 * @link http://status.net/
29 if (!defined('STATUSNET') && !defined('LACONICA')) {
34 * Superclass for plugins that do authentication
36 * Implementations will likely want to override onStartIoManagerClasses() so that their
41 * @author Craig Andrews <candrews@integralblue.com>
42 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
43 * @link http://status.net/
45 abstract class ImPlugin extends Plugin
47 //name of this IM transport
48 public $transport = null;
49 //list of screennames that should get all public notices
50 public $public = array();
52 protected $requires_cli = true;
55 * normalize a screenname for comparison
57 * @param string $screenname screenname to normalize
59 * @return string an equivalent screenname in normalized form
61 abstract function normalize($screenname);
64 * validate (ensure the validity of) a screenname
66 * @param string $screenname screenname to validate
70 abstract function validate($screenname);
73 * get the internationalized/translated display name of this IM service
77 abstract function getDisplayName();
80 * send a single notice to a given screenname
81 * The implementation should put raw data, ready to send, into the outgoing
82 * queue using enqueueOutgoingRaw()
84 * @param string $screenname screenname to send to
85 * @param Notice $notice notice to send
87 * @return boolean success value
89 function sendNotice($screenname, Notice $notice)
91 return $this->sendMessage($screenname, $this->formatNotice($notice));
95 * send a message (text) to a given screenname
96 * The implementation should put raw data, ready to send, into the outgoing
97 * queue using enqueueOutgoingRaw()
99 * @param string $screenname screenname to send to
100 * @param Notice $body text to send
102 * @return boolean success value
104 abstract function sendMessage($screenname, $body);
107 * receive a raw message
108 * Raw IM data is taken from the incoming queue, and passed to this function.
109 * It should parse the raw message and call handleIncoming()
111 * Returning false may CAUSE REPROCESSING OF THE QUEUE ITEM, and should
112 * be used for temporary failures only. For permanent failures such as
113 * unrecognized addresses, return true to indicate your processing has
116 * @param object $data raw IM data
118 * @return boolean true if processing completed, false for temporary failures
120 abstract function receiveRawMessage($data);
123 * get the screenname of the daemon that sends and receives message for this service
125 * @return string screenname of this plugin
127 abstract function daemonScreenname();
129 //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - MISC ========================\
132 * Put raw message data (ready to send) into the outgoing queue
134 * @param object $data
136 function enqueueOutgoingRaw($data)
138 $qm = QueueManager::get();
139 $qm->enqueue($data, $this->transport . '-out');
143 * Put raw message data (received, ready to be processed) into the incoming queue
145 * @param object $data
147 function enqueueIncomingRaw($data)
149 $qm = QueueManager::get();
150 $qm->enqueue($data, $this->transport . '-in');
154 * given a screenname, get the corresponding user
156 * @param string $screenname
160 function getUser($screenname)
162 $user_im_prefs = $this->getUserImPrefsFromScreenname($screenname);
164 $user = User::getKV('id', $user_im_prefs->user_id);
165 $user_im_prefs->free();
173 * given a screenname, get the User_im_prefs object for this transport
175 * @param string $screenname
177 * @return User_im_prefs user_im_prefs
179 function getUserImPrefsFromScreenname($screenname)
181 $user_im_prefs = User_im_prefs::pkeyGet(
182 array('transport' => $this->transport,
183 'screenname' => $this->normalize($screenname)));
184 if ($user_im_prefs) {
185 return $user_im_prefs;
192 * given a User, get their screenname
196 * @return string screenname of that user
198 function getScreenname($user)
200 $user_im_prefs = $this->getUserImPrefsFromUser($user);
201 if ($user_im_prefs) {
202 return $user_im_prefs->screenname;
209 * given a User, get their User_im_prefs
213 * @return User_im_prefs user_im_prefs of that user
215 function getUserImPrefsFromUser($user)
217 $user_im_prefs = User_im_prefs::pkeyGet(
218 array('transport' => $this->transport,
219 'user_id' => $user->id));
221 return $user_im_prefs;
226 //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - SENDING ========================\
228 * Send a message to a given screenname from the site
230 * @param string $screenname screenname to send the message to
231 * @param string $msg message contents to send
233 * @param boolean success
235 protected function sendFromSite($screenname, $msg)
237 $text = '['.common_config('site', 'name') . '] ' . $msg;
238 $this->sendMessage($screenname, $text);
242 * Send a confirmation code to a user
244 * @param string $screenname screenname sending to
245 * @param string $code the confirmation code
246 * @param Profile $target For whom the code is valid for
248 * @return boolean success value
250 function sendConfirmationCode($screenname, $code, Profile $target)
252 // TRANS: Body text for confirmation code e-mail.
253 // TRANS: %1$s is a user nickname, %2$s is the StatusNet sitename,
254 // TRANS: %3$s is the display name of an IM plugin.
255 $body = sprintf(_('User "%1$s" on %2$s has said that your %3$s screenname belongs to them. ' .
256 'If that is true, you can confirm by clicking on this URL: ' .
258 ' . (If you cannot click it, copy-and-paste it into the ' .
259 'address bar of your browser). If that user is not you, ' .
260 'or if you did not request this confirmation, just ignore this message.'),
261 $target->getNickname(), common_config('site', 'name'), $this->getDisplayName(), common_local_url('confirmaddress', null, array('code' => $code)));
263 return $this->sendMessage($screenname, $body);
267 * send a notice to all public listeners
269 * For notices that are generated on the local system (by users), we can optionally
270 * forward them to remote listeners by XMPP.
272 * @param Notice $notice notice to broadcast
274 * @return boolean success flag
277 function publicNotice($notice)
279 // Now, users who want everything
281 // FIXME PRIV don't send out private messages here
282 // XXX: should we send out non-local messages if public,localonly
283 // = false? I think not
285 foreach ($this->public as $screenname) {
287 'Sending notice ' . $notice->id .
288 ' to public listener ' . $screenname,
290 $this->sendNotice($screenname, $notice);
297 * broadcast a notice to all subscribers and reply recipients
299 * This function will send a notice to all subscribers on the local server
300 * who have IM addresses, and have IM notification enabled, and
301 * have this subscription enabled for IM. It also sends the notice to
302 * all recipients of @-replies who have IM addresses and IM notification
303 * enabled. This is really the heart of IM distribution in StatusNet.
305 * @param Notice $notice The notice to broadcast
307 * @return boolean success flag
310 function broadcastNotice($notice)
312 $ni = $notice->whoGets();
314 foreach ($ni as $user_id => $reason) {
315 $user = User::getKV($user_id);
317 // either not a local user, or just not found
320 $user_im_prefs = $this->getUserImPrefsFromUser($user);
321 if(!$user_im_prefs || !$user_im_prefs->notify){
326 case NOTICE_INBOX_SOURCE_REPLY:
327 if (!$user_im_prefs->replies) {
331 case NOTICE_INBOX_SOURCE_SUB:
332 $sub = Subscription::pkeyGet(array('subscriber' => $user->id,
333 'subscribed' => $notice->profile_id));
334 if (empty($sub) || !$sub->jabber) {
338 case NOTICE_INBOX_SOURCE_GROUP:
341 // TRANS: Exception thrown when trying to deliver a notice to an unknown inbox.
342 // TRANS: %d is the unknown inbox ID (number).
343 throw new Exception(sprintf(_('Unknown inbox source %d.'), $reason));
347 'Sending notice ' . $notice->id . ' to ' . $user_im_prefs->screenname,
349 $this->sendNotice($user_im_prefs->screenname, $notice);
350 $user_im_prefs->free();
357 * makes a plain-text formatted version of a notice, suitable for IM distribution
359 * @param Notice $notice notice being sent
361 * @return string plain-text version of the notice, with user nickname prefixed
364 protected function formatNotice(Notice $notice)
366 $profile = $notice->getProfile();
367 $nicknames = $profile->getNickname();
370 $parent = $notice->getParent();
371 $orig_profile = $parent->getProfile();
372 $nicknames = sprintf('%1$s => %2$s', $profile->getNickname(), $orig_profile->getNickname());
373 } catch (NoParentNoticeException $e) {
374 // Not a reply, no parent notice stored
375 } catch (NoResultException $e) {
376 // Parent notice was probably deleted
379 return sprintf('%1$s: %2$s [%3$u]', $nicknames, $notice->content, $notice->id);
381 //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - RECEIVING ========================\
384 * Attempt to handle a message as a command
385 * @param User $user user the message is from
386 * @param string $body message text
387 * @return boolean true if the message was a command and was executed, false if it was not a command
389 protected function handleCommand($user, $body)
391 $inter = new CommandInterpreter();
392 $cmd = $inter->handle_command($user, $body);
394 $chan = new IMChannel($this);
395 $cmd->execute($chan);
402 * Is some text an autoreply message?
403 * @param string $txt message text
404 * @return boolean true if autoreply
406 protected function isAutoreply($txt)
408 if (preg_match('/[\[\(]?[Aa]uto[-\s]?[Rr]e(ply|sponse)[\]\)]/', $txt)) {
410 } else if (preg_match('/^System: Message wasn\'t delivered. Offline storage size was exceeded.$/', $txt)) {
418 * Is some text an OTR message?
419 * @param string $txt message text
420 * @return boolean true if OTR
422 protected function isOtr($txt)
424 if (preg_match('/^\?OTR/', $txt)) {
432 * Helper for handling incoming messages
433 * Your incoming message handler will probably want to call this function
435 * @param string $from screenname the message was sent from
436 * @param string $message message contents
438 * @param boolean success
440 protected function handleIncoming($from, $notice_text)
442 $user = $this->getUser($from);
443 // For common_current_user to work
448 $this->sendFromSite($from, 'Unknown user; go to ' .
449 common_local_url('imsettings') .
450 ' to add your address to your account');
451 common_log(LOG_WARNING, 'Message from unknown user ' . $from);
454 if ($this->handleCommand($user, $notice_text)) {
455 common_log(LOG_INFO, "Command message by $from handled.");
457 } else if ($this->isAutoreply($notice_text)) {
458 common_log(LOG_INFO, 'Ignoring auto reply from ' . $from);
460 } else if ($this->isOtr($notice_text)) {
461 common_log(LOG_INFO, 'Ignoring OTR from ' . $from);
465 common_log(LOG_INFO, 'Posting a notice from ' . $user->nickname);
467 $this->addNotice($from, $user, $notice_text);
477 * Helper for handling incoming messages
478 * Your incoming message handler will probably want to call this function
480 * @param string $from screenname the message was sent from
481 * @param string $message message contents
483 * @param boolean success
485 protected function addNotice($screenname, $user, $body)
487 $body = trim(strip_tags($body));
488 $content_shortened = common_shorten_links($body);
489 if (Notice::contentTooLong($content_shortened)) {
490 $this->sendFromSite($screenname,
491 // TRANS: Message given when a status is too long. %1$s is the maximum number of characters,
492 // TRANS: %2$s is the number of characters sent (used for plural).
493 sprintf(_m('Message too long - maximum is %1$d character, you sent %2$d.',
494 'Message too long - maximum is %1$d characters, you sent %2$d.',
495 Notice::maxContent()),
496 Notice::maxContent(),
497 mb_strlen($content_shortened)));
502 $notice = Notice::saveNew($user->id, $content_shortened, $this->transport);
503 } catch (Exception $e) {
504 common_log(LOG_ERR, $e->getMessage());
505 $this->sendFromSite($from, $e->getMessage());
510 'Added notice ' . $notice->id . ' from user ' . $user->nickname);
515 //========================EVENT HANDLERS========================\
518 * Register notice queue handler
520 * @param QueueManager $manager
522 * @return boolean hook return
524 function onEndInitializeQueueManager($manager)
526 // If we don't require CLI mode, or if we do and GNUSOCIAL_CLI _is_ set, then connect the transports
527 // This check is made mostly because some IM plugins can't deliver to transports unless they
528 // have continously running daemons (such as XMPP) and we can't have that over HTTP requests.
529 if (!$this->requires_cli || defined('GNUSOCIAL_CLI')) {
530 $manager->connect($this->transport . '-in', new ImReceiverQueueHandler($this), 'im');
531 $manager->connect($this->transport, new ImQueueHandler($this));
532 $manager->connect($this->transport . '-out', new ImSenderQueueHandler($this), 'im');
537 function onStartImDaemonIoManagers(&$classes)
539 //$classes[] = new ImManager($this); // handles sending/receiving/pings/reconnects
543 function onStartEnqueueNotice($notice, &$transports)
545 $profile = Profile::getKV($notice->profile_id);
548 common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
549 'unknown profile ' . common_log_objstring($notice),
552 $transports[] = $this->transport;
558 function onEndShowHeadElements(Action $action)
560 if ($action instanceof ShownoticeAction) {
562 $user_im_prefs = new User_im_prefs();
563 $user_im_prefs->user_id = $action->notice->getProfile()->getID();
564 $user_im_prefs->transport = $this->transport;
566 } elseif ($action instanceof ShowstreamAction) {
568 $user_im_prefs = new User_im_prefs();
569 $user_im_prefs->user_id = $action->getTarget()->getID();
570 $user_im_prefs->transport = $this->transport;
575 function onNormalizeImScreenname($transport, &$screenname)
577 if($transport == $this->transport)
579 $screenname = $this->normalize($screenname);
584 function onValidateImScreenname($transport, $screenname, &$valid)
586 if($transport == $this->transport)
588 $valid = $this->validate($screenname);
593 function onGetImTransports(&$transports)
595 $transports[$this->transport] = array(
596 'display' => $this->getDisplayName(),
597 'daemonScreenname' => $this->daemonScreenname());
600 function onSendImConfirmationCode($transport, $screenname, $code, Profile $target)
602 if($transport == $this->transport)
604 $this->sendConfirmationCode($screenname, $code, $target);
609 function onUserDeleteRelated($user, &$tables)
611 $tables[] = 'User_im_prefs';
615 function onHaveImPlugin(&$haveImPlugin) {
616 $haveImPlugin = true; // set flag true (we're loaded, after all!)
617 return false; // stop looking
620 function initialize()
622 if( ! common_config('queue', 'enabled'))
624 // TRANS: Server exception thrown trying to initialise an IM plugin without meeting all prerequisites.
625 throw new ServerException(_('Queueing must be enabled to use IM plugins.'));
628 if(is_null($this->transport)){
629 // TRANS: Server exception thrown trying to initialise an IM plugin without a transport method.
630 throw new ServerException(_('Transport cannot be null.'));