implugin.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - MISC ========================\
  119. /**
  120. * Put raw message data (ready to send) into the outgoing queue
  121. *
  122. * @param object $data
  123. */
  124. function enqueueOutgoingRaw($data)
  125. {
  126. $qm = QueueManager::get();
  127. $qm->enqueue($data, $this->transport . '-out');
  128. }
  129. /**
  130. * Put raw message data (received, ready to be processed) into the incoming queue
  131. *
  132. * @param object $data
  133. */
  134. function enqueueIncomingRaw($data)
  135. {
  136. $qm = QueueManager::get();
  137. $qm->enqueue($data, $this->transport . '-in');
  138. }
  139. /**
  140. * given a screenname, get the corresponding user
  141. *
  142. * @param string $screenname
  143. *
  144. * @return User user
  145. */
  146. function getUser($screenname)
  147. {
  148. $user_im_prefs = $this->getUserImPrefsFromScreenname($screenname);
  149. if($user_im_prefs){
  150. $user = User::getKV('id', $user_im_prefs->user_id);
  151. $user_im_prefs->free();
  152. return $user;
  153. }else{
  154. return false;
  155. }
  156. }
  157. /**
  158. * given a screenname, get the User_im_prefs object for this transport
  159. *
  160. * @param string $screenname
  161. *
  162. * @return User_im_prefs user_im_prefs
  163. */
  164. function getUserImPrefsFromScreenname($screenname)
  165. {
  166. $user_im_prefs = User_im_prefs::pkeyGet(
  167. array('transport' => $this->transport,
  168. 'screenname' => $this->normalize($screenname)));
  169. if ($user_im_prefs) {
  170. return $user_im_prefs;
  171. } else {
  172. return false;
  173. }
  174. }
  175. /**
  176. * given a User, get their screenname
  177. *
  178. * @param User $user
  179. *
  180. * @return string screenname of that user
  181. */
  182. function getScreenname($user)
  183. {
  184. $user_im_prefs = $this->getUserImPrefsFromUser($user);
  185. if ($user_im_prefs) {
  186. return $user_im_prefs->screenname;
  187. } else {
  188. return false;
  189. }
  190. }
  191. /**
  192. * given a User, get their User_im_prefs
  193. *
  194. * @param User $user
  195. *
  196. * @return User_im_prefs user_im_prefs of that user
  197. */
  198. function getUserImPrefsFromUser($user)
  199. {
  200. $user_im_prefs = User_im_prefs::pkeyGet(
  201. array('transport' => $this->transport,
  202. 'user_id' => $user->id));
  203. if ($user_im_prefs){
  204. return $user_im_prefs;
  205. } else {
  206. return false;
  207. }
  208. }
  209. //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - SENDING ========================\
  210. /**
  211. * Send a message to a given screenname from the site
  212. *
  213. * @param string $screenname screenname to send the message to
  214. * @param string $msg message contents to send
  215. *
  216. * @param boolean success
  217. */
  218. protected function sendFromSite($screenname, $msg)
  219. {
  220. $text = '['.common_config('site', 'name') . '] ' . $msg;
  221. $this->sendMessage($screenname, $text);
  222. }
  223. /**
  224. * Send a confirmation code to a user
  225. *
  226. * @param string $screenname screenname sending to
  227. * @param string $code the confirmation code
  228. * @param Profile $target For whom the code is valid for
  229. *
  230. * @return boolean success value
  231. */
  232. function sendConfirmationCode($screenname, $code, Profile $target)
  233. {
  234. // TRANS: Body text for confirmation code e-mail.
  235. // TRANS: %1$s is a user nickname, %2$s is the StatusNet sitename,
  236. // TRANS: %3$s is the display name of an IM plugin.
  237. $body = sprintf(_('User "%1$s" on %2$s has said that your %3$s screenname belongs to them. ' .
  238. 'If that is true, you can confirm by clicking on this URL: ' .
  239. '%4$s' .
  240. ' . (If you cannot click it, copy-and-paste it into the ' .
  241. 'address bar of your browser). If that user is not you, ' .
  242. 'or if you did not request this confirmation, just ignore this message.'),
  243. $target->getNickname(), common_config('site', 'name'), $this->getDisplayName(), common_local_url('confirmaddress', null, array('code' => $code)));
  244. return $this->sendMessage($screenname, $body);
  245. }
  246. /**
  247. * send a notice to all public listeners
  248. *
  249. * For notices that are generated on the local system (by users), we can optionally
  250. * forward them to remote listeners by XMPP.
  251. *
  252. * @param Notice $notice notice to broadcast
  253. *
  254. * @return boolean success flag
  255. */
  256. function publicNotice($notice)
  257. {
  258. // Now, users who want everything
  259. // FIXME PRIV don't send out private messages here
  260. // XXX: should we send out non-local messages if public,localonly
  261. // = false? I think not
  262. foreach ($this->public as $screenname) {
  263. common_log(LOG_INFO,
  264. 'Sending notice ' . $notice->id .
  265. ' to public listener ' . $screenname,
  266. __FILE__);
  267. $this->sendNotice($screenname, $notice);
  268. }
  269. return true;
  270. }
  271. /**
  272. * broadcast a notice to all subscribers and reply recipients
  273. *
  274. * This function will send a notice to all subscribers on the local server
  275. * who have IM addresses, and have IM notification enabled, and
  276. * have this subscription enabled for IM. It also sends the notice to
  277. * all recipients of @-replies who have IM addresses and IM notification
  278. * enabled. This is really the heart of IM distribution in StatusNet.
  279. *
  280. * @param Notice $notice The notice to broadcast
  281. *
  282. * @return boolean success flag
  283. */
  284. function broadcastNotice($notice)
  285. {
  286. $ni = $notice->whoGets();
  287. foreach ($ni as $user_id => $reason) {
  288. $user = User::getKV($user_id);
  289. if (empty($user)) {
  290. // either not a local user, or just not found
  291. continue;
  292. }
  293. $user_im_prefs = $this->getUserImPrefsFromUser($user);
  294. if(!$user_im_prefs || !$user_im_prefs->notify){
  295. continue;
  296. }
  297. switch ($reason) {
  298. case NOTICE_INBOX_SOURCE_REPLY:
  299. if (!$user_im_prefs->replies) {
  300. continue 2;
  301. }
  302. break;
  303. case NOTICE_INBOX_SOURCE_SUB:
  304. $sub = Subscription::pkeyGet(array('subscriber' => $user->id,
  305. 'subscribed' => $notice->profile_id));
  306. if (empty($sub) || !$sub->jabber) {
  307. continue 2;
  308. }
  309. break;
  310. case NOTICE_INBOX_SOURCE_GROUP:
  311. break;
  312. default:
  313. // TRANS: Exception thrown when trying to deliver a notice to an unknown inbox.
  314. // TRANS: %d is the unknown inbox ID (number).
  315. throw new Exception(sprintf(_('Unknown inbox source %d.'), $reason));
  316. }
  317. common_log(LOG_INFO,
  318. 'Sending notice ' . $notice->id . ' to ' . $user_im_prefs->screenname,
  319. __FILE__);
  320. $this->sendNotice($user_im_prefs->screenname, $notice);
  321. $user_im_prefs->free();
  322. }
  323. return true;
  324. }
  325. /**
  326. * makes a plain-text formatted version of a notice, suitable for IM distribution
  327. *
  328. * @param Notice $notice notice being sent
  329. *
  330. * @return string plain-text version of the notice, with user nickname prefixed
  331. */
  332. protected function formatNotice(Notice $notice)
  333. {
  334. $profile = $notice->getProfile();
  335. $nicknames = $profile->getNickname();
  336. try {
  337. $parent = $notice->getParent();
  338. $orig_profile = $parent->getProfile();
  339. $nicknames = sprintf('%1$s => %2$s', $profile->getNickname(), $orig_profile->getNickname());
  340. } catch (NoParentNoticeException $e) {
  341. // Not a reply, no parent notice stored
  342. } catch (NoResultException $e) {
  343. // Parent notice was probably deleted
  344. }
  345. return sprintf('%1$s: %2$s [%3$u]', $nicknames, $notice->content, $notice->id);
  346. }
  347. //========================UTILITY FUNCTIONS USEFUL TO IMPLEMENTATIONS - RECEIVING ========================\
  348. /**
  349. * Attempt to handle a message as a command
  350. * @param User $user user the message is from
  351. * @param string $body message text
  352. * @return boolean true if the message was a command and was executed, false if it was not a command
  353. */
  354. protected function handleCommand($user, $body)
  355. {
  356. $inter = new CommandInterpreter();
  357. $cmd = $inter->handle_command($user, $body);
  358. if ($cmd) {
  359. $chan = new IMChannel($this);
  360. $cmd->execute($chan);
  361. return true;
  362. }
  363. return false;
  364. }
  365. /**
  366. * Is some text an autoreply message?
  367. * @param string $txt message text
  368. * @return boolean true if autoreply
  369. */
  370. protected function isAutoreply($txt)
  371. {
  372. if (preg_match('/[\[\(]?[Aa]uto[-\s]?[Rr]e(ply|sponse)[\]\)]/', $txt)) {
  373. return true;
  374. } else if (preg_match('/^System: Message wasn\'t delivered. Offline storage size was exceeded.$/', $txt)) {
  375. return true;
  376. } else {
  377. return false;
  378. }
  379. }
  380. /**
  381. * Is some text an OTR message?
  382. * @param string $txt message text
  383. * @return boolean true if OTR
  384. */
  385. protected function isOtr($txt)
  386. {
  387. if (preg_match('/^\?OTR/', $txt)) {
  388. return true;
  389. } else {
  390. return false;
  391. }
  392. }
  393. /**
  394. * Helper for handling incoming messages
  395. * Your incoming message handler will probably want to call this function
  396. *
  397. * @param string $from screenname the message was sent from
  398. * @param string $message message contents
  399. *
  400. * @param boolean success
  401. */
  402. protected function handleIncoming($from, $notice_text)
  403. {
  404. $user = $this->getUser($from);
  405. // For common_current_user to work
  406. global $_cur;
  407. $_cur = $user;
  408. if (!$user) {
  409. $this->sendFromSite($from, 'Unknown user; go to ' .
  410. common_local_url('imsettings') .
  411. ' to add your address to your account');
  412. common_log(LOG_WARNING, 'Message from unknown user ' . $from);
  413. return;
  414. }
  415. if ($this->handleCommand($user, $notice_text)) {
  416. common_log(LOG_INFO, "Command message by $from handled.");
  417. return;
  418. } else if ($this->isAutoreply($notice_text)) {
  419. common_log(LOG_INFO, 'Ignoring auto reply from ' . $from);
  420. return;
  421. } else if ($this->isOtr($notice_text)) {
  422. common_log(LOG_INFO, 'Ignoring OTR from ' . $from);
  423. return;
  424. } else {
  425. common_log(LOG_INFO, 'Posting a notice from ' . $user->nickname);
  426. $this->addNotice($from, $user, $notice_text);
  427. }
  428. $user->free();
  429. unset($user);
  430. unset($_cur);
  431. unset($message);
  432. }
  433. /**
  434. * Helper for handling incoming messages
  435. * Your incoming message handler will probably want to call this function
  436. *
  437. * @param string $from screenname the message was sent from
  438. * @param string $message message contents
  439. *
  440. * @param boolean success
  441. */
  442. protected function addNotice($screenname, $user, $body)
  443. {
  444. $body = trim(strip_tags($body));
  445. $content_shortened = common_shorten_links($body);
  446. if (Notice::contentTooLong($content_shortened)) {
  447. $this->sendFromSite($screenname,
  448. // TRANS: Message given when a status is too long. %1$s is the maximum number of characters,
  449. // TRANS: %2$s is the number of characters sent (used for plural).
  450. sprintf(_m('Message too long - maximum is %1$d character, you sent %2$d.',
  451. 'Message too long - maximum is %1$d characters, you sent %2$d.',
  452. Notice::maxContent()),
  453. Notice::maxContent(),
  454. mb_strlen($content_shortened)));
  455. return;
  456. }
  457. try {
  458. $notice = Notice::saveNew($user->id, $content_shortened, $this->transport);
  459. } catch (Exception $e) {
  460. common_log(LOG_ERR, $e->getMessage());
  461. $this->sendFromSite($from, $e->getMessage());
  462. return;
  463. }
  464. common_log(LOG_INFO,
  465. 'Added notice ' . $notice->id . ' from user ' . $user->nickname);
  466. $notice->free();
  467. unset($notice);
  468. }
  469. //========================EVENT HANDLERS========================\
  470. /**
  471. * Register notice queue handler
  472. *
  473. * @param QueueManager $manager
  474. *
  475. * @return boolean hook return
  476. */
  477. function onEndInitializeQueueManager($manager)
  478. {
  479. // If we don't require CLI mode, or if we do and GNUSOCIAL_CLI _is_ set, then connect the transports
  480. // This check is made mostly because some IM plugins can't deliver to transports unless they
  481. // have continously running daemons (such as XMPP) and we can't have that over HTTP requests.
  482. if (!$this->requires_cli || defined('GNUSOCIAL_CLI')) {
  483. $manager->connect($this->transport . '-in', new ImReceiverQueueHandler($this), 'im');
  484. $manager->connect($this->transport, new ImQueueHandler($this));
  485. $manager->connect($this->transport . '-out', new ImSenderQueueHandler($this), 'im');
  486. }
  487. return true;
  488. }
  489. function onStartImDaemonIoManagers(&$classes)
  490. {
  491. //$classes[] = new ImManager($this); // handles sending/receiving/pings/reconnects
  492. return true;
  493. }
  494. function onStartEnqueueNotice($notice, &$transports)
  495. {
  496. $profile = Profile::getKV($notice->profile_id);
  497. if (!$profile) {
  498. common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
  499. 'unknown profile ' . common_log_objstring($notice),
  500. __FILE__);
  501. }else{
  502. $transports[] = $this->transport;
  503. }
  504. return true;
  505. }
  506. function onEndShowHeadElements(Action $action)
  507. {
  508. if ($action instanceof ShownoticeAction) {
  509. $user_im_prefs = new User_im_prefs();
  510. $user_im_prefs->user_id = $action->notice->getProfile()->getID();
  511. $user_im_prefs->transport = $this->transport;
  512. } elseif ($action instanceof ShowstreamAction) {
  513. $user_im_prefs = new User_im_prefs();
  514. $user_im_prefs->user_id = $action->getTarget()->getID();
  515. $user_im_prefs->transport = $this->transport;
  516. }
  517. }
  518. function onNormalizeImScreenname($transport, &$screenname)
  519. {
  520. if($transport == $this->transport)
  521. {
  522. $screenname = $this->normalize($screenname);
  523. return false;
  524. }
  525. }
  526. function onValidateImScreenname($transport, $screenname, &$valid)
  527. {
  528. if($transport == $this->transport)
  529. {
  530. $valid = $this->validate($screenname);
  531. return false;
  532. }
  533. }
  534. function onGetImTransports(&$transports)
  535. {
  536. $transports[$this->transport] = array(
  537. 'display' => $this->getDisplayName(),
  538. 'daemonScreenname' => $this->daemonScreenname());
  539. }
  540. function onSendImConfirmationCode($transport, $screenname, $code, Profile $target)
  541. {
  542. if($transport == $this->transport)
  543. {
  544. $this->sendConfirmationCode($screenname, $code, $target);
  545. return false;
  546. }
  547. }
  548. function onUserDeleteRelated($user, &$tables)
  549. {
  550. $tables[] = 'User_im_prefs';
  551. return true;
  552. }
  553. function onHaveImPlugin(&$haveImPlugin) {
  554. $haveImPlugin = true; // set flag true (we're loaded, after all!)
  555. return false; // stop looking
  556. }
  557. function initialize()
  558. {
  559. if( ! common_config('queue', 'enabled'))
  560. {
  561. // TRANS: Server exception thrown trying to initialise an IM plugin without meeting all prerequisites.
  562. throw new ServerException(_('Queueing must be enabled to use IM plugins.'));
  563. }
  564. if(is_null($this->transport)){
  565. // TRANS: Server exception thrown trying to initialise an IM plugin without a transport method.
  566. throw new ServerException(_('Transport cannot be null.'));
  567. }
  568. }
  569. }