]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/maildaemon.php
Merge remote branch 'statusnet/0.8.x' into 0.9.x
[quix0rs-gnu-social.git] / scripts / maildaemon.php
1 #!/usr/bin/env php
2 <?php
3 /*
4  * StatusNet - the distributed open-source microblogging tool
5  * Copyright (C) 2008, 2009, StatusNet, Inc.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
22
23 $helptext = <<<END_OF_HELP
24 Script for converting mail messages into notices. Takes message body
25 as STDIN.
26
27 END_OF_HELP;
28
29 require_once INSTALLDIR.'/scripts/commandline.inc';
30
31 require_once(INSTALLDIR . '/lib/mail.php');
32 require_once('Mail/mimeDecode.php');
33
34 # FIXME: we use both Mail_mimeDecode and mailparse
35 # Need to move everything to mailparse
36
37 class MailerDaemon
38 {
39     function __construct()
40     {
41     }
42
43     function handle_message($fname='php://stdin')
44     {
45         list($from, $to, $msg, $attachments) = $this->parse_message($fname);
46         if (!$from || !$to || !$msg) {
47             $this->error(null, _('Could not parse message.'));
48         }
49         common_log(LOG_INFO, "Mail from $from to $to with ".count($attachments) .' attachment(s): ' .substr($msg, 0, 20));
50         $user = $this->user_from($from);
51         if (!$user) {
52             $this->error($from, _('Not a registered user.'));
53             return false;
54         }
55         if (!$this->user_match_to($user, $to)) {
56             $this->error($from, _('Sorry, that is not your incoming email address.'));
57             return false;
58         }
59         if (!$user->emailpost) {
60             $this->error($from, _('Sorry, no incoming email allowed.'));
61             return false;
62         }
63         $response = $this->handle_command($user, $from, $msg);
64         if ($response) {
65             return true;
66         }
67         $msg = $this->cleanup_msg($msg);
68         $msg = common_shorten_links($msg);
69         if (Notice::contentTooLong($msg)) {
70             $this->error($from, sprintf(_('That\'s too long. '.
71                                           'Max notice size is %d chars.'),
72                                         Notice::maxContent()));
73         }
74         $fileRecords = array();
75         foreach($attachments as $attachment){
76             $mimetype = $this->getUploadedFileType($attachment);
77             $stream  = stream_get_meta_data($attachment);
78             if (!$this->isRespectsQuota($user,filesize($stream['uri']))) {
79                 die('error() should trigger an exception before reaching here.');
80             }
81             $filename = $this->saveFile($user, $attachment,$mimetype);
82
83             fclose($attachment);
84
85             if (empty($filename)) {
86                 $this->error($from,_('Couldn\'t save file.'));
87             }
88
89             $fileRecord = $this->storeFile($filename, $mimetype);
90             $fileRecords[] = $fileRecord;
91             $fileurl = common_local_url('attachment',
92                 array('attachment' => $fileRecord->id));
93
94             // not sure this is necessary -- Zach
95             $this->maybeAddRedir($fileRecord->id, $fileurl);
96
97             $short_fileurl = common_shorten_url($fileurl);
98             $msg .= ' ' . $short_fileurl;
99
100             if (Notice::contentTooLong($msg)) {
101                 $this->deleteFile($filename);
102                 $this->error($from, sprintf(_('Max notice size is %d chars, including attachment URL.'),
103                                             Notice::maxContent()));
104             }
105
106             // Also, not sure this is necessary -- Zach
107             $this->maybeAddRedir($fileRecord->id, $short_fileurl);
108         }
109
110         $err = $this->add_notice($user, $msg, $fileRecords);
111         if (is_string($err)) {
112             $this->error($from, $err);
113             return false;
114         } else {
115             return true;
116         }
117     }
118
119     function saveFile($user, $attachment, $mimetype) {
120
121         $filename = File::filename($user->getProfile(), "email", $mimetype);
122
123         $filepath = File::path($filename);
124
125         $stream  = stream_get_meta_data($attachment);
126         if (copy($stream['uri'], $filepath) && chmod($filepath,0664)) {
127             return $filename;
128         } else {
129             $this->error(null,_('File could not be moved to destination directory.' . $stream['uri'] . ' ' . $filepath));
130         }
131     }
132
133     function storeFile($filename, $mimetype) {
134
135         $file = new File;
136         $file->filename = $filename;
137
138         $file->url = File::url($filename);
139
140         $filepath = File::path($filename);
141
142         $file->size = filesize($filepath);
143         $file->date = time();
144         $file->mimetype = $mimetype;
145
146         $file_id = $file->insert();
147
148         if (!$file_id) {
149             common_log_db_error($file, "INSERT", __FILE__);
150             $this->error(null,_('There was a database error while saving your file. Please try again.'));
151         }
152
153         return $file;
154     }
155
156     function maybeAddRedir($file_id, $url)
157     {
158         $file_redir = File_redirection::staticGet('url', $url);
159
160         if (empty($file_redir)) {
161             $file_redir = new File_redirection;
162             $file_redir->url = $url;
163             $file_redir->file_id = $file_id;
164
165             $result = $file_redir->insert();
166
167             if (!$result) {
168                 common_log_db_error($file_redir, "INSERT", __FILE__);
169                 $this->error(null,_('There was a database error while saving your file. Please try again.'));
170             }
171         }
172     }
173
174     function getUploadedFileType($fileHandle) {
175         require_once 'MIME/Type.php';
176
177         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
178         $cmd = common_config('attachments', 'filecommand');
179
180         $stream  = stream_get_meta_data($fileHandle);
181         $filetype = MIME_Type::autoDetect($stream['uri']);
182         if (in_array($filetype, common_config('attachments', 'supported'))) {
183             return $filetype;
184         }
185         $media = MIME_Type::getMedia($filetype);
186         if ('application' !== $media) {
187             $hint = sprintf(_(' Try using another %s format.'), $media);
188         } else {
189             $hint = '';
190         }
191         $this->error(null,sprintf(
192             _('%s is not a supported filetype on this server.'), $filetype) . $hint);
193     }
194
195     function isRespectsQuota($user,$fileSize) {
196         $file = new File;
197         $ret = $file->isRespectsQuota($user,$fileSize);
198         if (true === $ret) return true;
199         $this->error(null,$ret);
200     }
201
202     function error($from, $msg)
203     {
204         file_put_contents("php://stderr", $msg . "\n");
205         exit(1);
206     }
207
208     function user_from($from_hdr)
209     {
210         $froms = mailparse_rfc822_parse_addresses($from_hdr);
211         if (!$froms) {
212             return null;
213         }
214         $from = $froms[0];
215         $addr = common_canonical_email($from['address']);
216         $user = User::staticGet('email', $addr);
217         if (!$user) {
218             $user = User::staticGet('smsemail', $addr);
219         }
220         return $user;
221     }
222
223     function user_match_to($user, $to_hdr)
224     {
225         $incoming = $user->incomingemail;
226         $tos = mailparse_rfc822_parse_addresses($to_hdr);
227         foreach ($tos as $to) {
228             if (strcasecmp($incoming, $to['address']) == 0) {
229                 return true;
230             }
231         }
232         return false;
233     }
234
235     function handle_command($user, $from, $msg)
236     {
237         $inter = new CommandInterpreter();
238         $cmd = $inter->handle_command($user, $msg);
239         if ($cmd) {
240             $cmd->execute(new MailChannel($from));
241             return true;
242         }
243         return false;
244     }
245
246     function respond($from, $to, $response)
247     {
248
249         $headers['From'] = $to;
250         $headers['To'] = $from;
251         $headers['Subject'] = "Command complete";
252
253         return mail_send(array($from), $headers, $response);
254     }
255
256     function log($level, $msg)
257     {
258         common_log($level, 'MailDaemon: '.$msg);
259     }
260
261     function add_notice($user, $msg, $fileRecords)
262     {
263         try {
264             $notice = Notice::saveNew($user->id, $msg, 'mail');
265         } catch (Exception $e) {
266             $this->log(LOG_ERR, $e->getMessage());
267             return $e->getMessage();
268         }
269         foreach($fileRecords as $fileRecord){
270             $this->attachFile($notice, $fileRecord);
271         }
272         common_broadcast_notice($notice);
273         $this->log(LOG_INFO,
274                    'Added notice ' . $notice->id . ' from user ' . $user->nickname);
275         return true;
276     }
277
278     function attachFile($notice, $filerec)
279     {
280         File_to_post::processNew($filerec->id, $notice->id);
281
282         $this->maybeAddRedir($filerec->id,
283             common_local_url('file', array('notice' => $notice->id)));
284     }
285
286     function parse_message($fname)
287     {
288         $contents = file_get_contents($fname);
289         $parsed = Mail_mimeDecode::decode(array('input' => $contents,
290                                                 'include_bodies' => true,
291                                                 'decode_headers' => true,
292                                                 'decode_bodies' => true));
293         if (!$parsed) {
294             return null;
295         }
296
297         $from = $parsed->headers['from'];
298
299         $to = $parsed->headers['to'];
300
301         $type = $parsed->ctype_primary . '/' . $parsed->ctype_secondary;
302
303         $attachments = array();
304
305         $this->extract_part($parsed,$msg,$attachments);
306
307         return array($from, $to, $msg, $attachments);
308     }
309
310     function extract_part($parsed,&$msg,&$attachments){
311         if ($parsed->ctype_primary == 'multipart') {
312             if($parsed->ctype_secondary == 'alternative'){
313                 $altmsg = $this->extract_msg_from_multipart_alternative_part($parsed);
314                 if(!empty($altmsg)) $msg = $altmsg;
315             }else{
316                 foreach($parsed->parts as $part){
317                     $this->extract_part($part,$msg,$attachments);
318                 }
319             }
320         } else if ($parsed->ctype_primary == 'text'
321             && $parsed->ctype_secondary=='plain') {
322             $msg = $parsed->body;
323             if(strtolower($parsed->ctype_parameters['charset']) != "utf-8"){
324                 $msg = utf8_encode($msg);
325             }
326         }else if(!empty($parsed->body)){
327             if(common_config('attachments', 'uploads')){
328                 //only save attachments if uploads are enabled
329                 $attachment = tmpfile();
330                 fwrite($attachment, $parsed->body);
331                 $attachments[] = $attachment;
332             }
333         }
334     }
335
336     function extract_msg_from_multipart_alternative_part($parsed){
337         foreach ($parsed->parts as $part) {
338             $this->extract_part($part,$msg,$attachments);
339         }
340         //we don't want any attachments that are a result of this parsing
341         return $msg;
342     }
343
344     function unsupported_type($type)
345     {
346         $this->error(null, "Unsupported message type: " . $type);
347     }
348
349     function cleanup_msg($msg)
350     {
351         $lines = explode("\n", $msg);
352
353         $output = '';
354
355         foreach ($lines as $line) {
356             // skip quotes
357             if (preg_match('/^\s*>.*$/', $line)) {
358                 continue;
359             }
360             // skip start of quote
361             if (preg_match('/^\s*On.*wrote:\s*$/', $line)) {
362                 continue;
363             }
364             // probably interesting to someone, not us
365             if (preg_match('/^\s*Sent via/', $line)) {
366                 continue;
367             }
368             // skip everything after a sig
369             if (preg_match('/^\s*--+\s*$/', $line) ||
370                 preg_match('/^\s*__+\s*$/', $line))
371             {
372                 break;
373             }
374             // skip everything after Outlook quote
375             if (preg_match('/^\s*-+\s*Original Message\s*-+\s*$/', $line)) {
376                 break;
377             }
378             // skip everything after weird forward
379             if (preg_match('/^\s*Begin\s+forward/', $line)) {
380                 break;
381             }
382
383             $output .= ' ' . $line;
384         }
385
386         preg_replace('/\s+/', ' ', $output);
387         return trim($output);
388     }
389 }
390
391 if (common_config('emailpost', 'enabled')) {
392     $md = new MailerDaemon();
393     $md->handle_message('php://stdin');
394 }