/[drupal]/contributions/modules/mailsave/mailsave.module
ViewVC logotype

Contents of /contributions/modules/mailsave/mailsave.module

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.17 - (show annotations) (download) (as text)
Wed Aug 20 21:50:17 2008 UTC (15 months ago) by stuartgreenfield
Branch: MAIN
CVS Tags: DRUPAL-6--1-3, HEAD
Changes since 1.16: +2 -2 lines
File MIME type: text/x-php
Reported by mfb: fixes a potential vulnerability to mimetype spoofing that is corrected in Drupal 6.4 - this version of mailsave requires core 6.4 or higher in order to work.
1 <?php
2 // $Id: mailsave.module,v 1.16 2008/08/07 22:52:16 stuartgreenfield Exp $
3
4 /**
5 * This module interacts with mailhandler to save attachments from emails
6 * mailhandler.module is required
7 * upload.module must be enabled to allow attachments to be saved
8 * If image.module is available the first jpeg in a message can optionally cause the node to be created as an image type.
9 * Creation of image nodes and saving of attachments is managed via user access control privileges
10 */
11
12 // Some constant definitions to make later code clearer
13 // This value is defined to reflect the default filename created by mailhandler
14 define('MAILSAVE_UNNAMED_ATTACHMENT', 'unnamed_attachment');
15
16 /**
17 * Implementation of hook_help().
18 */
19 function mailsave_help($path, $arg) {
20
21 switch ($path) {
22
23 case 'admin/help#mailsave':
24
25 $output = '<p>' . t('<strong>mailsave</strong> works with <strong>mailhandler</strong> to detach files from incoming emails and attach them to the resulting nodes.') . '</p>';
26 $output .= '<p>' . t('If <strong>upload</strong> is installed you can allow users to submit files by email if they have both <em>save attachments</em> and <em>upload files</em> permissions.') . '</p>';
27 $output .= '<p>' . t('You can enable other modules, such as <strong>mailsave to image</strong>, to extend the functions of mailsave. For example, having messages with jpeg attachments automatically turned in to image nodes.') . '</p>';
28 return $output;
29
30 case 'admin/settings/mailsave':
31 $output = '<p>' . t('This page shows all the cleanup plug-ins that are available to mailhandler to carry out pre-processing of messages prior to saving them. These plug-ins are generally of most help when receiving messages that are submitted via a mobile phone multimedia messaging service (MMS) gateway.') . '</p>';
32 $output .= '<p>' . t('If additional modules have been installed that also provide clean up functions then these will not appear in this list. These modules must be enabled separately using the site\'s !admin.', array('!admin' => l(t('module adminstration page'), 'admin/build'))) . '</p>';
33 return $output;
34 }
35 }
36
37
38 /**
39 * Implementation of hook_perm
40 */
41 function mailsave_perm() {
42
43 return array(
44 'save attachments',
45 'administer mailsave',
46 );
47
48 }
49
50
51 /**
52 * Implementation of hook_mailhandler().
53 * Retrieve all attachments from the mail
54 * Then call mailsave handlers to process attachments
55 * Then try to store remaining attachments
56 */
57 function mailsave_mailhandler($node, $result, $i, $header, $mailbox) {
58
59 // Initialise attachments array
60 $attachments = array();
61
62 /**
63 * A legacy step follows as mailhandler never used to provide attachments.
64 * It now does, but in a slightly different structure to what mailsave used.
65 * This is a slightly lazy approach as we convert the mailhandler structure to
66 * mailsave - we could rewrite mailsave to use the new format natively, but that's
67 * for another day as it means updating all the mailsave modules.
68 */
69 // Create array of attachments that mailsave modules can use
70 $attachments = _mailsave_use_mailhandler_attachments($node);
71
72 // Link attachments to the node under mailsave_attachments
73 $node->mailsave_attachments = $attachments;
74
75 // Get the list of cleanup filters - it is returned grouped by country
76 foreach (_mailsave_build_cleanup_list() as $country => $cleanup) {
77
78 // Retrieve the array of active cleanup filters for this country from the variables table
79 $active_cleanup = variable_get('mailsave_'.$country, array());
80
81 // Go through the array of available clean-up filters for this country
82 foreach ($cleanup as $module => $filter) {
83
84 // See if the filter is active (uses module name as the keys in the array)
85 if ($active_cleanup[$module]) {
86
87 // If active, build the function name and call it
88 $function = $module .'_mailsave_clean';
89 $function($node, $result, $i, $header, $mailbox);
90 }
91 }
92 }
93
94 // Process the node through any other module that implements mailsave_clean
95 foreach (module_list() as $name) {
96 if (module_hook($name, 'mailsave_clean')) {
97 $function = $name .'_mailsave_clean';
98 $function($node, $result, $i, $header, $mailbox);
99 }
100 }
101
102 // See if any other module wants to try and react to the attachments
103 foreach (module_list() as $name) {
104 if (module_hook($name, 'mailsave')) {
105 $function = $name .'_mailsave';
106 if (!($node = $function($node, $result, $i, $header, $mailbox))) {
107 // Exit if a module has handled the submitted data.
108 break;
109 }
110 }
111 }
112
113 // Save remaining attachments that weren't handled elsewhere
114 _mailsave_save_files($node);
115
116 // Return the updated node
117 return $node;
118
119 }
120
121
122 /**
123 * Attach files to a post
124 * At the moment we go via $node->mailsave_attachments
125 * Maybe a little re-jig needed to give upload the format it wants
126 * Could probably go straight to $node->files at some point?
127 */
128 function _mailsave_save_files(&$node) {
129
130 // If $node->mailsave_attachments is empty or upload not installed just return
131 if (!$node->mailsave_attachments || !module_exists('upload')) {
132 return;
133 }
134
135 // If user doesn't have upload permission then don't bother processing
136 if (!(user_access('save attachments') && user_access('upload files'))) {
137 return;
138 }
139
140 // Convert $node->mailsave_attachments to $node->files ready for upload to use
141 foreach ($node->mailsave_attachments as $filekey => $attachment) {
142
143 global $user;
144
145 $limits = _upload_file_limits($user);
146 $validators = array(
147 'file_validate_extensions' => array($limits['extensions']),
148 'file_validate_image_resolution' => array($limits['resolution']),
149 'file_validate_size' => array($limits['file_size'], $limits['user_size']),
150 );
151
152 if ($file = _mailsave_save_file($attachment, $validators)) {
153 // Create the $node->files elements
154 $file->list = variable_get('upload_list_default', 1);
155 $file->description = $file->filename;
156 $node->files[$file->fid] = $file;
157
158 // This is a temporary line to get upload_save to work (see upload.module line 413)
159 // upload_save checks for either the presence of an old_vid, or the session variable, to determine
160 // if a new upload has been supplied and create a new entry in the database
161 $node->old_vid = 1;
162 }
163
164 }
165
166 // Destroy $node->mailsave_attachments now we have created $node->files
167 unset($node->mailsave_attachments);
168
169 }
170
171
172 /**
173 * mailsave_discard_attachment
174 * This function discards attachments with the specified name.
175 * It is typically used by the mailsave_clean hook to throw away logos or similar
176 * images that are attached by a service provider. As this is likely to be a common
177 * requirement of a clean routine it has been incorporated in to mailsave itself
178 * to avoid developers of future plug ins having to rewrite this over and over.
179 * Function does not return any vale
180 */
181 function mailsave_discard_attachment(&$node, $filename) {
182
183 foreach ($node->mailsave_attachments as $key => $attachment) {
184 if ($attachment['filename'] == $filename) {
185 unset($node->mailsave_attachments[$key]);
186 }
187 }
188
189 return;
190 }
191
192
193 /**
194 * Implementation of hook_menu
195 */
196 function mailsave_menu() {
197 $items = array();
198
199 $items['admin/settings/mailsave'] = array(
200 'title' => 'Mailsave',
201 'description' => 'Choose which e-mail and MMS clean up filters to apply to incoming messages.',
202 'page callback' => 'drupal_get_form',
203 'page arguments' => array('mailsave_admin_settings'),
204 'access arguments' => array('administer mailsave'),
205 );
206
207 return $items;
208 }
209
210
211 /**
212 * Present a form to allow the user to choose which clean up filters should be run
213 *
214 * It is done this way, rather than as discrete modules, to keep the module page short as there could
215 * be many filters available! It is possible to implement cleanup via a regular hook_mailsave_clean too
216 */
217 function mailsave_admin_settings() {
218
219 // Initialise an array
220 $form = array();
221
222 // _mailsave_build_cleanup_list returns available filters, grouped by country
223 foreach (_mailsave_build_cleanup_list() as $country => $cleanup) {
224
225 // Reset the options array for this country
226 $options = array();
227
228 // Go through each provider in turn and build the options group
229 foreach ($cleanup as $id => $filter) {
230 $options[$id] = $filter['provider'];
231 }
232
233 // Generate a set of checkboxes for this country
234 $form['mailsave_'. $country] = array(
235 '#type' => 'checkboxes',
236 '#title' => t('Providers - @country', array('@country' => $country)),
237 '#default_value' => variable_get('mailsave_'. $country, array()),
238 '#options' => $options,
239 );
240 }
241
242 // Return the form
243 return system_settings_form($form);
244
245 }
246
247
248 /**
249 * Return a list of available cleanup filters from the local cleanup directory
250 */
251 function _mailsave_build_cleanup_list() {
252
253 // Initialise an array to hold results
254 $cleanup_name = array();
255
256 // Load all modules from the cleanup directory
257 $path = drupal_get_path('module', 'mailsave') .'/cleanup';
258 $files = drupal_system_listing('.inc$', $path, 'name', 0);
259
260 // Process the list of files and include each one
261 foreach ($files as $file) {
262 require_once('./' . $file->filename);
263
264 // Build the function name to retrieve module information
265 $function = $file->name . '_mailsave_clean_info';
266
267 // If the function exists, call it, and get the results
268 if (function_exists($function)) {
269 $result = $function();
270
271 // If results are returned, and they are an array, merge them in to $cleanup_name
272 if (isset($result) && is_array($result)) {
273 $cleanup_name = array_merge($cleanup_name, $result);
274 }
275 }
276 }
277
278 // Group by country by creating a new array to make admin form easier to use
279 $cleanup_country = array();
280
281 // Go through each cleanup filter in turn
282 foreach ($cleanup_name as $name => $filter) {
283
284 // Build new array, using country as the first key
285 $cleanup_country[$filter['country']][$name] = $filter;
286
287 }
288
289 // Return result
290 return $cleanup_country;
291
292 }
293
294
295 /**
296 * Newer versions of mailhandler extract and decode mime parts
297 * Process the mailhandler attachments and return them in mailsave format
298 * to make them compatible with existing mailsave modules
299 * @TODO - with version six all other modules could be re-written to make this unnecessary
300 */
301 function _mailsave_use_mailhandler_attachments($node) {
302
303 // Initialise attachments array
304 $attachments = array();
305
306 // Parse each mime part in turn
307 foreach ($node->mimeparts as $mimepart) {
308
309 // Only return those parts that have a filename, or are non-text
310 // This is try and prevent unnamed text parts getting treated as attachments
311 if ($mimepart->filename != MAILSAVE_UNNAMED_ATTACHMENT || ((strpos($mimepart->filemime, 'TEXT') === FALSE) && (strpos($mimepart->filemime, 'MULTIPART') === FALSE))) {
312
313 // Save the data to temporary file
314 $temp_file = tempnam(file_directory_temp(), 'mail');
315 $filepath = file_save_data($mimepart->data, $temp_file);
316
317 // Add the item to the attachments array, and sanitise filename
318 $attachments[] = array(
319 'filename' => _mailsave_sanitise_filename($mimepart->filename),
320 'filepath' => $filepath,
321 'filemime' => strtolower($mimepart->filemime),
322 'filesize' => strlen($mimepart->data),
323 );
324 }
325 }
326
327 // Return the attachments
328 return $attachments;
329
330 }
331
332
333 // This started as a copy of file_save_upload
334 //function _mailsave_save_file($attachment, $source, $validators = array(), $dest = FALSE, $replace = FILE_EXISTS_RENAME) {
335 function _mailsave_save_file($attachment, $validators = array()) {
336
337 global $user;
338
339 // Add in our check of the the file name length.
340 $validators['file_validate_name_length'] = array();
341
342 // Build the list of non-munged extensions.
343 // @todo: this should not be here. we need to figure out the right place.
344 $extensions = '';
345 foreach ($user->roles as $rid => $name) {
346 $extensions .= ' '. variable_get("upload_extensions_$rid",
347 variable_get('upload_extensions_default', 'jpg jpeg gif png txt html doc xls pdf ppt pps odt ods odp'));
348 }
349
350 // Begin building file object.
351 $file = new stdClass();
352 $file->filename = file_munge_filename(trim(basename($attachment['filename']), '.'), $extensions);
353 $file->filepath = $attachment['filepath'];
354 $file->filemime = file_get_mimetype($file->filename);;
355
356 // Rename potentially executable files, to help prevent exploits.
357 if (preg_match('/\.(php|pl|py|cgi|asp|js)$/i', $file->filename) && (substr($file->filename, -4) != '.txt')) {
358 $file->filemime = 'text/plain';
359 $file->filepath .= '.txt';
360 $file->filename .= '.txt';
361 }
362
363 // Create temporary name/path for newly uploaded files.
364 //if (!$dest) {
365 $dest = file_destination(file_create_path($file->filename), FILE_EXISTS_RENAME);
366 //}
367 //$file->source = $source;
368 $file->destination = $dest;
369 $file->filesize = $attachment['filesize'];
370
371 // Call the validation functions.
372 $errors = array();
373 foreach ($validators as $function => $args) {
374 array_unshift($args, $file);
375 $errors = array_merge($errors, call_user_func_array($function, $args));
376 }
377
378 // Check for validation errors.
379 if (!empty($errors)) {
380 watchdog('mailhandler', 'The selected file %name could not be uploaded.', array('%name' => $file->filename), WATCHDOG_WARNING);
381 while ($errors) {
382 watchdog('mailhandler', array_shift($errors));
383 }
384 return 0;
385 }
386
387 // Move uploaded files from PHP's tmp_dir to Drupal's temporary directory.
388 // This overcomes open_basedir restrictions for future file operations.
389 $file->filepath = $file->destination;
390 if (!file_move($attachment['filepath'], $file->filepath)) {
391 watchdog('mailhandler', 'Upload error. Could not move file %file to destination %destination.', array('%file' => $file->filename, '%destination' => $file->filepath), WATCHDOG_ERROR);
392 return 0;
393 }
394
395 // If we made it this far it's safe to record this file in the database.
396 $file->uid = $user->uid;
397 $file->status = FILE_STATUS_TEMPORARY;
398 $file->timestamp = time();
399 drupal_write_record('files', $file);
400
401 // Return the results of the save operation
402 return $file;
403
404 }
405
406 /**
407 * Take a raw attachment filename, decode it if necessary, and strip out invalid characters
408 * Return a sanitised filename that should be ok for use by modules that want to save the file
409 */
410 function _mailsave_sanitise_filename($filename) {
411
412 // Decode multibyte encoded filename
413 $filename = mb_decode_mimeheader($filename);
414
415 // Replaces all characters up through space and all past ~ along with the above reserved characters to sanitise filename
416 // from php.net/manual/en/function.preg-replace.php#80431
417
418 // Define characters that are illegal on any of the 3 major OS's
419 $reserved = preg_quote('\/:*?"<>|', '/');
420
421 // Perform cleanup
422 $filename = preg_replace("/([\\x00-\\x20\\x7f-\\xff{$reserved}])/e", "_", $filename);
423
424 // Return the cleaned up filename
425 return $filename;
426 }

  ViewVC Help
Powered by ViewVC 1.1.2