]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/mailhandler.php
Merge branch 'testing' into 0.9.x
[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 # 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             $this->error(null, _('Could not parse message.'));
38         }
39         common_log(LOG_INFO, "Mail from $from to $to with ".count($attachments) .' attachment(s): ' .substr($msg, 0, 20));
40         $user = $this->user_from_header($from);
41         if (!$user) {
42             $this->error($from, _('Not a registered user.'));
43             return false;
44         }
45         if (!$this->user_match_to($user, $to)) {
46             $this->error($from, _('Sorry, that is not your incoming email address.'));
47             return false;
48         }
49         if (!$user->emailpost) {
50             $this->error($from, _('Sorry, no incoming email allowed.'));
51             return false;
52         }
53         $response = $this->handle_command($user, $from, $msg);
54         if ($response) {
55             return true;
56         }
57         $msg = $this->cleanup_msg($msg);
58         $msg = common_shorten_links($msg);
59         if (Notice::contentTooLong($msg)) {
60             $this->error($from, sprintf(_('That\'s too long. '.
61                                           'Max notice size is %d chars.'),
62                                         Notice::maxContent()));
63         }
64
65         $mediafiles = array();
66
67         foreach($attachments as $attachment){
68
69             $mf = null;
70
71             try {
72                 $mf = MediaFile::fromFileHandle($attachment, $user);
73             } catch(ClientException $ce) {
74                 $this->error($from, $ce->getMessage());
75             }
76
77             $msg .= ' ' . $mf->shortUrl();
78
79             array_push($mediafiles, $mf);
80             fclose($attachment);
81         }
82
83         $err = $this->add_notice($user, $msg, $mediafiles);
84
85         if (is_string($err)) {
86             $this->error($from, $err);
87             return false;
88         } else {
89             return true;
90         }
91     }
92
93     function error($from, $msg)
94     {
95         file_put_contents("php://stderr", $msg . "\n");
96         exit(1);
97     }
98
99     function user_from_header($from_hdr)
100     {
101         $froms = mailparse_rfc822_parse_addresses($from_hdr);
102         if (!$froms) {
103             return null;
104         }
105         $from = $froms[0];
106         $addr = common_canonical_email($from['address']);
107         $user = User::staticGet('email', $addr);
108         if (!$user) {
109             $user = User::staticGet('smsemail', $addr);
110         }
111         return $user;
112     }
113
114     function user_match_to($user, $to_hdr)
115     {
116         $incoming = $user->incomingemail;
117         $tos = mailparse_rfc822_parse_addresses($to_hdr);
118         foreach ($tos as $to) {
119             if (strcasecmp($incoming, $to['address']) == 0) {
120                 return true;
121             }
122         }
123         return false;
124     }
125
126     function handle_command($user, $from, $msg)
127     {
128         $inter = new CommandInterpreter();
129         $cmd = $inter->handle_command($user, $msg);
130         if ($cmd) {
131             $cmd->execute(new MailChannel($from));
132             return true;
133         }
134         return false;
135     }
136
137     function respond($from, $to, $response)
138     {
139
140         $headers['From'] = $to;
141         $headers['To'] = $from;
142         $headers['Subject'] = _('Command complete');
143
144         return mail_send(array($from), $headers, $response);
145     }
146
147     function log($level, $msg)
148     {
149         common_log($level, 'MailDaemon: '.$msg);
150     }
151
152     function add_notice($user, $msg, $mediafiles)
153     {
154         try {
155             $notice = Notice::saveNew($user->id, $msg, 'mail');
156         } catch (Exception $e) {
157             $this->log(LOG_ERR, $e->getMessage());
158             return $e->getMessage();
159         }
160         foreach($mediafiles as $mf){
161             $mf->attachToNotice($notice);
162         }
163
164         $this->log(LOG_INFO,
165                    'Added notice ' . $notice->id . ' from user ' . $user->nickname);
166         return true;
167     }
168
169     function parse_message($contents)
170     {
171         $parsed = Mail_mimeDecode::decode(array('input' => $contents,
172                                                 'include_bodies' => true,
173                                                 'decode_headers' => true,
174                                                 'decode_bodies' => true));
175         if (!$parsed) {
176             return null;
177         }
178
179         $from = $parsed->headers['from'];
180
181         $to = $parsed->headers['to'];
182
183         $type = $parsed->ctype_primary . '/' . $parsed->ctype_secondary;
184
185         $attachments = array();
186
187         $this->extract_part($parsed,$msg,$attachments);
188
189         return array($from, $to, $msg, $attachments);
190     }
191
192     function extract_part($parsed,&$msg,&$attachments){
193         if ($parsed->ctype_primary == 'multipart') {
194             if($parsed->ctype_secondary == 'alternative'){
195                 $altmsg = $this->extract_msg_from_multipart_alternative_part($parsed);
196                 if(!empty($altmsg)) $msg = $altmsg;
197             }else{
198                 foreach($parsed->parts as $part){
199                     $this->extract_part($part,$msg,$attachments);
200                 }
201             }
202         } else if ($parsed->ctype_primary == 'text'
203             && $parsed->ctype_secondary=='plain') {
204             $msg = $parsed->body;
205             if(strtolower($parsed->ctype_parameters['charset']) != "utf-8"){
206                 $msg = utf8_encode($msg);
207             }
208         }else if(!empty($parsed->body)){
209             if(common_config('attachments', 'uploads')){
210                 //only save attachments if uploads are enabled
211                 $attachment = tmpfile();
212                 fwrite($attachment, $parsed->body);
213                 $attachments[] = $attachment;
214             }
215         }
216     }
217
218     function extract_msg_from_multipart_alternative_part($parsed){
219         foreach ($parsed->parts as $part) {
220             $this->extract_part($part,$msg,$attachments);
221         }
222         //we don't want any attachments that are a result of this parsing
223         return $msg;
224     }
225
226     function unsupported_type($type)
227     {
228         $this->error(null, sprintf(_('Unsupported message type: %s'), $type));
229     }
230
231     function cleanup_msg($msg)
232     {
233         $lines = explode("\n", $msg);
234
235         $output = '';
236
237         foreach ($lines as $line) {
238             // skip quotes
239             if (preg_match('/^\s*>.*$/', $line)) {
240                 continue;
241             }
242             // skip start of quote
243             if (preg_match('/^\s*On.*wrote:\s*$/', $line)) {
244                 continue;
245             }
246             // probably interesting to someone, not us
247             if (preg_match('/^\s*Sent via/', $line)) {
248                 continue;
249             }
250             if (preg_match('/^\s*Sent from my/', $line)) {
251                 continue;
252             }
253
254             // skip everything after a sig
255             if (preg_match('/^\s*--+\s*$/', $line) ||
256                 preg_match('/^\s*__+\s*$/', $line))
257             {
258                 break;
259             }
260             // skip everything after Outlook quote
261             if (preg_match('/^\s*-+\s*Original Message\s*-+\s*$/', $line)) {
262                 break;
263             }
264             // skip everything after weird forward
265             if (preg_match('/^\s*Begin\s+forward/', $line)) {
266                 break;
267             }
268             // skip everything after a blank line if we already have content
269             if ($output !== '' && $line === '') {
270                 break;
271             }
272
273             $output .= ' ' . $line;
274         }
275
276         preg_replace('/\s+/', ' ', $output);
277         return trim($output);
278     }
279 }