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