]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/maildaemon.php
Merge branch 'master' into testing
[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 (mb_strlen($msg) > 140) {
70             $this->error($from,_('That\'s too long. '.
71                 'Max notice size is 140 chars.'));
72         }
73         $fileRecords = array();
74         foreach($attachments as $attachment){
75             $mimetype = $this->getUploadedFileType($attachment);
76             $stream  = stream_get_meta_data($attachment);
77             if (!$this->isRespectsQuota($user,filesize($stream['uri']))) {
78                 die('error() should trigger an exception before reaching here.');
79             }
80             $filename = $this->saveFile($user, $attachment,$mimetype);
81             
82             fclose($attachment);
83             
84             if (empty($filename)) {
85                 $this->error($from,_('Couldn\'t save file.'));
86             }
87
88             $fileRecord = $this->storeFile($filename, $mimetype);
89             $fileRecords[] = $fileRecord;
90             $fileurl = common_local_url('attachment',
91                 array('attachment' => $fileRecord->id));
92
93             // not sure this is necessary -- Zach
94             $this->maybeAddRedir($fileRecord->id, $fileurl);
95
96             $short_fileurl = common_shorten_url($fileurl);
97             $msg .= ' ' . $short_fileurl;
98
99             if (mb_strlen($msg) > 140) {
100                 $this->deleteFile($filename);
101                 $this->error($from,_('Max notice size is 140 chars, including attachment URL.'));
102             }
103
104             // Also, not sure this is necessary -- Zach
105             $this->maybeAddRedir($fileRecord->id, $short_fileurl);
106         }
107
108         $err = $this->add_notice($user, $msg, $fileRecords);
109         if (is_string($err)) {
110             $this->error($from, $err);
111             return false;
112         } else {
113             return true;
114         }
115     }
116
117     function saveFile($user, $attachment, $mimetype) {
118
119         $filename = File::filename($user->getProfile(), "email", $mimetype);
120
121         $filepath = File::path($filename);
122
123         $stream  = stream_get_meta_data($attachment);
124         if (copy($stream['uri'], $filepath) && chmod($filepath,0664)) {
125             return $filename;
126         } else {   
127             $this->error(null,_('File could not be moved to destination directory.' . $stream['uri'] . ' ' . $filepath));
128         }
129     }
130
131     function storeFile($filename, $mimetype) {
132
133         $file = new File;
134         $file->filename = $filename;
135
136         $file->url = File::url($filename);
137
138         $filepath = File::path($filename);
139
140         $file->size = filesize($filepath);
141         $file->date = time();
142         $file->mimetype = $mimetype;
143
144         $file_id = $file->insert();
145
146         if (!$file_id) {
147             common_log_db_error($file, "INSERT", __FILE__);
148             $this->error(null,_('There was a database error while saving your file. Please try again.'));
149         }
150
151         return $file;
152     }
153
154     function maybeAddRedir($file_id, $url)
155     {   
156         $file_redir = File_redirection::staticGet('url', $url);
157
158         if (empty($file_redir)) {
159             $file_redir = new File_redirection;
160             $file_redir->url = $url;
161             $file_redir->file_id = $file_id;
162
163             $result = $file_redir->insert();
164
165             if (!$result) {
166                 common_log_db_error($file_redir, "INSERT", __FILE__);
167                 $this->error(null,_('There was a database error while saving your file. Please try again.'));
168             }
169         }
170     }
171
172     function getUploadedFileType($fileHandle) {
173         require_once 'MIME/Type.php';
174
175         $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
176         $cmd = common_config('attachments', 'filecommand');
177
178         $stream  = stream_get_meta_data($fileHandle);
179         $filetype = MIME_Type::autoDetect($stream['uri']);
180         if (in_array($filetype, common_config('attachments', 'supported'))) {
181             return $filetype;
182         }
183         $media = MIME_Type::getMedia($filetype);
184         if ('application' !== $media) {
185             $hint = sprintf(_(' Try using another %s format.'), $media);
186         } else {
187             $hint = '';
188         }
189         $this->error(null,sprintf(
190             _('%s is not a supported filetype on this server.'), $filetype) . $hint);
191     }
192
193     function isRespectsQuota($user,$fileSize) {
194         $file = new File;
195         $ret = $file->isRespectsQuota($user,$fileSize);
196         if (true === $ret) return true;
197         $this->error(null,$ret);
198     }
199
200     function error($from, $msg)
201     {
202         file_put_contents("php://stderr", $msg . "\n");
203         exit(1);
204     }
205
206     function user_from($from_hdr)
207     {
208         $froms = mailparse_rfc822_parse_addresses($from_hdr);
209         if (!$froms) {
210             return null;
211         }
212         $from = $froms[0];
213         $addr = common_canonical_email($from['address']);
214         $user = User::staticGet('email', $addr);
215         if (!$user) {
216             $user = User::staticGet('smsemail', $addr);
217         }
218         return $user;
219     }
220
221     function user_match_to($user, $to_hdr)
222     {
223         $incoming = $user->incomingemail;
224         $tos = mailparse_rfc822_parse_addresses($to_hdr);
225         foreach ($tos as $to) {
226             if (strcasecmp($incoming, $to['address']) == 0) {
227                 return true;
228             }
229         }
230         return false;
231     }
232
233     function handle_command($user, $from, $msg)
234     {
235         $inter = new CommandInterpreter();
236         $cmd = $inter->handle_command($user, $msg);
237         if ($cmd) {
238             $cmd->execute(new MailChannel($from));
239             return true;
240         }
241         return false;
242     }
243
244     function respond($from, $to, $response)
245     {
246
247         $headers['From'] = $to;
248         $headers['To'] = $from;
249         $headers['Subject'] = "Command complete";
250
251         return mail_send(array($from), $headers, $response);
252     }
253
254     function log($level, $msg)
255     {
256         common_log($level, 'MailDaemon: '.$msg);
257     }
258
259     function add_notice($user, $msg, $fileRecords)
260     {
261         $notice = Notice::saveNew($user->id, $msg, 'mail');
262         if (is_string($notice)) {
263             $this->log(LOG_ERR, $notice);
264             return $notice;
265         }
266         foreach($fileRecords as $fileRecord){
267             $this->attachFile($notice, $fileRecord);
268         }
269         common_broadcast_notice($notice);
270         $this->log(LOG_INFO,
271                    'Added notice ' . $notice->id . ' from user ' . $user->nickname);
272         return true;
273     }
274
275     function attachFile($notice, $filerec)
276     {   
277         File_to_post::processNew($filerec->id, $notice->id);
278
279         $this->maybeAddRedir($filerec->id,
280             common_local_url('file', array('notice' => $notice->id)));
281     }
282
283     function parse_message($fname)
284     {
285         $contents = file_get_contents($fname);
286         $parsed = Mail_mimeDecode::decode(array('input' => $contents,
287                                                 'include_bodies' => true,
288                                                 'decode_headers' => true,
289                                                 'decode_bodies' => true));
290         if (!$parsed) {
291             return null;
292         }
293
294         $from = $parsed->headers['from'];
295
296         $to = $parsed->headers['to'];
297
298         $type = $parsed->ctype_primary . '/' . $parsed->ctype_secondary;
299
300         $attachments = array();
301
302         $this->extract_part($parsed,$msg,$attachments);
303
304         return array($from, $to, $msg, $attachments);
305     }
306
307     function extract_part($parsed,&$msg,&$attachments){
308         if ($parsed->ctype_primary == 'multipart') {
309             if($parsed->ctype_secondary == 'alternative'){
310                 $altmsg = $this->extract_msg_from_multipart_alternative_part($parsed);
311                 if(!empty($altmsg)) $msg = $altmsg;
312             }else{
313                 foreach($parsed->parts as $part){
314                     $this->extract_part($part,$msg,$attachments);
315                 }
316             }
317         } else if ($parsed->ctype_primary == 'text'
318             && $parsed->ctype_secondary=='plain') {
319             $msg = $parsed->body;
320             if(strtolower($parsed->ctype_parameters['charset']) != "utf-8"){
321                 $msg = utf8_encode($msg);
322             }
323         }else if(!empty($parsed->body)){
324             if(common_config('attachments', 'uploads')){
325                 //only save attachments if uploads are enabled
326                 $attachment = tmpfile();
327                 fwrite($attachment, $parsed->body);
328                 $attachments[] = $attachment;
329             }
330         }
331     }
332
333     function extract_msg_from_multipart_alternative_part($parsed){
334         foreach ($parsed->parts as $part) {
335             $this->extract_part($part,$msg,$attachments);
336         }
337         //we don't want any attachments that are a result of this parsing
338         return $msg;
339     }
340
341     function unsupported_type($type)
342     {
343         $this->error(null, "Unsupported message type: " . $type);
344     }
345
346     function cleanup_msg($msg)
347     {
348         $lines = explode("\n", $msg);
349
350         $output = '';
351
352         foreach ($lines as $line) {
353             // skip quotes
354             if (preg_match('/^\s*>.*$/', $line)) {
355                 continue;
356             }
357             // skip start of quote
358             if (preg_match('/^\s*On.*wrote:\s*$/', $line)) {
359                 continue;
360             }
361             // probably interesting to someone, not us
362             if (preg_match('/^\s*Sent via/', $line)) {
363                 continue;
364             }
365             if (preg_match('/^\s*Sent from my/', $line)) {
366                 continue;
367             }
368
369             // skip everything after a sig
370             if (preg_match('/^\s*--+\s*$/', $line) ||
371                 preg_match('/^\s*__+\s*$/', $line))
372             {
373                 break;
374             }
375             // skip everything after Outlook quote
376             if (preg_match('/^\s*-+\s*Original Message\s*-+\s*$/', $line)) {
377                 break;
378             }
379             // skip everything after weird forward
380             if (preg_match('/^\s*Begin\s+forward/', $line)) {
381                 break;
382             }
383
384             $output .= ' ' . $line;
385         }
386
387         preg_replace('/\s+/', ' ', $output);
388         return trim($output);
389     }
390 }
391
392 if (common_config('emailpost', 'enabled')) {
393     $md = new MailerDaemon();
394     $md->handle_message('php://stdin');
395 }