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 (mb_strlen($msg) > 140) {
70 $this->error($from,_('That\'s too long. '.
71 'Max notice size is 140 chars.'));
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.');
80 $filename = $this->saveFile($user, $attachment,$mimetype);
84 if (empty($filename)) {
85 $this->error($from,_('Couldn\'t save file.'));
88 $fileRecord = $this->storeFile($filename, $mimetype);
89 $fileRecords[] = $fileRecord;
90 $fileurl = common_local_url('attachment',
91 array('attachment' => $fileRecord->id));
93 // not sure this is necessary -- Zach
94 $this->maybeAddRedir($fileRecord->id, $fileurl);
96 $short_fileurl = common_shorten_url($fileurl);
97 $msg .= ' ' . $short_fileurl;
99 if (mb_strlen($msg) > 140) {
100 $this->deleteFile($filename);
101 $this->error($from,_('Max notice size is 140 chars, including attachment URL.'));
104 // Also, not sure this is necessary -- Zach
105 $this->maybeAddRedir($fileRecord->id, $short_fileurl);
108 $err = $this->add_notice($user, $msg, $fileRecords);
109 if (is_string($err)) {
110 $this->error($from, $err);
117 function saveFile($user, $attachment, $mimetype) {
119 $filename = File::filename($user->getProfile(), "email", $mimetype);
121 $filepath = File::path($filename);
123 $stream = stream_get_meta_data($attachment);
124 if (copy($stream['uri'], $filepath) && chmod($filepath,0664)) {
127 $this->error(null,_('File could not be moved to destination directory.' . $stream['uri'] . ' ' . $filepath));
131 function storeFile($filename, $mimetype) {
134 $file->filename = $filename;
136 $file->url = File::url($filename);
138 $filepath = File::path($filename);
140 $file->size = filesize($filepath);
141 $file->date = time();
142 $file->mimetype = $mimetype;
144 $file_id = $file->insert();
147 common_log_db_error($file, "INSERT", __FILE__);
148 $this->error(null,_('There was a database error while saving your file. Please try again.'));
154 function maybeAddRedir($file_id, $url)
156 $file_redir = File_redirection::staticGet('url', $url);
158 if (empty($file_redir)) {
159 $file_redir = new File_redirection;
160 $file_redir->url = $url;
161 $file_redir->file_id = $file_id;
163 $result = $file_redir->insert();
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.'));
172 function getUploadedFileType($fileHandle) {
173 require_once 'MIME/Type.php';
175 $cmd = &PEAR::getStaticProperty('MIME_Type', 'fileCmd');
176 $cmd = common_config('attachments', 'filecommand');
178 $stream = stream_get_meta_data($fileHandle);
179 $filetype = MIME_Type::autoDetect($stream['uri']);
180 if (in_array($filetype, common_config('attachments', 'supported'))) {
183 $media = MIME_Type::getMedia($filetype);
184 if ('application' !== $media) {
185 $hint = sprintf(_(' Try using another %s format.'), $media);
189 $this->error(null,sprintf(
190 _('%s is not a supported filetype on this server.'), $filetype) . $hint);
193 function isRespectsQuota($user,$fileSize) {
195 $ret = $file->isRespectsQuota($user,$fileSize);
196 if (true === $ret) return true;
197 $this->error(null,$ret);
200 function error($from, $msg)
202 file_put_contents("php://stderr", $msg . "\n");
206 function user_from($from_hdr)
208 $froms = mailparse_rfc822_parse_addresses($from_hdr);
213 $addr = common_canonical_email($from['address']);
214 $user = User::staticGet('email', $addr);
216 $user = User::staticGet('smsemail', $addr);
221 function user_match_to($user, $to_hdr)
223 $incoming = $user->incomingemail;
224 $tos = mailparse_rfc822_parse_addresses($to_hdr);
225 foreach ($tos as $to) {
226 if (strcasecmp($incoming, $to['address']) == 0) {
233 function handle_command($user, $from, $msg)
235 $inter = new CommandInterpreter();
236 $cmd = $inter->handle_command($user, $msg);
238 $cmd->execute(new MailChannel($from));
244 function respond($from, $to, $response)
247 $headers['From'] = $to;
248 $headers['To'] = $from;
249 $headers['Subject'] = "Command complete";
251 return mail_send(array($from), $headers, $response);
254 function log($level, $msg)
256 common_log($level, 'MailDaemon: '.$msg);
259 function add_notice($user, $msg, $fileRecords)
261 $notice = Notice::saveNew($user->id, $msg, 'mail');
262 if (is_string($notice)) {
263 $this->log(LOG_ERR, $notice);
266 foreach($fileRecords as $fileRecord){
267 $this->attachFile($notice, $fileRecord);
269 common_broadcast_notice($notice);
271 'Added notice ' . $notice->id . ' from user ' . $user->nickname);
275 function attachFile($notice, $filerec)
277 File_to_post::processNew($filerec->id, $notice->id);
279 $this->maybeAddRedir($filerec->id,
280 common_local_url('file', array('notice' => $notice->id)));
283 function parse_message($fname)
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));
294 $from = $parsed->headers['from'];
296 $to = $parsed->headers['to'];
298 $type = $parsed->ctype_primary . '/' . $parsed->ctype_secondary;
300 $attachments = array();
302 $this->extract_part($parsed,$msg,$attachments);
304 return array($from, $to, $msg, $attachments);
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;
313 foreach($parsed->parts as $part){
314 $this->extract_part($part,$msg,$attachments);
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);
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;
333 function extract_msg_from_multipart_alternative_part($parsed){
334 foreach ($parsed->parts as $part) {
335 $this->extract_part($part,$msg,$attachments);
337 //we don't want any attachments that are a result of this parsing
341 function unsupported_type($type)
343 $this->error(null, "Unsupported message type: " . $type);
346 function cleanup_msg($msg)
348 $lines = explode("\n", $msg);
352 foreach ($lines as $line) {
354 if (preg_match('/^\s*>.*$/', $line)) {
357 // skip start of quote
358 if (preg_match('/^\s*On.*wrote:\s*$/', $line)) {
361 // probably interesting to someone, not us
362 if (preg_match('/^\s*Sent via/', $line)) {
365 if (preg_match('/^\s*Sent from my/', $line)) {
369 // skip everything after a sig
370 if (preg_match('/^\s*--+\s*$/', $line) ||
371 preg_match('/^\s*__+\s*$/', $line))
375 // skip everything after Outlook quote
376 if (preg_match('/^\s*-+\s*Original Message\s*-+\s*$/', $line)) {
379 // skip everything after weird forward
380 if (preg_match('/^\s*Begin\s+forward/', $line)) {
384 $output .= ' ' . $line;
387 preg_replace('/\s+/', ' ', $output);
388 return trim($output);
392 if (common_config('emailpost', 'enabled')) {
393 $md = new MailerDaemon();
394 $md->handle_message('php://stdin');