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();
53 * normalize a screenname for comparison
55 * @param string $screenname screenname to normalize
57 * @return string an equivalent screenname in normalized form
59 abstract function normalize($screenname);
62 * validate (ensure the validity of) a screenname
64 * @param string $screenname screenname to validate
68 abstract function validate($screenname);
71 * get the internationalized/translated display name of this IM service
75 abstract function getDisplayName();
78 * send a single notice to a given screenname
79 * The implementation should put raw data, ready to send, into the outgoing
80 * queue using enqueueOutgoingRaw()
82 * @param string $screenname screenname to send to
83 * @param Notice $notice notice to send
85 * @return boolean success value
87 function sendNotice($screenname, $notice)
89 return $this->sendMessage($screenname, $this->formatNotice($notice));
93 * send a message (text) to a given screenname
94 * The implementation should put raw data, ready to send, into the outgoing
95 * queue using enqueueOutgoingRaw()
97 * @param string $screenname screenname to send to
98 * @param Notice $body text to send
100 * @return boolean success value
102 abstract function sendMessage($screenname, $body);
105 * receive a raw message
106 * Raw IM data is taken from the incoming queue, and passed to this function.
107 * It should parse the raw message and call handleIncoming()
109 * Returning false may CAUSE REPROCESSING OF THE QUEUE ITEM, and should
110 * be used for temporary failures only. For permanent failures such as
111 * unrecognized addresses, return true to indicate your processing has
114 * @param object $data raw IM data
116 * @return boolean true if processing completed, false for temporary failures
118 abstract function receiveRawMessage($data);
121 * get the screenname of the daemon that sends and receives message for this service
123 * @return string screenname of this plugin
125 abstract function daemonScreenname();
128 * get the microid uri of a given screenname
130 * @param string $screenname screenname
132 * @return string microid uri
134 function microiduri($screenname)
136 return $this->transport . ':' . $screenname;
138 //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - MISC ========================\
141 * Put raw message data (ready to send) into the outgoing queue
143 * @param object $data
145 function enqueueOutgoingRaw($data)
147 $qm = QueueManager::get();
148 $qm->enqueue($data, $this->transport . '-out');
152 * Put raw message data (received, ready to be processed) into the incoming queue
154 * @param object $data
156 function enqueueIncomingRaw($data)
158 $qm = QueueManager::get();
159 $qm->enqueue($data, $this->transport . '-in');
163 * given a screenname, get the corresponding user
165 * @param string $screenname
169 function getUser($screenname)
171 $user_im_prefs = $this->getUserImPrefsFromScreenname($screenname);
173 $user = User::staticGet('id', $user_im_prefs->user_id);
174 $user_im_prefs->free();
182 * given a screenname, get the User_im_prefs object for this transport
184 * @param string $screenname
186 * @return User_im_prefs user_im_prefs
188 function getUserImPrefsFromScreenname($screenname)
190 $user_im_prefs = User_im_prefs::pkeyGet(
191 array('transport' => $this->transport,
192 'screenname' => $this->normalize($screenname)));
193 if ($user_im_prefs) {
194 return $user_im_prefs;
201 * given a User, get their screenname
205 * @return string screenname of that user
207 function getScreenname($user)
209 $user_im_prefs = $this->getUserImPrefsFromUser($user);
210 if ($user_im_prefs) {
211 return $user_im_prefs->screenname;
218 * given a User, get their User_im_prefs
222 * @return User_im_prefs user_im_prefs of that user
224 function getUserImPrefsFromUser($user)
226 $user_im_prefs = User_im_prefs::pkeyGet(
227 array('transport' => $this->transport,
228 'user_id' => $user->id));
230 return $user_im_prefs;
235 //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - SENDING ========================\
237 * Send a message to a given screenname from the site
239 * @param string $screenname screenname to send the message to
240 * @param string $msg message contents to send
242 * @param boolean success
244 protected function sendFromSite($screenname, $msg)
246 $text = '['.common_config('site', 'name') . '] ' . $msg;
247 $this->sendMessage($screenname, $text);
251 * Send a confirmation code to a user
253 * @param string $screenname screenname sending to
254 * @param string $code the confirmation code
255 * @param User $user user sending to
257 * @return boolean success value
259 function sendConfirmationCode($screenname, $code, $user)
261 // @todo FIXME: parameter 4 is not being used. Should para3 and para4 be a markdown link?
262 // TRANS: Body text for confirmation code e-mail.
263 // TRANS: %1$s is a user nickname, %2$s is the StatusNet sitename,
264 // TRANS: %3$s is the display name of an IM plugin.
265 $body = sprintf(_('User "%1$s" on %2$s has said that your %3$s screenname belongs to them. ' .
266 'If that is true, you can confirm by clicking on this URL: ' .
268 ' . (If you cannot click it, copy-and-paste it into the ' .
269 'address bar of your browser). If that user is not you, ' .
270 'or if you did not request this confirmation, just ignore this message.'),
271 $user->nickname, common_config('site', 'name'), $this->getDisplayName(), common_local_url('confirmaddress', array('code' => $code)));
273 return $this->sendMessage($screenname, $body);
277 * send a notice to all public listeners
279 * For notices that are generated on the local system (by users), we can optionally
280 * forward them to remote listeners by XMPP.
282 * @param Notice $notice notice to broadcast
284 * @return boolean success flag
287 function publicNotice($notice)
289 // Now, users who want everything
291 // FIXME PRIV don't send out private messages here
292 // XXX: should we send out non-local messages if public,localonly
293 // = false? I think not
295 foreach ($this->public as $screenname) {
297 'Sending notice ' . $notice->id .
298 ' to public listener ' . $screenname,
300 $this->sendNotice($screenname, $notice);
307 * broadcast a notice to all subscribers and reply recipients
309 * This function will send a notice to all subscribers on the local server
310 * who have IM addresses, and have IM notification enabled, and
311 * have this subscription enabled for IM. It also sends the notice to
312 * all recipients of @-replies who have IM addresses and IM notification
313 * enabled. This is really the heart of IM distribution in StatusNet.
315 * @param Notice $notice The notice to broadcast
317 * @return boolean success flag
320 function broadcastNotice($notice)
322 $ni = $notice->whoGets();
324 foreach ($ni as $user_id => $reason) {
325 $user = User::staticGet($user_id);
327 // either not a local user, or just not found
330 $user_im_prefs = $this->getUserImPrefsFromUser($user);
331 if(!$user_im_prefs || !$user_im_prefs->notify){
336 case NOTICE_INBOX_SOURCE_REPLY:
337 if (!$user_im_prefs->replies) {
341 case NOTICE_INBOX_SOURCE_SUB:
342 $sub = Subscription::pkeyGet(array('subscriber' => $user->id,
343 'subscribed' => $notice->profile_id));
344 if (empty($sub) || !$sub->jabber) {
348 case NOTICE_INBOX_SOURCE_GROUP:
351 // TRANS: Exception thrown when trying to deliver a notice to an unknown inbox.
352 // TRANS: %d is the unknown inbox ID (number).
353 throw new Exception(sprintf(_('Unknown inbox source %d.'), $reason));
357 'Sending notice ' . $notice->id . ' to ' . $user_im_prefs->screenname,
359 $this->sendNotice($user_im_prefs->screenname, $notice);
360 $user_im_prefs->free();
367 * makes a plain-text formatted version of a notice, suitable for IM distribution
369 * @param Notice $notice notice being sent
371 * @return string plain-text version of the notice, with user nickname prefixed
374 function formatNotice($notice)
376 $profile = $notice->getProfile();
377 return $profile->nickname . ': ' . $notice->content . ' [' . $notice->id . ']';
379 //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - RECEIVING ========================\
382 * Attempt to handle a message as a command
383 * @param User $user user the message is from
384 * @param string $body message text
385 * @return boolean true if the message was a command and was executed, false if it was not a command
387 protected function handleCommand($user, $body)
389 $inter = new CommandInterpreter();
390 $cmd = $inter->handle_command($user, $body);
392 $chan = new IMChannel($this);
393 $cmd->execute($chan);
401 * Is some text an autoreply message?
402 * @param string $txt message text
403 * @return boolean true if autoreply
405 protected function isAutoreply($txt)
407 if (preg_match('/[\[\(]?[Aa]uto[-\s]?[Rr]e(ply|sponse)[\]\)]/', $txt)) {
409 } else if (preg_match('/^System: Message wasn\'t delivered. Offline storage size was exceeded.$/', $txt)) {
417 * Is some text an OTR message?
418 * @param string $txt message text
419 * @return boolean true if OTR
421 protected function isOtr($txt)
423 if (preg_match('/^\?OTR/', $txt)) {
431 * Helper for handling incoming messages
432 * Your incoming message handler will probably want to call this function
434 * @param string $from screenname the message was sent from
435 * @param string $message message contents
437 * @param boolean success
439 protected function handleIncoming($from, $notice_text)
441 $user = $this->getUser($from);
442 // For common_current_user to work
447 $this->sendFromSite($from, 'Unknown user; go to ' .
448 common_local_url('imsettings') .
449 ' to add your address to your account');
450 common_log(LOG_WARNING, 'Message from unknown user ' . $from);
453 if ($this->handleCommand($user, $notice_text)) {
454 common_log(LOG_INFO, "Command message by $from handled.");
456 } else if ($this->isAutoreply($notice_text)) {
457 common_log(LOG_INFO, 'Ignoring auto reply from ' . $from);
459 } else if ($this->isOtr($notice_text)) {
460 common_log(LOG_INFO, 'Ignoring OTR from ' . $from);
464 common_log(LOG_INFO, 'Posting a notice from ' . $user->nickname);
466 $this->addNotice($from, $user, $notice_text);
476 * Helper for handling incoming messages
477 * Your incoming message handler will probably want to call this function
479 * @param string $from screenname the message was sent from
480 * @param string $message message contents
482 * @param boolean success
484 protected function addNotice($screenname, $user, $body)
486 $body = trim(strip_tags($body));
487 $content_shortened = common_shorten_links($body);
488 if (Notice::contentTooLong($content_shortened)) {
489 $this->sendFromSite($screenname,
490 // TRANS: Message given when a status is too long. %1$s is the maximum number of characters,
491 // TRANS: %2$s is the number of characters sent (used for plural).
492 sprintf(_m('Message too long - maximum is %1$d character, you sent %2$d.',
493 'Message too long - maximum is %1$d characters, you sent %2$d.',
494 Notice::maxContent()),
495 Notice::maxContent(),
496 mb_strlen($content_shortened)));
501 $notice = Notice::saveNew($user->id, $content_shortened, $this->transport);
502 } catch (Exception $e) {
503 common_log(LOG_ERR, $e->getMessage());
504 $this->sendFromSite($from, $e->getMessage());
509 'Added notice ' . $notice->id . ' from user ' . $user->nickname);
514 //========================EVENT HANDLERS========================\
517 * Register notice queue handler
519 * @param QueueManager $manager
521 * @return boolean hook return
523 function onEndInitializeQueueManager($manager)
525 $manager->connect($this->transport . '-in', new ImReceiverQueueHandler($this), 'im');
526 $manager->connect($this->transport, new ImQueueHandler($this));
527 $manager->connect($this->transport . '-out', new ImSenderQueueHandler($this), 'im');
531 function onStartImDaemonIoManagers(&$classes)
533 //$classes[] = new ImManager($this); // handles sending/receiving/pings/reconnects
537 function onStartEnqueueNotice($notice, &$transports)
539 $profile = Profile::staticGet($notice->profile_id);
542 common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
543 'unknown profile ' . common_log_objstring($notice),
546 $transports[] = $this->transport;
552 function onEndShowHeadElements($action)
554 $aname = $action->trimmed('action');
556 if ($aname == 'shownotice') {
558 $user_im_prefs = new User_im_prefs();
559 $user_im_prefs->user_id = $action->profile->id;
560 $user_im_prefs->transport = $this->transport;
562 if ($user_im_prefs->find() && $user_im_prefs->fetch() && $user_im_prefs->microid && $action->notice->uri) {
563 $id = new Microid($this->microiduri($user_im_prefs->screenname),
564 $action->notice->uri);
565 $action->element('meta', array('name' => 'microid',
566 'content' => $id->toString()));
569 } else if ($aname == 'showstream') {
571 $user_im_prefs = new User_im_prefs();
572 $user_im_prefs->user_id = $action->user->id;
573 $user_im_prefs->transport = $this->transport;
575 if ($user_im_prefs->find() && $user_im_prefs->fetch() && $user_im_prefs->microid && $action->profile->profileurl) {
576 $id = new Microid($this->microiduri($user_im_prefs->screenname),
578 $action->element('meta', array('name' => 'microid',
579 'content' => $id->toString()));
584 function onNormalizeImScreenname($transport, &$screenname)
586 if($transport == $this->transport)
588 $screenname = $this->normalize($screenname);
593 function onValidateImScreenname($transport, $screenname, &$valid)
595 if($transport == $this->transport)
597 $valid = $this->validate($screenname);
602 function onGetImTransports(&$transports)
604 $transports[$this->transport] = array(
605 'display' => $this->getDisplayName(),
606 'daemonScreenname' => $this->daemonScreenname());
609 function onSendImConfirmationCode($transport, $screenname, $code, $user)
611 if($transport == $this->transport)
613 $this->sendConfirmationCode($screenname, $code, $user);
618 function onUserDeleteRelated($user, &$tables)
620 $tables[] = 'User_im_prefs';
624 function initialize()
626 if( ! common_config('queue', 'enabled'))
628 // TRANS: Server exception thrown trying to initialise an IM plugin without meeting all prerequisites.
629 throw new ServerException(_('Queueing must be enabled to use IM plugins.'));
632 if(is_null($this->transport)){
633 // TRANS: Server exception thrown trying to initialise an IM plugin without a transport method.
634 throw new ServerException(_('Transport cannot be null.'));