mailhandler.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /*
  17. * @copyright 2008, 2009 StatusNet, Inc.
  18. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  19. */
  20. defined('GNUSOCIAL') || die();
  21. require_once INSTALLDIR . '/lib/util/tempfile.php';
  22. require_once INSTALLDIR . '/lib/util/mail.php';
  23. require_once 'Mail/mimeDecode.php';
  24. // @todo FIXME: we use both Mail_mimeDecode and mailparse
  25. // Need to move everything to mailparse
  26. class MailHandler
  27. {
  28. public function __construct()
  29. {
  30. }
  31. public function handle_message($rawmessage)
  32. {
  33. list($from, $to, $msg, $attachments) = $this->parse_message($rawmessage);
  34. if (!$from || !$to || !$msg) {
  35. // TRANS: Error message in incoming mail handler used when an incoming e-mail cannot be processed.
  36. $this->error(null, _('Could not parse message.'));
  37. }
  38. common_log(LOG_INFO, "Mail from $from to $to with ".count($attachments) .' attachment(s): ' .substr($msg, 0, 20));
  39. $user = $this->user_from_header($from);
  40. if (!$user) {
  41. // TRANS: Error message in incoming mail handler used when an incoming e-mail is not from a registered user.
  42. $this->error($from, _('Not a registered user.'));
  43. return false;
  44. }
  45. if (!$this->user_match_to($user, $to)) {
  46. // TRANS: Error message in incoming mail handler used when an incoming e-mail is not from a user's incoming e-mail address.
  47. $this->error($from, _('Sorry, that is not your incoming email address.'));
  48. return false;
  49. }
  50. if (!$user->emailpost) {
  51. // TRANS: Error message in incoming mail handler used when no incoming e-mail is allowed.
  52. $this->error($from, _('Sorry, no incoming email allowed.'));
  53. return false;
  54. }
  55. $response = $this->handle_command($user, $from, $msg);
  56. if ($response) {
  57. return true;
  58. }
  59. $msg = $this->cleanup_msg($msg);
  60. $msg = $user->shortenLinks($msg);
  61. if (Notice::contentTooLong($msg)) {
  62. // TRANS: Error message in incoming mail handler used when an incoming e-mail contains too many characters.
  63. $this->error($from, sprintf(
  64. _m('That\'s too long. Maximum notice size is %d character.',
  65. 'That\'s too long. Maximum notice size is %d characters.',
  66. Notice::maxContent()),
  67. Notice::maxContent()
  68. ));
  69. }
  70. $mediafiles = array();
  71. foreach ($attachments as $attachment) {
  72. $mf = null;
  73. try {
  74. $mf = MediaFile::fromFileInfo($attachment, $user->getProfile());
  75. } catch (ClientException $ce) {
  76. $this->error($from, $ce->getMessage());
  77. }
  78. $msg .= ' ' . $mf->shortUrl();
  79. array_push($mediafiles, $mf);
  80. fclose($attachment);
  81. }
  82. $err = $this->add_notice($user, $msg, $mediafiles);
  83. if (is_string($err)) {
  84. $this->error($from, $err);
  85. return false;
  86. } else {
  87. return true;
  88. }
  89. }
  90. public function error($from, $msg)
  91. {
  92. file_put_contents("php://stderr", $msg . "\n");
  93. exit(1);
  94. }
  95. public function user_from_header($from_hdr)
  96. {
  97. $froms = mailparse_rfc822_parse_addresses($from_hdr);
  98. if (!$froms) {
  99. return null;
  100. }
  101. $from = $froms[0];
  102. $addr = common_canonical_email($from['address']);
  103. $user = User::getKV('email', $addr);
  104. if (!$user) {
  105. $user = User::getKV('smsemail', $addr);
  106. }
  107. return $user;
  108. }
  109. public function user_match_to($user, $to_hdr)
  110. {
  111. $incoming = $user->incomingemail;
  112. $tos = mailparse_rfc822_parse_addresses($to_hdr);
  113. foreach ($tos as $to) {
  114. if (strcasecmp($incoming, $to['address']) == 0) {
  115. return true;
  116. }
  117. }
  118. return false;
  119. }
  120. public function handle_command($user, $from, $msg)
  121. {
  122. $inter = new CommandInterpreter();
  123. $cmd = $inter->handle_command($user, $msg);
  124. if ($cmd) {
  125. $cmd->execute(new MailChannel($from));
  126. return true;
  127. }
  128. return false;
  129. }
  130. public function respond($from, $to, $response)
  131. {
  132. $headers['From'] = $to;
  133. $headers['To'] = $from;
  134. // TRANS: E-mail subject for reply to an e-mail command.
  135. $headers['Subject'] = _('Command complete');
  136. return mail_send(array($from), $headers, $response);
  137. }
  138. public function log($level, $msg)
  139. {
  140. common_log($level, 'MailDaemon: '.$msg);
  141. }
  142. public function add_notice($user, $msg, $mediafiles)
  143. {
  144. try {
  145. $notice = Notice::saveNew($user->id, $msg, 'mail');
  146. } catch (Exception $e) {
  147. $this->log(LOG_ERR, $e->getMessage());
  148. return $e->getMessage();
  149. }
  150. foreach ($mediafiles as $mf) {
  151. $mf->attachToNotice($notice);
  152. }
  153. $this->log(
  154. LOG_INFO,
  155. "Added notice {$notice->id} from user {$user->nickname}"
  156. );
  157. return true;
  158. }
  159. public function parse_message($contents)
  160. {
  161. $parsed = Mail_mimeDecode::decode([
  162. 'input' => $contents,
  163. 'include_bodies' => true,
  164. 'decode_headers' => true,
  165. 'decode_bodies' => true,
  166. ]);
  167. if (!$parsed) {
  168. return null;
  169. }
  170. $from = $parsed->headers['from'];
  171. $to = $parsed->headers['to'];
  172. $type = $parsed->ctype_primary . '/' . $parsed->ctype_secondary;
  173. $attachments = array();
  174. $this->extract_part($parsed, $msg, $attachments);
  175. return array($from, $to, $msg, $attachments);
  176. }
  177. public function extract_part($parsed, &$msg, &$attachments)
  178. {
  179. if ($parsed->ctype_primary === 'multipart') {
  180. if ($parsed->ctype_secondary === 'alternative') {
  181. $altmsg = $this->extract_msg_from_multipart_alternative_part($parsed);
  182. if (!empty($altmsg)) {
  183. $msg = $altmsg;
  184. }
  185. } else {
  186. foreach ($parsed->parts as $part) {
  187. $this->extract_part($part, $msg, $attachments);
  188. }
  189. }
  190. } elseif (
  191. $parsed->ctype_primary === 'text'
  192. && $parsed->ctype_secondary === 'plain'
  193. ) {
  194. $msg = $parsed->body;
  195. if (strtolower($parsed->ctype_parameters['charset']) !== 'utf-8') {
  196. $msg = utf8_encode($msg);
  197. }
  198. } elseif (!empty($parsed->body)) {
  199. if (common_config('attachments', 'uploads')) {
  200. // Only save attachments if uploads are enabled
  201. $attachment = new TemporaryFile('gs-mailattach');
  202. fwrite($attachment->getResource(), $parsed->body);
  203. fflush($attachment->getResource());
  204. $attachments[] = $attachment;
  205. }
  206. }
  207. }
  208. public function extract_msg_from_multipart_alternative_part($parsed)
  209. {
  210. foreach ($parsed->parts as $part) {
  211. $this->extract_part($part, $msg, $attachments);
  212. }
  213. //we don't want any attachments that are a result of this parsing
  214. return $msg;
  215. }
  216. public function unsupported_type($type)
  217. {
  218. // TRANS: Error message in incoming mail handler used when an incoming e-mail is of an unsupported type.
  219. // TRANS: %s is the unsupported type.
  220. $this->error(null, sprintf(_('Unsupported message type: %s.'), $type));
  221. }
  222. public function cleanup_msg($msg)
  223. {
  224. $lines = explode("\n", $msg);
  225. $output = '';
  226. foreach ($lines as $line) {
  227. // skip quotes
  228. if (preg_match('/^\s*>.*$/', $line)) {
  229. continue;
  230. }
  231. // skip start of quote
  232. if (preg_match('/^\s*On.*wrote:\s*$/', $line)) {
  233. continue;
  234. }
  235. // probably interesting to someone, not us
  236. if (preg_match('/^\s*Sent via/', $line)) {
  237. continue;
  238. }
  239. if (preg_match('/^\s*Sent from my/', $line)) {
  240. continue;
  241. }
  242. // skip everything after a sig
  243. if (
  244. preg_match('/^\s*--+\s*$/', $line)
  245. || preg_match('/^\s*__+\s*$/', $line)
  246. ) {
  247. break;
  248. }
  249. // skip everything after Outlook quote
  250. if (preg_match('/^\s*-+\s*Original Message\s*-+\s*$/', $line)) {
  251. break;
  252. }
  253. // skip everything after weird forward
  254. if (preg_match('/^\s*Begin\s+forward/', $line)) {
  255. break;
  256. }
  257. // skip everything after a blank line if we already have content
  258. if ($output !== '' && $line === '') {
  259. break;
  260. }
  261. $output .= ' ' . $line;
  262. }
  263. preg_replace('/\s+/', ' ', $output);
  264. return trim($output);
  265. }
  266. }