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