4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
23 $helptext = <<<END_OF_HELP
24 Script for converting mail messages into notices. Takes message body
29 require_once INSTALLDIR.'/scripts/commandline.inc';
31 require_once(INSTALLDIR . '/lib/mail.php');
32 require_once('Mail/mimeDecode.php');
34 # FIXME: we use both Mail_mimeDecode and mailparse
35 # Need to move everything to mailparse
39 function __construct()
43 function handle_message($fname='php://stdin')
45 list($from, $to, $msg, $attachments) = $this->parse_message($fname);
46 if (!$from || !$to || !$msg) {
47 $this->error(null, _('Could not parse message.'));
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);
52 $this->error($from, _('Not a registered user.'));
55 if (!$this->user_match_to($user, $to)) {
56 $this->error($from, _('Sorry, that is not your incoming email address.'));
59 if (!$user->emailpost) {
60 $this->error($from, _('Sorry, no incoming email allowed.'));
63 $response = $this->handle_command($user, $from, $msg);
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()));
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.');
81 $filename = $this->saveFile($user, $attachment,$mimetype);
85 if (empty($filename)) {
86 $this->error($from,_('Couldn\'t save file.'));
89 $fileRecord = $this->storeFile($filename, $mimetype);
90 $fileRecords[] = $fileRecord;
91 $fileurl = common_local_url('attachment',
92 array('attachment' => $fileRecord->id));
94 // not sure this is necessary -- Zach
95 $this->maybeAddRedir($fileRecord->id, $fileurl);
97 $short_fileurl = common_shorten_url($fileurl);
98 $msg .= ' ' . $short_fileurl;
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()));
106 // Also, not sure this is necessary -- Zach
107 $this->maybeAddRedir($fileRecord->id, $short_fileurl);
110 $err = $this->add_notice($user, $msg, $fileRecords);
111 if (is_string($err)) {
112 $this->error($from, $err);
119 function saveFile($user, $attachment, $mimetype) {
121 $filename = File::filename($user->getProfile(), "email", $mimetype);
123 $filepath = File::path($filename);
125 $stream = stream_get_meta_data($attachment);
126 if (copy($stream['uri'], $filepath) && chmod($filepath,0664)) {
129 $this->error(null,_('File could not be moved to destination directory.' . $stream['uri'] . ' ' . $filepath));
133 function storeFile($filename, $mimetype) {
136 $file->filename = $filename;
138 $file->url = File::url($filename);
140 $filepath = File::path($filename);
142 $file->size = filesize($filepath);
143 $file->date = time();
144 $file->mimetype = $mimetype;
146 $file_id = $file->insert();
149 common_log_db_error($file, "INSERT", __FILE__);
150 $this->error(null,_('There was a database error while saving your file. Please try again.'));
156 function maybeAddRedir($file_id, $url)
158 $file_redir = File_redirection::staticGet('url', $url);
160 if (empty($file_redir)) {
161 $file_redir = new File_redirection;
162 $file_redir->url = $url;
163 $file_redir->file_id = $file_id;
165 $result = $file_redir->insert();
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.'));
174 function getUploadedFileType($fileHandle) {
175 require_once 'MIME/Type.php';
177 $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
178 $cmd = common_config('attachments', 'filecommand');
180 $stream = stream_get_meta_data($fileHandle);
181 $filetype = MIME_Type::autoDetect($stream['uri']);
182 if (in_array($filetype, common_config('attachments', 'supported'))) {
185 $media = MIME_Type::getMedia($filetype);
186 if ('application' !== $media) {
187 $hint = sprintf(_(' Try using another %s format.'), $media);
191 $this->error(null,sprintf(
192 _('%s is not a supported filetype on this server.'), $filetype) . $hint);
195 function isRespectsQuota($user,$fileSize) {
197 $ret = $file->isRespectsQuota($user,$fileSize);
198 if (true === $ret) return true;
199 $this->error(null,$ret);
202 function error($from, $msg)
204 file_put_contents("php://stderr", $msg . "\n");
208 function user_from($from_hdr)
210 $froms = mailparse_rfc822_parse_addresses($from_hdr);
215 $addr = common_canonical_email($from['address']);
216 $user = User::staticGet('email', $addr);
218 $user = User::staticGet('smsemail', $addr);
223 function user_match_to($user, $to_hdr)
225 $incoming = $user->incomingemail;
226 $tos = mailparse_rfc822_parse_addresses($to_hdr);
227 foreach ($tos as $to) {
228 if (strcasecmp($incoming, $to['address']) == 0) {
235 function handle_command($user, $from, $msg)
237 $inter = new CommandInterpreter();
238 $cmd = $inter->handle_command($user, $msg);
240 $cmd->execute(new MailChannel($from));
246 function respond($from, $to, $response)
249 $headers['From'] = $to;
250 $headers['To'] = $from;
251 $headers['Subject'] = "Command complete";
253 return mail_send(array($from), $headers, $response);
256 function log($level, $msg)
258 common_log($level, 'MailDaemon: '.$msg);
261 function add_notice($user, $msg, $fileRecords)
264 $notice = Notice::saveNew($user->id, $msg, 'mail');
265 } catch (Exception $e) {
266 $this->log(LOG_ERR, $e->getMessage());
267 return $e->getMessage();
269 foreach($fileRecords as $fileRecord){
270 $this->attachFile($notice, $fileRecord);
272 common_broadcast_notice($notice);
274 'Added notice ' . $notice->id . ' from user ' . $user->nickname);
278 function attachFile($notice, $filerec)
280 File_to_post::processNew($filerec->id, $notice->id);
282 $this->maybeAddRedir($filerec->id,
283 common_local_url('file', array('notice' => $notice->id)));
286 function parse_message($fname)
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));
297 $from = $parsed->headers['from'];
299 $to = $parsed->headers['to'];
301 $type = $parsed->ctype_primary . '/' . $parsed->ctype_secondary;
303 $attachments = array();
305 $this->extract_part($parsed,$msg,$attachments);
307 return array($from, $to, $msg, $attachments);
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;
316 foreach($parsed->parts as $part){
317 $this->extract_part($part,$msg,$attachments);
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);
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;
336 function extract_msg_from_multipart_alternative_part($parsed){
337 foreach ($parsed->parts as $part) {
338 $this->extract_part($part,$msg,$attachments);
340 //we don't want any attachments that are a result of this parsing
344 function unsupported_type($type)
346 $this->error(null, "Unsupported message type: " . $type);
349 function cleanup_msg($msg)
351 $lines = explode("\n", $msg);
355 foreach ($lines as $line) {
357 if (preg_match('/^\s*>.*$/', $line)) {
360 // skip start of quote
361 if (preg_match('/^\s*On.*wrote:\s*$/', $line)) {
364 // probably interesting to someone, not us
365 if (preg_match('/^\s*Sent via/', $line)) {
368 // skip everything after a sig
369 if (preg_match('/^\s*--+\s*$/', $line) ||
370 preg_match('/^\s*__+\s*$/', $line))
374 // skip everything after Outlook quote
375 if (preg_match('/^\s*-+\s*Original Message\s*-+\s*$/', $line)) {
378 // skip everything after weird forward
379 if (preg_match('/^\s*Begin\s+forward/', $line)) {
383 $output .= ' ' . $line;
386 preg_replace('/\s+/', ' ', $output);
387 return trim($output);
391 if (common_config('emailpost', 'enabled')) {
392 $md = new MailerDaemon();
393 $md->handle_message('php://stdin');