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

Contents of /contributions/modules/mailhandler/mailhandler.module

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


Revision 1.87.2.18 - (show annotations) (download) (as text)
Thu Dec 25 13:01:20 2008 UTC (11 months ago) by zstolar
Branch: DRUPAL-5
Changes since 1.87.2.17: +4 -5 lines
File MIME type: text/x-php
Use actual sending time for the node creation timestamp
1 <?php
2 // $Id: mailhandler.module,v 1.87.2.17 2008/09/17 16:29:36 heine Exp $
3
4 /**
5 * Retrieve all msgs from a given mailbox and process them.
6 */
7 function mailhandler_retrieve($mailbox) {
8
9 if ($mailbox['domain']) {
10 if ($mailbox['imap'] == 1) {
11 $box = '{'. $mailbox['domain'] .':'. $mailbox['port'] . $mailbox['extraimap'] .'}'. $mailbox['folder'];
12 }
13 else {
14 $box = '{'. $mailbox['domain'] .':'. $mailbox['port'] .'/pop3'. $mailbox['extraimap'] .'}'. $mailbox['folder'];
15 }
16 $result = imap_open($box, $mailbox['name'], $mailbox['pass']);
17 $err = 'domain';
18 }
19 else {
20 $box = $mailbox['folder'];
21 $result = imap_open($box, '', '');
22 }
23
24 if ($result) {
25 $n = imap_num_msg($result);
26 $num_processed = 0;
27 for ($i = 1; $i <= $n; $i++) {
28 $header = imap_header($result, $i);
29
30 // only process new messages
31 if (!$mailbox['delete_after_read'] && $header->Unseen != 'U' && $header->Recent != 'N') {
32 continue;
33 }
34
35 $mime = explode(',', $mailbox['mime']);
36
37 // Get the first text part - this will be the node body
38 $origbody = mailhandler_get_part($result, $i, $mime[0]);
39
40 // If we didn't get a body from our first attempt, try the alternate format (HTML or PLAIN)
41 if (!$origbody) {
42 $origbody = mailhandler_get_part($result, $i, $mime[1]);
43 }
44
45 // Parse MIME parts, so all mailhandler modules have access to
46 // the full array of mime parts without having to process the email.
47 $mimeparts = mailhandler_get_parts($result, $i);
48
49 // Is this an empty message with no body and no mimeparts?
50 if (!$origbody && !$mimeparts) {
51 // @TODO: Log that we got an empty email?
52 continue;
53 }
54
55 $num_processed++;
56
57 // we must process before authenticating because the password may be in Commands
58 $node = mailhandler_process_message($header, $origbody, $mailbox);
59
60 // check if mail originates from an authenticated user
61 $node = mailhandler_authenticate($node, $header, $origbody, $mailbox);
62
63 // Put $mimeparts on the node
64 $node->mimeparts = $mimeparts;
65
66 // we need to change the current user
67 // this has to be done here to allow modules
68 // to create users
69 mailhandler_switch_user($node->uid);
70
71 // modules may override node elements before submitting. they do so by returning the node.
72 foreach (module_list() as $name) {
73 if (module_hook($name, 'mailhandler')) {
74 $function = $name .'_mailhandler';
75 if (!($node = $function($node, $result, $i, $header, $mailbox))) {
76 // Exit if a module has handled the submitted data.
77 break;
78 }
79 }
80 }
81
82 if ($node) {
83 if ($node->type == 'comment') {
84 mailhandler_comment_submit($node, $header, $mailbox, $origbody);
85 }
86 else {
87 mailhandler_node_submit($node, $header, $mailbox, $origbody);
88 }
89 }
90 // don't delete while we're only getting new messages
91 if ($mailbox['delete_after_read']) {
92 imap_delete($result, $i);
93 }
94
95 // switch back to original user
96 mailhandler_switch_user();
97 }
98 imap_close($result, CL_EXPUNGE);
99 return t('Mailhandler retrieve successful: %num_processed messages for %m', array('%num_processed' => $num_processed, '%m' => $mailbox['mail']));
100 }
101 else {
102 if ($err) {
103 watchdog('mailhandler', t('Mailhandler %c connection failed: %m', array('%c' => ($mailbox['imap'] ? 'imap' : 'POP3'), '%m' => $mailbox['mail'])), WATCHDOG_ERROR);
104 return t('Mailhandler %c connection failed: %m', array('%c' => ($mailbox['imap'] ? 'imap' : 'POP3'), '%m' => $mailbox['mail']));
105 }
106 else {
107 watchdog('mailhandler', t('Mailhandler: Could not access local folder: %m', array('%m' => $mailbox['mail'])), WATCHDOG_ERROR);
108 return t('Mailhandler could not access local folder: %m', array('%m' => $mailbox['mail']));
109 }
110 }
111 }
112
113 /**
114 * Create the comment.
115 */
116 function mailhandler_comment_submit($node, $header, $mailbox, $origbody) {
117 if (!$node->subject) $node->subject = $node->title;
118 if (!$node->comment) $node->comment = $node->body;
119 // We want the comment to have the email time, not the current time
120 $node->timestamp = $node->created;
121 // comment_save gets an array
122 $edit = (array)$node;
123
124 // post the comment. if unable, send a failure email when so configured
125 if (!comment_save($edit) && $mailbox['replies']) {
126 // $fromaddress really refers to the mail header which is authoritative for authentication
127 list($fromaddress, $fromname) = mailhandler_get_fromaddress($header, $mailbox);
128 $error_txt = t("Sorry, your comment experienced an error and was not posted. Possible reasons are\n- you have insufficient permission to post comments\n- The node is no longer open for comments.\n\n");
129 $error = $error_txt. t("\n\nYou sent:\n\nFrom: %f\nSubject: %t\nBody:\n%b", array('%f' => $fromaddress, '%t' => $header->subject, '%b' => $origbody));
130 drupal_mail('mailhandler_error_comment', $fromaddress, t('Email submission to %sn failed - %subj', array('%sn' => variable_get('site_name', 'Drupal'), '%subj' => $header->subject)));
131 $watchdog = t('Mailhandler: comment submission failure: %subject.', array('%subject' => $edit['subject']));
132 watchdog('mailhandler', $watchdog, WATCHDOG_ERROR);
133 }
134 }
135
136 /**
137 * Create the node.
138 */
139 // handle defaults for node creation (e.g. comment | promote | moderate | sticky fields)
140 $node_blog_default = variable_get('node_options_blog', array('status', 'promote'));
141 $node->status = in_array('status', $node_blog_default);
142 $node->promote = in_array('promote', $node_blog_default);
143 $node->moderate = in_array('moderate', $node_blog_default);
144 $node->revision = in_array('revision', $node_blog_default);
145 $node->comment = variable_get('comment_blog', 2);
146
147 function mailhandler_node_submit($node, $header, $mailbox, $origbody) {
148
149 list($fromaddress, $fromname) = mailhandler_get_fromaddress($header, $mailbox);
150
151 //dprint_r($node); //DEBUG
152
153 // Drupal 5.x & 6.x don't support multiple validations: each node_validate()
154 // call will ADD error messages to previous ones, so if some validation error
155 // occours in one message it will be reported in all messages after it.
156 // Since there is no way to reset form errors, the only method to avoid this
157 // problem is working with $_SESSION['messages'], used by form_set_error().
158 // See http://drupal.org/node/271975 for more info.
159 // Warning: with this method, if the same error message is reported for 2+ different
160 // fields it will be detected only for the last one.
161 if (!isset($_SESSION['messages'])) {
162 $_SESSION['messages'] = array();
163 }
164 $saved_errors = is_array($_SESSION['messages']['error']) ? $_SESSION['messages']['error'] : array();
165 $_SESSION['messages']['error'] = array();
166 node_validate($node);
167 $error = array();
168 if (count($_SESSION['messages']['error'])) {
169 $allerrors = form_get_errors();
170 foreach ($_SESSION['messages']['error'] as $message) {
171 $keys = array_keys($allerrors, $message);
172 if (!$keys || !count($keys)) {
173 // Not a validation error (but an error, i'll print it)
174 $saved_errors[] = $message;
175 } else {
176 // This is a validation error, i take the last field with it (previous fields
177 // should be about previous validations)
178 $error[$keys[count($keys) - 1]] = $message;
179 }
180 }
181 }
182 if (is_array($saved_errors) && count($saved_errors)) {
183 $_SESSION['messages']['error'] = $saved_errors;
184 }
185 else {
186 unset($_SESSION['messages']['error']);
187 }
188
189 if (!$error) {
190 // Prepare the node for save and allow modules make changes
191 $node = node_submit($node);
192 // Save the node
193 if ($node->nid) {
194 if (node_access('update', $node)) {
195 node_save($node);
196 watchdog('mailhandler', t("Mailhandler: Updated '%t' by %f", array('%t' => $node->title, '%f' => $fromaddress)), WATCHDOG_NOTICE);
197 }
198 else {
199 $errortxt = t("The e-mail address '%f' may not update %t items.", array('%f' => $fromaddress, '%t' => $node->type));
200 }
201 }
202 else {
203 if (node_access('create', $node)) {
204 node_save($node);
205 watchdog('mailhandler', t("Mailhandler: Added '%t' by %f", array('%t' => $node->title, '%f' => $fromaddress)), WATCHDOG_NOTICE);
206 }
207 else {
208 $errortxt = t("The e-mail address '%f' may not create %t items.", array('%f' => $fromaddress, '%t' => $node->type));
209 }
210 }
211 }
212 else {
213 $errortxt = t("Your submission is invalid: \n\n");
214 foreach ($error as $key => $value) {
215 $errortxt .= "$key: $value\n";
216 }
217 }
218
219 if ($errortxt) {
220 watchdog('mailhandler', "Mailhandler: $errortxt", WATCHDOG_ERROR);
221 if ($mailbox['replies']) {
222 $errortxt .= t("\n\nYou sent:\n\nFrom: %f\nSubject: %t\nBody:\n%b", array('%f' => $fromaddress, '%t' => $header->subject, '%b' => $origbody));
223 drupal_mail('mailhandler_error_node', $fromaddress, t('Email submission to %sn failed - %subj', array('%sn' => variable_get('site_name', 'Drupal'), '%subj' => $node->title)), $errortxt);
224 }
225 }
226 }
227
228 /**
229 * Append default commands. Separate commands from body. Strip signature.
230 * Return a node object.
231 */
232 function mailhandler_process_message($header, $body, $mailbox) {
233 $node = new stdClass();
234
235 // initialize params
236 $sep = $mailbox['sigseparator'];
237
238 // copy any name/value pairs from In-Reply-To or References e-mail headers to $node. Useful for maintaining threading info.
239 if ($header->references) {
240 // we want the final element in references header, watching out for white space
241 $threading = substr(strrchr($header->references, '<'), 0);
242 }
243 else if ($header->in_reply_to) {
244 $threading = str_replace(strstr($header->in_reply_to, '>'), '>', $header->in_reply_to); // Some MUAs send more info in that header.
245 }
246 if ($threading = rtrim(ltrim($threading, '<'), '>')) { //strip angle brackets
247 if ($threading) $node->threading = $threading;
248 parse_str($threading, $tmp);
249 if ($tmp['host']) {
250 $tmp['host'] = ltrim($tmp['host'], '@'); // strip unnecessary @ from 'host' element
251 }
252 foreach ($tmp as $key => $value) {
253 $node->$key = $value;
254 }
255 }
256
257 // prepend the default commands for this mailbox
258 if ($mailbox['commands']) {
259 $body = trim($mailbox['commands']) ."\n". $body;
260 }
261
262 // We set the type now, because we need it in the next block
263 if (!$node->type) $node->type = 'blog';
264
265 // Reset $node->taxonomy
266 $node->taxonomy = array();
267
268 // process the commands and the body
269 $lines = explode("\n", $body);
270 for ($i = 0; $i < count($lines); $i++) {
271 $line = trim($lines[$i]);
272 $words = explode(' ', $line);
273 // look for a command line. if not present, note which line number is the boundary
274 if (substr($words[0], -1) == ':' && is_null($endcommands)) {
275 // Looks like a name: value pair
276 $data = explode(': ', $line, 2);
277
278 //TODO: allow for nested arrays in commands ... Possibly trim() values after explode().
279 // if needed, turn this command value into an array
280 if (substr($data[1], 0, 1) == '[' && substr($data[1], -1, 1) == ']') {
281 $data[1] = rtrim(ltrim($data[1], '['), ']'); //strip brackets
282 $data[1] = explode(",", $data[1]);
283 }
284 $data[0] = strtolower(str_replace(' ', '_', $data[0]));
285 // if needed, map term names into IDs. this should move to taxonomy_mailhandler()
286 if ($data[0] == 'taxonomy' && !is_numeric($data[1][0])) {
287 array_walk($data[1], 'mailhandler_term_map');
288 $node->taxonomy = array_merge($node->taxonomy, $data[1]);
289 unset($data[0]);
290 }
291 else if (substr($data[0], 0, 9) == 'taxonomy[' && substr($data[0], -1, 1) == ']'){
292 // make sure a valid vid is passed in:
293 $vid = substr($data[0], 9, -1);
294 $vocabulary = taxonomy_get_vocabulary($vid);
295 // if the vocabulary is not activated for that node type, unset $data[0], so the command will be ommited from $node
296 // TODO: add an error message
297 if (!in_array($node->type, $vocabulary->nodes)) {
298 unset($data[0]);
299 }
300 else if (!$vocabulary->tags) {
301 array_walk($data[1], 'mailhandler_term_map');
302 $node->taxonomy = array_merge($node->taxonomy, $data[1]);
303 unset($data[0]);
304 }
305 else if ($vocabulary->tags) {
306 // for freetagging vocabularies, we just pass the list of terms
307 $node->taxonomy['tags'][$vid] = implode(',', $data[1]);
308 unset($data[0]); // unset, so it won't be included when populating the node object
309 }
310 }
311 if (!empty($data[0])) {
312 $node->$data[0] = $data[1];
313 }
314 }
315 else {
316 if (is_null($endcommands)) $endcommands = $i;
317 }
318
319 // stop when we encounter the sig. we'll discard all remaining text.
320 $start = substr($line, 0, strlen($sep)+3);
321 if ($sep && strstr($start, $sep)) { // mail clients sometimes prefix replies with ' >'
322 break;
323 }
324 }
325
326 // isolate the body from the commands and the sig
327 $tmp = array_slice($lines, $endcommands, $i - $endcommands);
328 // flatten and assign the body to node object. note that filter() is called within node_save() [tested with blog post]
329 $node->body = implode("\n", $tmp);
330
331 if (!$node->teaser) $node->teaser = node_teaser($node->body);
332
333 // decode encoded subject line
334 $subjectarr = imap_mime_header_decode($header->subject);
335 for ($i = 0; $i < count($subjectarr); $i++) {
336 if ($subjectarr[$i]->charset != 'default')
337 $node->title .= drupal_convert_to_utf8($subjectarr[$i]->text, $subjectarr[$i]->charset);
338 else
339 $node->title .= $subjectarr[$i]->text;
340 }
341
342 $node->date = format_date($header->udate, 'custom', 'Y-m-d H:i:s O');
343 $node->format = $mailbox['format'];
344
345 return $node;
346 }
347
348 /**
349 * Accept a taxonomy term name and replace with a tid. this belongs in taxonomy.module.
350 */
351 function mailhandler_term_map(&$term) {
352 // provide case insensitive and trimmed map so as to maximize likelihood of successful mapping
353 $term = db_result(db_query("SELECT tid FROM {term_data} WHERE LOWER('%s') LIKE LOWER(name)", trim($term)));
354 }
355
356 /**
357 * Determine who is the author of the upcoming node.
358 */
359 function mailhandler_authenticate($node, $header, $origbody, $mailbox) {
360
361 // $fromaddress really refers to the mail header which is authoritative for authentication
362 list($fromaddress, $fromname) = mailhandler_get_fromaddress($header, $mailbox);
363 if ($from_user = mailhandler_user_load($fromaddress, $node->pass, $mailbox)) {
364 $node->uid = $from_user->uid; // success!
365 $node->name = $from_user->name;
366 }
367 else if (function_exists('mailalias_user')) { // since $fromaddress failed, try e-mail aliases
368 $result = db_query("SELECT mail FROM {users} WHERE data LIKE '%%%s%%'", $fromaddress);
369 while ($alias = db_result($result)) {
370 if ($from_user = mailhandler_user_load($alias, $node->pass, $mailbox)) {
371 $node->uid = $from_user->uid; // success!
372 $node->name = $from_user->name;
373 break;
374 }
375 }
376 }
377 if (!$from_user) {
378 // failed authentication. we will still try to submit anonymously.
379 $node->uid = 0;
380 $node->name = $fromname; // use the name supplied in email headers
381 }
382 return $node;
383 }
384
385 /**
386 * Switch from original user to mail submision user and back.
387 *
388 * Note: You first need to run mailhandler_switch_user without
389 * argument to store the current user. Call mailhandler_switch_user
390 * without argument to set the user back to the original user.
391 *
392 * @param $uid The user ID to switch to
393 *
394 */
395 function mailhandler_switch_user($uid = NULL) {
396 global $user;
397 static $orig_user = array();
398
399 if (isset($uid)) {
400 session_save_session(FALSE);
401 $user = user_load(array('uid' => $uid));
402 }
403 // retrieve the initial user, can be called multiple times
404 else if (count($orig_user)) {
405 $user = array_shift($orig_user);
406 session_save_session(TRUE);
407 array_unshift($orig_user, $user);
408 }
409 // store the initial user
410 else {
411 $orig_user[] = $user;
412 }
413 }
414
415 /**
416 * Retrieve user information from his email address.
417 */
418 function mailhandler_user_load($mail, $pass, $mailbox) {
419 if ($mailbox['security'] == 1) {
420 return user_load(array('mail' => $mail, 'pass' => $pass));
421 }
422 else {
423 return user_load(array('mail' => $mail));
424 }
425 }
426
427 /**
428 * If available, use the mail header specified in mailbox config. otherwise use From: header
429 */
430 function mailhandler_get_fromaddress($header, $mailbox) {
431 if ($fromheader = strtolower($mailbox['fromheader']) && isset($header->$fromheader)) {
432 $from = $header->$fromheader;
433 }
434 else {
435 $from = $header->from;
436 }
437 return array($from[0]->mailbox .'@'. $from[0]->host, $from[0]->personal);
438 }
439
440 /**
441 * Returns the first part with the specified mime_type
442 *
443 * USAGE EXAMPLES - from php manual: imap_fetch_structure() comments
444 * $data = get_part($stream, $msg_number, "TEXT/PLAIN"); // get plain text
445 * $data = get_part($stream, $msg_number, "TEXT/HTML"); // get HTML text
446 */
447 function mailhandler_get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) {
448
449 if (!$structure) {
450 $structure = imap_fetchstructure($stream, $msg_number);
451 }
452 if ($structure) {
453 foreach ($structure->parameters as $parameter) {
454 if (strtoupper($parameter->attribute) == 'CHARSET') {
455 $encoding = $parameter->value;
456 //watchdog('mailhandler', 'Encoding is ' . $encoding);
457 }
458 }
459 if ($mime_type == mailhandler_get_mime_type($structure)) {
460 if (!$part_number) {
461 $part_number = '1';
462 }
463 $text = imap_fetchbody($stream, $msg_number, $part_number);
464 if ($structure->encoding == ENCBASE64) {
465 return drupal_convert_to_utf8(imap_base64($text), $encoding);
466 }
467 else if ($structure->encoding == ENCQUOTEDPRINTABLE) {
468 return drupal_convert_to_utf8(quoted_printable_decode($text), $encoding);
469 }
470 else {
471 return drupal_convert_to_utf8($text, $encoding);
472 }
473 }
474 if ($structure->type == TYPEMULTIPART) { /* multipart */
475 while (list($index, $sub_structure) = each ($structure->parts)) {
476 if ($part_number) {
477 $prefix = $part_number .'.';
478 }
479 $data = mailhandler_get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
480 if ($data) {
481 return $data;
482 }
483 }
484 }
485 }
486
487 return false;
488 }
489
490
491 /**
492 * Returns an array of parts as file objects
493 *
494 * @param
495 * @param $structure
496 * A message structure, usually used to recurse into specific parts
497 * @param $max_depth
498 * Maximum Depth to recurse into parts.
499 * @param $depth
500 * The current recursion depth.
501 * @param $part_number
502 * A message part number to track position in a message during recursion.
503 * @return
504 * An array of file objects.
505 */
506 function mailhandler_get_parts($stream, $msg_number, $max_depth = 10, $depth = 0, $structure = FALSE, $part_number = FALSE) {
507 $parts = array();
508
509 // Load Structure.
510 if (!$structure && !$structure = imap_fetchstructure($stream, $msg_number)) {
511 watchdog('mailhandler', t('Could not fetch structure for message number %msg_number', array('%msg_number' => $msg_number)), WATCHDOG_NOTICE);
512 return $parts;
513 }
514
515 // Recurse into multipart messages.
516 if ($structure->type == TYPEMULTIPART) {
517 // Restrict recursion depth.
518 if ($depth >= $max_depth) {
519 watchdog('mailhandler', t('Maximum recursion depths met in mailhander_get_structure_part for
520 message number %msg_number.', array('%msg_number' => $msg_number)), WATCHDOG_NOTICE);
521 return $parts;
522 }
523 foreach($structure->parts as $index => $sub_structure) {
524 // If a part number was passed in and we are a multitype message, prefix the
525 // the part number for the recursive call to match the imap4 dot seperated part indexing.
526 if ($part_number) {
527 $prefix = $part_number .'.';
528 }
529 $sub_parts = mailhandler_get_parts($stream, $msg_number, $max_depth, $depth + 1,
530 $sub_structure, $prefix . ($index + 1));
531 $parts = array_merge($parts, $sub_parts);
532 }
533 return $parts;
534 }
535
536 // Per Part Parsing.
537
538 // Initalize file object like part structure.
539 $part = new StdClass();
540 $part->attributes = array();
541 $part->filename = 'unnamed_attachment';
542 if (!$part->filemime = mailhandler_get_mime_type($structure)) {
543 watchdog('mailhandler', t('Could not fetch mime type for message part. Defaulting to application/octet-stream.'),
544 WATCHDOG_NOTICE);
545 $part->filemime = 'application/octet-stream';
546 }
547
548 if ($structure->ifparameters) {
549 foreach ($structure->parameters as $parameter) {
550 switch (strtoupper($parameter->attribute)) {
551 case 'NAME':
552 case 'FILENAME':
553 $part->filename = $parameter->value;
554 break;
555 default:
556 // put every thing else in the attributes array;
557 $part->attributes[$parameter->attribute] = $parameter->value;
558 }
559 }
560 }
561
562 // Handle Content-Disposition parameters for non-text types.
563 if ($structure->type != TYPETEXT && $structure->ifdparameters) {
564 foreach ($structure->dparameters as $parameter) {
565 switch (strtoupper($parameter->attribute)) {
566 case 'NAME':
567 case 'FILENAME':
568 $part->filename = $parameter->value;
569 break;
570 // put every thing else in the attributes array;
571 default:
572 $part->attributes[$parameter->attribute] = $parameter->value;
573 }
574 }
575 }
576
577 // Retrieve part convert MIME encoding to UTF-8
578 if(!$part->data = imap_fetchbody($stream, $msg_number, $part_number)) {
579 watchdog('mailhandler', 'No Data!!', WATCHDOG_ERROR);
580 return $parts;
581 }
582
583 // convert text attachment to UTF-8.
584 if ($structure->type == TYPETEXT) {
585 $part->data = imap_utf8($part->data);
586 }
587 else {
588 // If not text then decode as necessary
589 if ($structure->encoding == ENCBASE64) {
590 $part->data = imap_base64($part->data);
591 }
592 else if ($structure->encoding == ENCQUOTEDPRINTABLE) {
593 $part->data = quoted_printable_decode($part->data);
594 }
595 }
596
597 //always return an array to satisfy array_merge in recursion catch, and array return value.
598 $parts[] = $part;
599 return $parts;
600 }
601
602 /**
603 * Retrieve MIME type of the message structure.
604 */
605 function mailhandler_get_mime_type(&$structure) {
606 static $primary_mime_type = array('TEXT', 'MULTIPART', 'MESSAGE', 'APPLICATION', 'AUDIO', 'IMAGE', 'VIDEO', 'OTHER');
607 $type_id = (int)$structure->type;
608 if (isset($primary_mime_type[$type_id]) && !empty($structure->subtype)) {
609 return $primary_mime_type[$type_id] .'/'. $structure->subtype;
610 }
611 return 'TEXT/PLAIN';
612 }
613
614 /**
615 * Implementation of hook_cron(). Process msgs from all enabled mailboxes.
616 */
617 function mailhandler_cron() {
618 // store the original cron user
619 mailhandler_switch_user();
620 $result = db_query('SELECT * FROM {mailhandler} WHERE enabled = 1 ORDER BY mail');
621 while ($mailbox = db_fetch_array($result)) {
622 mailhandler_retrieve($mailbox);
623 }
624 // revert to the original cron user
625 mailhandler_switch_user();
626 }
627
628 /**
629 * Implementation of hook_perm().
630 */
631 function mailhandler_perm() {
632 return array('administer mailhandler');
633 }
634
635 /**
636 * Implementation of hook_menu().
637 */
638 function mailhandler_menu($may_cache) {
639 $items = array();
640 $admin_access = user_access('administer mailhandler');
641
642 if ($may_cache) {
643 $items[] = array('path' => 'admin/content/mailhandler', 'title' => t('Mailhandler'),
644 'callback' => 'mailhandler_admin',
645 'description' => t('Manage mailboxes and retrieve messages.'),
646 'access' => $admin_access);
647 $items[] = array('path' => 'admin/content/mailhandler/retrieve', 'title' => t('Retrieve'),
648 'callback' => 'mailhandler_admin_retrieve',
649 'access' => $admin_access,
650 'type' => MENU_CALLBACK);
651 $items[] = array('path' => 'admin/content/mailhandler/edit', 'title' => t('Edit mailbox'),
652 'callback' => 'mailhandler_admin_edit',
653 'access' => $admin_access,
654 'type' => MENU_CALLBACK);
655 $items[] = array('path' => 'admin/content/mailhandler/delete', 'title' => t('Delete mailbox'),
656 'callback' => 'drupal_get_form',
657 'callback arguments' => array('mailhandler_admin_delete_confirm'),
658 'access' => $admin_access,
659 'type' => MENU_CALLBACK);
660 $items[] = array('path' => 'admin/content/mailhandler/list', 'title' => t('List'),
661 'type' => MENU_DEFAULT_LOCAL_TASK,
662 'weight' => -10,
663 'access' => $admin_access);
664 $items[] = array('path' => 'admin/content/mailhandler/add', 'title' => t('Add mailbox'),
665 'callback' => 'mailhandler_admin_edit',
666 'access' => $admin_access,
667 'type' => MENU_LOCAL_TASK);
668 }
669 else {
670 drupal_add_css(drupal_get_path('module', 'mailhandler') .'/mailhandler.css');
671 }
672
673 return $items;
674 }
675
676 /**
677 * Menu callback; presents an overview of all URL aliases.
678 */
679 function mailhandler_admin() {
680 return mailhandler_display();
681 }
682
683 /**
684 * Return a listing of all defined mailboxes.
685 */
686 function mailhandler_display() {
687 $destination = drupal_get_destination();
688 $header = array(t('Mailbox'), t('Folder'), array('data' => t('Operations'), 'colspan' => 3));
689 $rows = array();
690 $result = db_query('SELECT * FROM {mailhandler} ORDER BY mail');
691 while ($mailbox = db_fetch_object($result)) {
692 $rows[] = array(
693 "<a href=\"mailto:$mailbox->mail\">$mailbox->mail</a>",
694 $mailbox->folder ? check_plain($mailbox->folder) : '',
695 l(t('Retrieve'), "admin/content/mailhandler/retrieve/$mailbox->mid", array('title' => t('Retrieve and process pending e-mails in this mailbox')), $destination),
696 l(t('Edit'), "admin/content/mailhandler/edit/$mailbox->mid", array('title' => t('Edit this mailbox configuration')), $destination),
697 l(t('Delete'), "admin/content/mailhandler/delete/$mailbox->mid", array('title' => t('Delete this mailbox')), $destination)
698 );
699 }
700
701 if (empty($rows)) {
702 $rows[] = array(array('data' => t('No mailboxes available.'), 'colspan' => '4'));
703 }
704
705 return theme('table', $header, $rows);
706 }
707
708 /**
709 * Menu callback; Retrieve and process pending e-mails for a mailbox.
710 */
711 function mailhandler_admin_retrieve($mid = 0) {
712 // store the original user
713 mailhandler_switch_user();
714 drupal_set_message(mailhandler_retrieve(mailhandler_get_mailbox($mid)));
715 $output = mailhandler_display();
716 // revert to the original user
717 mailhandler_switch_user();
718 return $output;
719 }
720
721 /**
722 * Menu callback; handles pages for creating and editing mailboxes.
723 */
724 function mailhandler_admin_edit($mid = 0) {
725 if ($mid) {
726 $output = drupal_get_form('mailhandler_form', mailhandler_get_mailbox($mid));
727 }
728 else {
729 $output = drupal_get_form('mailhandler_form');
730 }
731 return $output;
732 }
733
734 /**
735 * Fetch a specific mailbox from the database.
736 */
737 function mailhandler_get_mailbox($mid) {
738 return db_fetch_array(db_query("SELECT * FROM {mailhandler} WHERE mid = %d", $mid));
739 }
740
741 /**
742 * Return a form for editing or creating an individual mailbox.
743 */
744 function mailhandler_form($edit = array()) {
745 if (empty($edit['folder'])) {
746 $edit['folder'] = 'INBOX';
747 }
748
749 $form['mail'] = array('#type' => 'textfield', '#title' => t('E-mail address'), '#default_value' => $edit['mail'], '#description' => t('The e-mail address to which users should send their submissions.'), '#required' => TRUE);
750 $form['mailto'] = array('#type' => 'textfield', '#title' => t('Second E-mail address'), '#default_value' => $edit['mailto'], '#description' => t('Optional. The e-mail address to which modules should send generated content.'));
751 $form['folder'] = array('#type' => 'textfield', '#title' => t('Folder'), '#default_value' => $edit['folder'], '#description' => t('Optional. The folder where the mail is stored. If you want this mailbox to read from a local folder, give the full path. Leave domain, port, name, and pass empty below. Remember to set the folder to readable and writable by the webserver.'));
752 $form['imap'] = array('#type' => 'select', '#title' => t('POP3 or IMAP Mailbox'), '#options' => array('POP3', 'IMAP'), '#default_value' => $edit['imap'], '#description' => t('If you wish to retrieve mail from a POP3 or IMAP mailbox instead of a Folder, select POP3 or IMAP. Also, complete the Mailbox items below.'));
753 $form['domain'] = array('#type' => 'textfield', '#title' => t('Mailbox domain'), '#default_value' => $edit['domain'], '#description' => t('The domain of the server used to collect mail.'));
754 $form['port'] = array('#type' => 'textfield', '#title' => t('Mailbox port'), '#size' => 5, '#maxlength' => 5, '#default_value' => $edit['port'], '#description' => t('The port of the mailbox used to collect mail (usually 110 for POP3, 143 for IMAP).'));
755 $form['name'] = array('#type' => 'textfield', '#title' => t('Mailbox username'), '#default_value' => $edit['name'], '#description' => t('This username is used while logging into this mailbox during mail retrieval.'));
756 $form['pass'] = array('#type' => 'textfield', '#title' => t('Mailbox password'), '#default_value' => $edit['pass'], '#description' => t('The password corresponding to the username above. Consider using a non-vital password, since this field is stored without encryption in the database.'));
757
758 // Allow administrators to configure the mailbox with extra IMAP commands (notls, novalidate-cert etc.)
759 $form['extraimap'] = array('#type' => 'textfield', '#title' => t('Extra commands'), '#default_value' => $edit['extraimap'], '#description' => t('Optional. In some circumstances you need to issue extra commands to connect to your mail server (e.g. "/notls", "/novalidate-cert" etc.). See documentation for <a href="http://php.net/imap_open">imap_open</a>. Begin the string with a "/", separating each subsequent command with another "/".'));
760 $form['mime'] = array('#type' => 'select', '#title' => t('Mime preference'), '#options' => array('TEXT/HTML,TEXT/PLAIN' => 'HTML', 'TEXT/PLAIN,TEXT/HTML' => t('Plain text')), '#default_value' => $edit['mime'], '#description' => t('When a user sends an e-mail containing both HTML and plain text parts, use this part as the node body.'));
761 $form['security'] = array('#type' => 'radios', '#title' => t('Security'), '#options' => array(t('Disabled'), t('Require password')), '#default_value' => $edit['security'], '#description' => t('Disable security if your site does not require a password in the Commands section of incoming e-mails. Note: Security=Enabled and Mime preference=HTML is an unsupported combination.'));
762 $form['replies'] = array('#type' => 'radios', '#title' => t('Send error replies'), '#options' => array(t('Disabled'), t('Enabled')), '#default_value' => $edit['replies'], '#description' => t('Send helpful replies to all unsuccessful e-mail submissions. Consider disabling when a listserv posts to this mailbox.'));
763 $form['fromheader'] = array('#type' => 'textfield', '#title' => t('From header'), '#default_value' => $edit['fromheader'], '#description' => t('Use this e-mail header to determine the author of the resulting node. Admins usually leave this field blank (thus using the <strong>From</strong> header), but <strong>Sender</strong> is also useful when working with listservs.'));
764 $form['commands'] = array('#type' => 'textarea', '#title' => t('Default commands'), '#default_value' => $edit['commands'], '#description' => t('A set of commands which are added to each message. One command per line. See !link.', array('!link' => l(t('Commands'), 'admin/help/mailhandler#commands'))));
765 $form['sigseparator'] = array('#type' => 'textfield', '#title' => t('Signature separator'), '#default_value' => $edit['sigseparator'], '#description' => t('All text after this string will be discarded. A typical value is <strong>"-- "</strong> that is two dashes followed by a blank in an otherwise empty line. Leave blank to include signature text in nodes.'));
766 $form['delete_after_read'] = array('#type' => 'checkbox', '#title' => t('Delete messages after they are processed?'), '#default_value' => $edit['delete_after_read'], '#description' => t('Uncheck this box to leave read messages in the mailbox. They will not be processed again unless they become marked as unread.'));
767 $form['enabled'] = array('#type' => 'radios', '#title' => t('Cron processing'), '#options' => array(t('Disabled'), t('Enabled')), '#default_value' => $edit['enabled'], '#description' => t('Select disable to temporarily stop cron processing for this mailbox.'));
768
769 // Allow administrators to select the format of saved nodes/comments
770 $form['format'] = filter_form($edit['format']);
771
772 if ($edit['mid']) {
773 $form['mid'] = array('#type' => 'hidden', '#value' => $edit['mid']);
774 $form['submit'] = array('#type' => 'submit', '#value' => t('Update mailbox'));
775 }
776 else {
777 $form['submit'] = array('#type' => 'submit', '#value' => t('Create new mailbox'));
778 }
779
780 return $form;
781 }
782
783 /**
784 * Verify that the Mailbox is valid, and save it to the database.
785 */
786 function mailhandler_form_validate($form_id, $edit) {
787 if ($error = user_validate_mail($edit['mail'])) {
788 form_set_error('mail', $error);
789 }
790 if ($edit['mailto'] && ($error = user_validate_mail($edit['mailto']))) {
791 form_set_error('mailto', $error);
792 }
793 if ($edit['domain'] && $edit['port'] && !is_numeric($edit['port'])) { // assume external mailbox
794 form_set_error('port', t('Mailbox port must be an integer.'));
795 }
796
797 if (!$edit['domain'] && !$edit['port'] && $edit['folder']) { // assume local folder
798 // check read and write permission
799 if (!is_readable($edit['folder']) || !is_writable($edit['folder'])) {
800 form_set_error('port', t('The local folder has to be readable and writable by owner of the webserver process, e.g. nobody.'));
801 }
802 }
803 }
804
805 /**
806 * Save the Mailbox to the database.
807 */
808 function mailhandler_form_submit($form_id, $edit) {
809 if ($edit['mid']) {
810 // Includes fields to allow administrators to add extra IMAP commands,
811 // and select the format of saved nodes/comments
812 db_query("UPDATE {mailhandler} SET mail = '%s', mailto = '%s', domain = '%s', port = %d, folder = '%s', name = '%s', pass = '%s', extraimap = '%s', mime = '%s', imap = '%s', security = %d, replies = %d, fromheader = '%s', commands = '%s', sigseparator = '%s', enabled = %d, delete_after_read = %d, format = %d WHERE mid = %d", $edit['mail'], $edit['mailto'], $edit['domain'], $edit['port'], $edit['folder'], $edit['name'], $edit['pass'], $edit['extraimap'], $edit['mime'], $edit['imap'], $edit['security'], $edit['replies'], $edit['fromheader'], $edit['commands'], $edit['sigseparator'], $edit['enabled'], $edit['delete_after_read'], $edit['format'], $edit['mid']);
813 drupal_set_message(t('Mailbox updated'));
814 }
815 else {
816 // Includes fields to allow administrators to add extra IMAP commands,
817 // and select the format of saved nodes/comments
818 db_query("INSERT INTO {mailhandler} (mail, mailto, domain, port, folder, name, pass, extraimap, mime, imap, security, replies, fromheader, commands, sigseparator, enabled, delete_after_read, format) VALUES ('%s', '%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', %d, %d, %d)", $edit['mail'], $edit['mailto'], $edit['domain'], $edit['port'], $edit['folder'], $edit['name'], $edit['pass'], $edit['extraimap'], $edit['mime'], $edit['imap'], $edit['security'], $edit['replies'], $edit['fromheader'], $edit['commands'], $edit['sigseparator'], $edit['enabled'], $edit['delete_after_read'], $edit['format']);
819 drupal_set_message(t('Mailbox added'));
820 }
821 return 'admin/content/mailhandler';
822 }
823
824 /**
825 * Confirm/Delete Mailbox
826 */
827
828 function mailhandler_admin_delete_confirm($mid) {
829 $info = db_fetch_object(db_query("SELECT mid, mail FROM {mailhandler} WHERE mid = %d", $mid));
830 $form = array();
831 $form['mid'] = array('#type' => 'hidden', '#value' => $mid);
832 return confirm_form($form,
833 t('Do you wish to delete mailbox %mailbox?', array('%mailbox' => $info->mail)),
834 'admin/content/mailhandler',
835 t('This action cannot be undone.'),
836 t('Delete'),
837 t('Cancel')
838 );
839 }
840
841 function mailhandler_admin_delete_confirm_submit($form_id, $form_values) {
842 $info = db_fetch_object(db_query("SELECT mid, mail FROM {mailhandler} WHERE mid = %d", $form_values['mid']));
843 db_query("DELETE FROM {mailhandler} WHERE mid = %d", $form_values['mid']);
844 watchdog('mailhandler', t('Mailhandler: Mailbox %mailbox deleted', array('%mailbox' => $info->mail)), WATCHDOG_NOTICE);
845 drupal_set_message(t('Mailbox %mailbox deleted', array('%mailbox' => $info->mail)));
846 drupal_goto('admin/content/mailhandler');
847 }
848
849 /**
850 * Implementation of hook_help().
851 */
852 function mailhandler_help($section = 'admin/help#mailhandler') {
853 $output = '';
854 $link->add = l(t('Add mailbox'), 'admin/content/mailhandler/add');
855
856 // Gather examples of useful commands, and build a definition list with them:
857 $commands[] = array('command' => 'taxonomy: [term1, term2]',
858 'description' => t('Use this to add the terms <em>term1</em> and <em>term2</em> to the node.<br />
859 Both of the terms should already exist. In case they do not exist already, they will be quietly ommitted'));
860 $commands[] = array('command' => 'taxonomy[v]: [term1, term2]',
861 'description' => t('Similar to the above: adds the terms <em>term1</em> and <em>term2</em> to the node, but uses the vocabulary with the vocabulary id <em>v</em>. For example <em>taxonomy[3]</em> will chose only terms from the vocabulary which id is 3.<br />
862 In case some of the terms do not exist already, the behavior will depend on whether the vocabulary is a free tagging vocabulary or not. If it is a free tagging vocabulary, the term will be added, otherwise, it will be quietly ommitted'));
863
864 $commands_list = '<dl>';
865 foreach ($commands as $command) {
866 $commands_list .= '<dt>'. $command['command'] .'</dt>';
867 $commands_list .= '<dl>'. $command['description'] .'</dl>';
868 }
869 $commands_list .= '</dl>';
870
871 switch ($section) {
872 case 'admin/help#mailhandler':
873 $output = '<p>'. t('The mailhandler module allows registered users to create or edit nodes and comments via e-mail. Users may post taxonomy terms, teasers, and other post attributes using the mail commands capability. This module is useful because e-mail is the preferred method of communication by community members.') .'</p>';
874 $output .= '<p>'. t('The mailhandler module requires the use of a custom mailbox. Administrators can add mailboxes that should be customized to meet the needs of a mailing list. This mailbox will then be checked on every cron job. Administrators may also initiate a manual retrieval of messages.') .'</p>';
875 $output .= '<p>'. t('This is particularly useful when you want multiple sets of default commands. For example , if you want to authenticate based on a non-standard mail header like Sender: which is useful for accepting submissions from a listserv. Authentication is usually based on the From: e-mail address. Administrators can edit the individual mailboxes when they administer mailhandler.') .'</p>';
876 $output .= t('<p>You can</p>
877 <ul>
878 <li>run the cron job at cron.php.</li>
879 <li>add a mailbox at <a href="@admin-mailhandler-add">administer &gt;&gt; mailhandler &gt;&gt; add a mailbox.</a></li>
880 <li>administer mailhandler at <a href="@admin-mailhandler">administer &gt;&gt; mailhandler</a>.</li>
881 <li>set default commands, (password, type, taxonomy, promote, status), for how to work with incoming mail at <a href="%admin-mailhandler">admin >> mailhandler</a> select <strong>edit</strong> for the email address being handled. Set commands in the default command field.</li>
882 <li>post email, such as from a mailing list, to a forum by adding the term id (number found in the URL) to the default commands using <strong>tid: #</strong>.', array('@admin-mailhandler-add' => url('admin/content/mailhandler/add'), '@admin-mailhandler' => url('admin/content/mailhandler'))) .'</ul>';
883 $output .= '<h3 id="commands">'. t('Useful Commands') .'</h3>';
884 $output .= $commands_list;
885 $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%mailhandler">Mailhandler page</a>.', array('%mailhandler' => 'http://www.drupal.org/handbook/modules/mailhandler/')) .'</p>';
886 return $output;
887 case 'admin/content/mailhandler':
888 return t('The mailhandler module allows registered users to create or edit nodes and comments via email. Authentication is usually based on the From: email address. There is also an email filter that can be used to prettify incoming email. Users may post taxonomy terms, teasers, and other node parameters using the Command capability.');
889 case 'admin/content/mailhandler/add':
890 return t('Add a mailbox whose mail you wish to import into Drupal. Can be IMAP, POP3, or local folder.');
891 }
892 }

  ViewVC Help
Powered by ViewVC 1.1.2