implugin.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Superclass for plugins that do instant messaging
  6. *
  7. * PHP version 5
  8. *
  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.
  13. *
  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.
  18. *
  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/>.
  21. *
  22. * @category Plugin
  23. * @package StatusNet
  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/
  27. */
  28. if (!defined('STATUSNET') && !defined('LACONICA')) {
  29. exit(1);
  30. }
  31. /**
  32. * Superclass for plugins that do authentication
  33. *
  34. * Implementations will likely want to override onStartIoManagerClasses() so that their
  35. * IO manager is used
  36. *
  37. * @category Plugin
  38. * @package StatusNet
  39. * @author Craig Andrews <candrews@integralblue.com>
  40. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  41. * @link http://status.net/
  42. */
  43. abstract class ImPlugin extends Plugin
  44. {
  45. //name of this IM transport
  46. public $transport = null;
  47. //list of screennames that should get all public notices
  48. public $public = array();
  49. protected $requires_cli = true;
  50. /**
  51. * normalize a screenname for comparison
  52. *
  53. * @param string $screenname screenname to normalize
  54. *
  55. * @return string an equivalent screenname in normalized form
  56. */
  57. abstract function normalize($screenname);
  58. /**
  59. * validate (ensure the validity of) a screenname
  60. *
  61. * @param string $screenname screenname to validate
  62. *
  63. * @return boolean
  64. */
  65. abstract function validate($screenname);
  66. /**
  67. * get the internationalized/translated display name of this IM service
  68. *
  69. * @return string
  70. */
  71. abstract function getDisplayName();
  72. /**
  73. * send a single notice to a given screenname
  74. * The implementation should put raw data, ready to send, into the outgoing
  75. * queue using enqueueOutgoingRaw()
  76. *
  77. * @param string $screenname screenname to send to
  78. * @param Notice $notice notice to send
  79. *
  80. * @return boolean success value
  81. */
  82. function sendNotice($screenname, Notice $notice)
  83. {
  84. return $this->sendMessage($screenname, $this->formatNotice($notice));
  85. }
  86. /**
  87. * send a message (text) to a given screenname
  88. * The implementation should put raw data, ready to send, into the outgoing
  89. * queue using enqueueOutgoingRaw()
  90. *
  91. * @param string $screenname screenname to send to
  92. * @param Notice $body text to send
  93. *
  94. * @return boolean success value
  95. */
  96. abstract function sendMessage($screenname, $body);
  97. /**
  98. * receive a raw message
  99. * Raw IM data is taken from the incoming queue, and passed to this function.
  100. * It should parse the raw message and call handleIncoming()
  101. *
  102. * Returning false may CAUSE REPROCESSING OF THE QUEUE ITEM, and should
  103. * be used for temporary failures only. For permanent failures such as
  104. * unrecognized addresses, return true to indicate your processing has
  105. * completed.
  106. *
  107. * @param object $data raw IM data
  108. *
  109. * @return boolean true if processing completed, false for temporary failures
  110. */
  111. abstract function receiveRawMessage($data);
  112. /**
  113. * get the screenname of the daemon that sends and receives message for this service
  114. *
  115. * @return string screenname of this plugin
  116. */
  117. abstract function daemonScreenname();
  118. /**
  119. * get the microid uri of a given screenname
  120. *
  121. * @param string $screenname screenname
  122. *
  123. * @return string microid uri
  124. */
  125. function microiduri($screenname)
  126. {
  127. return $this->transport . ':' . $screenname;
  128. }
  129. //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - MISC ========================\
  130. /**
  131. * Put raw message data (ready to send) into the outgoing queue
  132. *
  133. * @param object $data
  134. */
  135. function enqueueOutgoingRaw($data)
  136. {
  137. $qm = QueueManager::get();
  138. $qm->enqueue($data, $this->transport . '-out');
  139. }
  140. /**
  141. * Put raw message data (received, ready to be processed) into the incoming queue
  142. *
  143. * @param object $data
  144. */
  145. function enqueueIncomingRaw($data)
  146. {
  147. $qm = QueueManager::get();
  148. $qm->enqueue($data, $this->transport . '-in');
  149. }
  150. /**
  151. * given a screenname, get the corresponding user
  152. *
  153. * @param string $screenname
  154. *
  155. * @return User user
  156. */
  157. function getUser($screenname)
  158. {
  159. $user_im_prefs = $this->getUserImPrefsFromScreenname($screenname);
  160. if($user_im_prefs){
  161. $user = User::getKV('id', $user_im_prefs->user_id);
  162. $user_im_prefs->free();
  163. return $user;
  164. }else{
  165. return false;
  166. }
  167. }
  168. /**
  169. * given a screenname, get the User_im_prefs object for this transport
  170. *
  171. * @param string $screenname
  172. *
  173. * @return User_im_prefs user_im_prefs
  174. */
  175. function getUserImPrefsFromScreenname($screenname)
  176. {
  177. $user_im_prefs = User_im_prefs::pkeyGet(
  178. array('transport' => $this->transport,
  179. 'screenname' => $this->normalize($screenname)));
  180. if ($user_im_prefs) {
  181. return $user_im_prefs;
  182. } else {
  183. return false;
  184. }
  185. }
  186. /**
  187. * given a User, get their screenname
  188. *
  189. * @param User $user
  190. *
  191. * @return string screenname of that user
  192. */
  193. function getScreenname($user)
  194. {
  195. $user_im_prefs = $this->getUserImPrefsFromUser($user);
  196. if ($user_im_prefs) {
  197. return $user_im_prefs->screenname;
  198. } else {
  199. return false;
  200. }
  201. }
  202. /**
  203. * given a User, get their User_im_prefs
  204. *
  205. * @param User $user
  206. *
  207. * @return User_im_prefs user_im_prefs of that user
  208. */
  209. function getUserImPrefsFromUser($user)
  210. {
  211. $user_im_prefs = User_im_prefs::pkeyGet(
  212. array('transport' => $this->transport,
  213. 'user_id' => $user->id));
  214. if ($user_im_prefs){
  215. return $user_im_prefs;
  216. } else {
  217. return false;
  218. }
  219. }
  220. //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - SENDING ========================\
  221. /**
  222. * Send a message to a given screenname from the site
  223. *
  224. * @param string $screenname screenname to send the message to
  225. * @param string $msg message contents to send
  226. *
  227. * @param boolean success
  228. */
  229. protected function sendFromSite($screenname, $msg)
  230. {
  231. $text = '['.common_config('site', 'name') . '] ' . $msg;
  232. $this->sendMessage($screenname, $text);
  233. }
  234. /**
  235. * Send a confirmation code to a user
  236. *
  237. * @param string $screenname screenname sending to
  238. * @param string $code the confirmation code
  239. * @param User $user user sending to
  240. *
  241. * @return boolean success value
  242. */
  243. function sendConfirmationCode($screenname, $code, $user)
  244. {
  245. // TRANS: Body text for confirmation code e-mail.
  246. // TRANS: %1$s is a user nickname, %2$s is the StatusNet sitename,
  247. // TRANS: %3$s is the display name of an IM plugin.
  248. $body = sprintf(_('User "%1$s" on %2$s has said that your %3$s screenname belongs to them. ' .
  249. 'If that is true, you can confirm by clicking on this URL: ' .
  250. '%4$s' .
  251. ' . (If you cannot click it, copy-and-paste it into the ' .
  252. 'address bar of your browser). If that user is not you, ' .
  253. 'or if you did not request this confirmation, just ignore this message.'),
  254. $user->nickname, common_config('site', 'name'), $this->getDisplayName(), common_local_url('confirmaddress', null, array('code' => $code)));
  255. return $this->sendMessage($screenname, $body);
  256. }
  257. /**
  258. * send a notice to all public listeners
  259. *
  260. * For notices that are generated on the local system (by users), we can optionally
  261. * forward them to remote listeners by XMPP.
  262. *
  263. * @param Notice $notice notice to broadcast
  264. *
  265. * @return boolean success flag
  266. */
  267. function publicNotice($notice)
  268. {
  269. // Now, users who want everything
  270. // FIXME PRIV don't send out private messages here
  271. // XXX: should we send out non-local messages if public,localonly
  272. // = false? I think not
  273. foreach ($this->public as $screenname) {
  274. common_log(LOG_INFO,
  275. 'Sending notice ' . $notice->id .
  276. ' to public listener ' . $screenname,
  277. __FILE__);
  278. $this->sendNotice($screenname, $notice);
  279. }
  280. return true;
  281. }
  282. /**
  283. * broadcast a notice to all subscribers and reply recipients
  284. *
  285. * This function will send a notice to all subscribers on the local server
  286. * who have IM addresses, and have IM notification enabled, and
  287. * have this subscription enabled for IM. It also sends the notice to
  288. * all recipients of @-replies who have IM addresses and IM notification
  289. * enabled. This is really the heart of IM distribution in StatusNet.
  290. *
  291. * @param Notice $notice The notice to broadcast
  292. *
  293. * @return boolean success flag
  294. */
  295. function broadcastNotice($notice)
  296. {
  297. $ni = $notice->whoGets();
  298. foreach ($ni as $user_id => $reason) {
  299. $user = User::getKV($user_id);
  300. if (empty($user)) {
  301. // either not a local user, or just not found
  302. continue;
  303. }
  304. $user_im_prefs = $this->getUserImPrefsFromUser($user);
  305. if(!$user_im_prefs || !$user_im_prefs->notify){
  306. continue;
  307. }
  308. switch ($reason) {
  309. case NOTICE_INBOX_SOURCE_REPLY:
  310. if (!$user_im_prefs->replies) {
  311. continue 2;
  312. }
  313. break;
  314. case NOTICE_INBOX_SOURCE_SUB:
  315. $sub = Subscription::pkeyGet(array('subscriber' => $user->id,
  316. 'subscribed' => $notice->profile_id));
  317. if (empty($sub) || !$sub->jabber) {
  318. continue 2;
  319. }
  320. break;
  321. case NOTICE_INBOX_SOURCE_GROUP:
  322. break;
  323. default:
  324. // TRANS: Exception thrown when trying to deliver a notice to an unknown inbox.
  325. // TRANS: %d is the unknown inbox ID (number).
  326. throw new Exception(sprintf(_('Unknown inbox source %d.'), $reason));
  327. }
  328. common_log(LOG_INFO,
  329. 'Sending notice ' . $notice->id . ' to ' . $user_im_prefs->screenname,
  330. __FILE__);
  331. $this->sendNotice($user_im_prefs->screenname, $notice);
  332. $user_im_prefs->free();
  333. }
  334. return true;
  335. }
  336. /**
  337. * makes a plain-text formatted version of a notice, suitable for IM distribution
  338. *
  339. * @param Notice $notice notice being sent
  340. *
  341. * @return string plain-text version of the notice, with user nickname prefixed
  342. */
  343. protected function formatNotice(Notice $notice)
  344. {
  345. $profile = $notice->getProfile();
  346. try {
  347. $parent = $notice->getParent();
  348. $orig_profile = $parent->getProfile();
  349. $nicknames = sprintf('%1$s => %2$s', $profile->nickname, $orig_profile->nickname);
  350. } catch (Exception $e) {
  351. $nicknames = $profile->nickname;
  352. }
  353. return sprintf('%1$s: %2$s [%3$u]', $nicknames, $notice->content, $notice->id);
  354. }
  355. //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - RECEIVING ========================\
  356. /**
  357. * Attempt to handle a message as a command
  358. * @param User $user user the message is from
  359. * @param string $body message text
  360. * @return boolean true if the message was a command and was executed, false if it was not a command
  361. */
  362. protected function handleCommand($user, $body)
  363. {
  364. $inter = new CommandInterpreter();
  365. $cmd = $inter->handle_command($user, $body);
  366. if ($cmd) {
  367. $chan = new IMChannel($this);
  368. $cmd->execute($chan);
  369. return true;
  370. } else {
  371. return false;
  372. }
  373. }
  374. /**
  375. * Is some text an autoreply message?
  376. * @param string $txt message text
  377. * @return boolean true if autoreply
  378. */
  379. protected function isAutoreply($txt)
  380. {
  381. if (preg_match('/[\[\(]?[Aa]uto[-\s]?[Rr]e(ply|sponse)[\]\)]/', $txt)) {
  382. return true;
  383. } else if (preg_match('/^System: Message wasn\'t delivered. Offline storage size was exceeded.$/', $txt)) {
  384. return true;
  385. } else {
  386. return false;
  387. }
  388. }
  389. /**
  390. * Is some text an OTR message?
  391. * @param string $txt message text
  392. * @return boolean true if OTR
  393. */
  394. protected function isOtr($txt)
  395. {
  396. if (preg_match('/^\?OTR/', $txt)) {
  397. return true;
  398. } else {
  399. return false;
  400. }
  401. }
  402. /**
  403. * Helper for handling incoming messages
  404. * Your incoming message handler will probably want to call this function
  405. *
  406. * @param string $from screenname the message was sent from
  407. * @param string $message message contents
  408. *
  409. * @param boolean success
  410. */
  411. protected function handleIncoming($from, $notice_text)
  412. {
  413. $user = $this->getUser($from);
  414. // For common_current_user to work
  415. global $_cur;
  416. $_cur = $user;
  417. if (!$user) {
  418. $this->sendFromSite($from, 'Unknown user; go to ' .
  419. common_local_url('imsettings') .
  420. ' to add your address to your account');
  421. common_log(LOG_WARNING, 'Message from unknown user ' . $from);
  422. return;
  423. }
  424. if ($this->handleCommand($user, $notice_text)) {
  425. common_log(LOG_INFO, "Command message by $from handled.");
  426. return;
  427. } else if ($this->isAutoreply($notice_text)) {
  428. common_log(LOG_INFO, 'Ignoring auto reply from ' . $from);
  429. return;
  430. } else if ($this->isOtr($notice_text)) {
  431. common_log(LOG_INFO, 'Ignoring OTR from ' . $from);
  432. return;
  433. } else {
  434. common_log(LOG_INFO, 'Posting a notice from ' . $user->nickname);
  435. $this->addNotice($from, $user, $notice_text);
  436. }
  437. $user->free();
  438. unset($user);
  439. unset($_cur);
  440. unset($message);
  441. }
  442. /**
  443. * Helper for handling incoming messages
  444. * Your incoming message handler will probably want to call this function
  445. *
  446. * @param string $from screenname the message was sent from
  447. * @param string $message message contents
  448. *
  449. * @param boolean success
  450. */
  451. protected function addNotice($screenname, $user, $body)
  452. {
  453. $body = trim(strip_tags($body));
  454. $content_shortened = common_shorten_links($body);
  455. if (Notice::contentTooLong($content_shortened)) {
  456. $this->sendFromSite($screenname,
  457. // TRANS: Message given when a status is too long. %1$s is the maximum number of characters,
  458. // TRANS: %2$s is the number of characters sent (used for plural).
  459. sprintf(_m('Message too long - maximum is %1$d character, you sent %2$d.',
  460. 'Message too long - maximum is %1$d characters, you sent %2$d.',
  461. Notice::maxContent()),
  462. Notice::maxContent(),
  463. mb_strlen($content_shortened)));
  464. return;
  465. }
  466. try {
  467. $notice = Notice::saveNew($user->id, $content_shortened, $this->transport);
  468. } catch (Exception $e) {
  469. common_log(LOG_ERR, $e->getMessage());
  470. $this->sendFromSite($from, $e->getMessage());
  471. return;
  472. }
  473. common_log(LOG_INFO,
  474. 'Added notice ' . $notice->id . ' from user ' . $user->nickname);
  475. $notice->free();
  476. unset($notice);
  477. }
  478. //========================EVENT HANDLERS========================\
  479. /**
  480. * Register notice queue handler
  481. *
  482. * @param QueueManager $manager
  483. *
  484. * @return boolean hook return
  485. */
  486. function onEndInitializeQueueManager($manager)
  487. {
  488. // If we don't require CLI mode, or if we do and GNUSOCIAL_CLI _is_ set, then connect the transports
  489. // This check is made mostly because some IM plugins can't deliver to transports unless they
  490. // have continously running daemons (such as XMPP) and we can't have that over HTTP requests.
  491. if (!$this->requires_cli || defined('GNUSOCIAL_CLI')) {
  492. $manager->connect($this->transport . '-in', new ImReceiverQueueHandler($this), 'im');
  493. $manager->connect($this->transport, new ImQueueHandler($this));
  494. $manager->connect($this->transport . '-out', new ImSenderQueueHandler($this), 'im');
  495. }
  496. return true;
  497. }
  498. function onStartImDaemonIoManagers(&$classes)
  499. {
  500. //$classes[] = new ImManager($this); // handles sending/receiving/pings/reconnects
  501. return true;
  502. }
  503. function onStartEnqueueNotice($notice, &$transports)
  504. {
  505. $profile = Profile::getKV($notice->profile_id);
  506. if (!$profile) {
  507. common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
  508. 'unknown profile ' . common_log_objstring($notice),
  509. __FILE__);
  510. }else{
  511. $transports[] = $this->transport;
  512. }
  513. return true;
  514. }
  515. function onEndShowHeadElements($action)
  516. {
  517. $aname = $action->trimmed('action');
  518. if ($aname == 'shownotice') {
  519. $user_im_prefs = new User_im_prefs();
  520. $user_im_prefs->user_id = $action->profile->id;
  521. $user_im_prefs->transport = $this->transport;
  522. if ($user_im_prefs->find() && $user_im_prefs->fetch() && $user_im_prefs->microid && $action->notice->uri) {
  523. $id = new Microid($this->microiduri($user_im_prefs->screenname),
  524. $action->notice->uri);
  525. $action->element('meta', array('name' => 'microid',
  526. 'content' => $id->toString()));
  527. }
  528. } else if ($aname == 'showstream') {
  529. $user_im_prefs = new User_im_prefs();
  530. $user_im_prefs->user_id = $action->user->id;
  531. $user_im_prefs->transport = $this->transport;
  532. if ($user_im_prefs->find() && $user_im_prefs->fetch() && $user_im_prefs->microid && $action->profile->profileurl) {
  533. $id = new Microid($this->microiduri($user_im_prefs->screenname),
  534. $action->selfUrl());
  535. $action->element('meta', array('name' => 'microid',
  536. 'content' => $id->toString()));
  537. }
  538. }
  539. }
  540. function onNormalizeImScreenname($transport, &$screenname)
  541. {
  542. if($transport == $this->transport)
  543. {
  544. $screenname = $this->normalize($screenname);
  545. return false;
  546. }
  547. }
  548. function onValidateImScreenname($transport, $screenname, &$valid)
  549. {
  550. if($transport == $this->transport)
  551. {
  552. $valid = $this->validate($screenname);
  553. return false;
  554. }
  555. }
  556. function onGetImTransports(&$transports)
  557. {
  558. $transports[$this->transport] = array(
  559. 'display' => $this->getDisplayName(),
  560. 'daemonScreenname' => $this->daemonScreenname());
  561. }
  562. function onSendImConfirmationCode($transport, $screenname, $code, $user)
  563. {
  564. if($transport == $this->transport)
  565. {
  566. $this->sendConfirmationCode($screenname, $code, $user);
  567. return false;
  568. }
  569. }
  570. function onUserDeleteRelated($user, &$tables)
  571. {
  572. $tables[] = 'User_im_prefs';
  573. return true;
  574. }
  575. function onHaveImPlugin(&$haveImPlugin) {
  576. $haveImPlugin = true; // set flag true (we're loaded, after all!)
  577. return false; // stop looking
  578. }
  579. function initialize()
  580. {
  581. if( ! common_config('queue', 'enabled'))
  582. {
  583. // TRANS: Server exception thrown trying to initialise an IM plugin without meeting all prerequisites.
  584. throw new ServerException(_('Queueing must be enabled to use IM plugins.'));
  585. }
  586. if(is_null($this->transport)){
  587. // TRANS: Server exception thrown trying to initialise an IM plugin without a transport method.
  588. throw new ServerException(_('Transport cannot be null.'));
  589. }
  590. }
  591. }