source: subversion/trunk/roundcubemail/program/steps/mail/compose.inc @ 5403

Last change on this file since 5403 was 5403, checked in by thomasb, 19 months ago

Consider replication delays in session storage

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 47.4 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/steps/mail/compose.inc                                        |
6 |                                                                       |
7 | This file is part of the Roundcube Webmail client                     |
8 | Copyright (C) 2005-2011, The Roundcube Dev Team                       |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Compose a new mail message with all headers and attachments         |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22// define constants for message compose mode
23define('RCUBE_COMPOSE_REPLY', 0x0106);
24define('RCUBE_COMPOSE_FORWARD', 0x0107);
25define('RCUBE_COMPOSE_DRAFT', 0x0108);
26define('RCUBE_COMPOSE_EDIT', 0x0109);
27
28$MESSAGE_FORM = NULL;
29$MESSAGE = NULL;
30
31$COMPOSE_ID = get_input_value('_id', RCUBE_INPUT_GET);
32$_SESSION['compose'] = $_SESSION['compose_data_'.$COMPOSE_ID];
33
34// give replicated session storage some time to synchronize
35$retries = 0;
36while ($COMPOSE_ID && !is_array($_SESSION['compose']) && $RCMAIL->db->is_replicated() && $retries++ < 5) {
37  usleep(500000);
38  $RCMAIL->session->reload();
39  $_SESSION['compose'] = $_SESSION['compose_data_'.$COMPOSE_ID];
40}
41
42// Nothing below is called during message composition, only at "new/forward/reply/draft" initialization or
43// if a compose-ID is given (i.e. when the compose step is opened in a new window/tab).
44if (!is_array($_SESSION['compose']))
45{
46  // Infinite redirect prevention in case of broken session (#1487028)
47  if ($COMPOSE_ID)
48    raise_error(array('code' => 500, 'type' => 'php',
49      'file' => __FILE__, 'line' => __LINE__,
50      'message' => "Invalid compose ID"), true, true);
51
52  $_SESSION['compose'] = array(
53    'id' => uniqid(mt_rand()),
54    'param' => request2param(RCUBE_INPUT_GET),
55    'mailbox' => $IMAP->get_mailbox_name(),
56  );
57
58  // process values like "mailto:foo@bar.com?subject=new+message&cc=another"
59  if ($_SESSION['compose']['param']['to']) {
60    // #1486037: remove "mailto:" prefix
61    $_SESSION['compose']['param']['to'] = preg_replace('/^mailto:/i', '', $_SESSION['compose']['param']['to']);
62    $mailto = explode('?', $_SESSION['compose']['param']['to']);
63    if (count($mailto) > 1) {
64      $_SESSION['compose']['param']['to'] = $mailto[0];
65      parse_str($mailto[1], $query);
66      foreach ($query as $f => $val)
67        $_SESSION['compose']['param'][$f] = $val;
68    }
69  }
70
71  // select folder where to save the sent message
72  $_SESSION['compose']['param']['sent_mbox'] = $RCMAIL->config->get('sent_mbox');
73
74  // pipe compose parameters thru plugins
75  $plugin = $RCMAIL->plugins->exec_hook('message_compose', $_SESSION['compose']);
76  $_SESSION['compose']['param'] = array_merge($_SESSION['compose']['param'], $plugin['param']);
77
78  // add attachments listed by message_compose hook
79  if (is_array($plugin['attachments'])) {
80    foreach ($plugin['attachments'] as $attach) {
81      // we have structured data
82      if (is_array($attach)) {
83        $attachment = $attach;
84      }
85      // only a file path is given
86      else {
87        $filename = basename($attach);
88        $attachment = array(
89          'group' => $COMPOSE_ID,
90          'name' => $filename,
91          'mimetype' => rc_mime_content_type($attach, $filename),
92          'path' => $attach,
93        );
94      }
95
96      // save attachment if valid
97      if (($attachment['data'] && $attachment['name']) || ($attachment['path'] && file_exists($attachment['path']))) {
98        $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
99      }
100
101      if ($attachment['status'] && !$attachment['abort']) {
102        unset($attachment['data'], $attachment['status'], $attachment['abort']);
103        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
104      }
105    }
106  }
107
108  // check if folder for saving sent messages exists and is subscribed (#1486802)
109  if ($sent_folder = $_SESSION['compose']['param']['sent_mbox']) {
110    rcmail_check_sent_folder($sent_folder, true);
111  }
112
113  // redirect to a unique URL with all parameters stored in session
114  $OUTPUT->redirect(array('_action' => 'compose', '_id' => $_SESSION['compose']['id']));
115}
116
117
118// add some labels to client
119$OUTPUT->add_label('nosubject', 'nosenderwarning', 'norecipientwarning', 'nosubjectwarning', 'cancel',
120    'nobodywarning', 'notsentwarning', 'notuploadedwarning', 'savingmessage', 'sendingmessage',
121    'messagesaved', 'converting', 'editorwarning', 'searching', 'uploading', 'uploadingmany',
122    'fileuploaderror');
123
124$OUTPUT->set_env('compose_id', $COMPOSE_ID);
125
126// add config parameters to client script
127if (!empty($CONFIG['drafts_mbox'])) {
128  $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
129  $OUTPUT->set_env('draft_autosave', $CONFIG['draft_autosave']);
130}
131// set current mailbox in client environment
132$OUTPUT->set_env('mailbox', $IMAP->get_mailbox_name());
133$OUTPUT->set_env('sig_above', $RCMAIL->config->get('sig_above', false));
134$OUTPUT->set_env('top_posting', $RCMAIL->config->get('top_posting', false));
135$OUTPUT->set_env('recipients_separator', trim($RCMAIL->config->get('recipients_separator', ',')));
136
137// get reference message and set compose mode
138if ($msg_uid = $_SESSION['compose']['param']['draft_uid']) {
139  $RCMAIL->imap->set_mailbox($CONFIG['drafts_mbox']);
140  $compose_mode = RCUBE_COMPOSE_DRAFT;
141}
142else if ($msg_uid = $_SESSION['compose']['param']['reply_uid'])
143  $compose_mode = RCUBE_COMPOSE_REPLY;
144else if ($msg_uid = $_SESSION['compose']['param']['forward_uid'])
145  $compose_mode = RCUBE_COMPOSE_FORWARD;
146else if ($msg_uid = $_SESSION['compose']['param']['uid'])
147  $compose_mode = RCUBE_COMPOSE_EDIT;
148
149$config_show_sig = $RCMAIL->config->get('show_sig', 1);
150if ($config_show_sig == 1)
151  $OUTPUT->set_env('show_sig', true);
152else if ($config_show_sig == 2 && (empty($compose_mode) || $compose_mode == RCUBE_COMPOSE_EDIT || $compose_mode == RCUBE_COMPOSE_DRAFT))
153  $OUTPUT->set_env('show_sig', true);
154else if ($config_show_sig == 3 && ($compose_mode == RCUBE_COMPOSE_REPLY || $compose_mode == RCUBE_COMPOSE_FORWARD))
155  $OUTPUT->set_env('show_sig', true);
156else
157  $OUTPUT->set_env('show_sig', false);
158
159// set line length for body wrapping
160$LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
161
162if (!empty($msg_uid))
163{
164  // similar as in program/steps/mail/show.inc
165  // re-set 'prefer_html' to have possibility to use html part for compose
166  $CONFIG['prefer_html'] = $CONFIG['prefer_html'] || $CONFIG['htmleditor'] || $compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT;
167  $MESSAGE = new rcube_message($msg_uid);
168
169  // make sure message is marked as read
170  if ($MESSAGE && $MESSAGE->headers && empty($MESSAGE->headers->flags['SEEN']))
171    $IMAP->set_flag($msg_uid, 'SEEN');
172
173  if (!empty($MESSAGE->headers->charset))
174    $IMAP->set_charset($MESSAGE->headers->charset);
175
176  if ($compose_mode == RCUBE_COMPOSE_REPLY)
177  {
178    $_SESSION['compose']['reply_uid'] = $msg_uid;
179    $_SESSION['compose']['reply_msgid'] = $MESSAGE->headers->messageID;
180    $_SESSION['compose']['references']  = trim($MESSAGE->headers->references . " " . $MESSAGE->headers->messageID);
181
182    if (!empty($_SESSION['compose']['param']['all']))
183      $MESSAGE->reply_all = $_SESSION['compose']['param']['all'];
184
185    $OUTPUT->set_env('compose_mode', 'reply');
186
187    // Save the sent message in the same folder of the message being replied to
188    if ($RCMAIL->config->get('reply_same_folder') && ($sent_folder = $_SESSION['compose']['mailbox'])
189      && rcmail_check_sent_folder($sent_folder, false)
190    ) {
191      $_SESSION['compose']['param']['sent_mbox'] = $sent_folder;
192    }
193  }
194  else if ($compose_mode == RCUBE_COMPOSE_DRAFT)
195  {
196    if ($MESSAGE->headers->others['x-draft-info'])
197    {
198      // get reply_uid/forward_uid to flag the original message when sending
199      $info = rcmail_draftinfo_decode($MESSAGE->headers->others['x-draft-info']);
200
201      if ($info['type'] == 'reply')
202        $_SESSION['compose']['reply_uid'] = $info['uid'];
203      else if ($info['type'] == 'forward')
204        $_SESSION['compose']['forward_uid'] = $info['uid'];
205
206      $_SESSION['compose']['mailbox'] = $info['folder'];
207
208      // Save the sent message in the same folder of the message being replied to
209      if ($RCMAIL->config->get('reply_same_folder') && ($sent_folder = $info['folder'])
210        && rcmail_check_sent_folder($sent_folder, false)
211      ) {
212        $_SESSION['compose']['param']['sent_mbox'] = $sent_folder;
213      }
214    }
215
216    if ($MESSAGE->headers->in_reply_to)
217      $_SESSION['compose']['reply_msgid'] = '<'.$MESSAGE->headers->in_reply_to.'>';
218
219    $_SESSION['compose']['references']  = $MESSAGE->headers->references;
220  }
221  else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
222  {
223    $_SESSION['compose']['forward_uid'] = $msg_uid;
224    $OUTPUT->set_env('compose_mode', 'forward');
225
226    if (!empty($_SESSION['compose']['param']['attachment']))
227      $MESSAGE->forward_attachment = true;
228  }
229}
230
231$MESSAGE->compose = array();
232
233// get user's identities
234$MESSAGE->identities = $USER->list_identities();
235if (count($MESSAGE->identities))
236{
237  foreach ($MESSAGE->identities as $idx => $ident) {
238    $email = mb_strtolower(rcube_idn_to_utf8($ident['email']));
239
240    $MESSAGE->identities[$idx]['email_ascii'] = $ident['email'];
241    $MESSAGE->identities[$idx]['ident']       = format_email_recipient($ident['email'], $ident['name']);
242    $MESSAGE->identities[$idx]['email']       = $email;
243  }
244}
245
246// Set From field value
247if (!empty($_POST['_from'])) {
248  $MESSAGE->compose['from'] = get_input_value('_from', RCUBE_INPUT_POST);
249}
250else if (!empty($_SESSION['compose']['param']['from'])) {
251  $MESSAGE->compose['from'] = $_SESSION['compose']['param']['from'];
252}
253else if (count($MESSAGE->identities)) {
254  $a_recipients = array();
255  $a_names      = array();
256
257  // extract all recipients of the reply-message
258  if (is_object($MESSAGE->headers) && in_array($compose_mode, array(RCUBE_COMPOSE_REPLY, RCUBE_COMPOSE_FORWARD)))
259  {
260    $a_to = $IMAP->decode_address_list($MESSAGE->headers->to);
261    foreach ($a_to as $addr) {
262      if (!empty($addr['mailto'])) {
263        $a_recipients[] = strtolower($addr['mailto']);
264        $a_names[]      = $addr['name'];
265      }
266    }
267
268    if (!empty($MESSAGE->headers->cc)) {
269      $a_cc = $IMAP->decode_address_list($MESSAGE->headers->cc);
270      foreach ($a_cc as $addr) {
271        if (!empty($addr['mailto'])) {
272          $a_recipients[] = strtolower($addr['mailto']);
273          $a_names[]      = $addr['name'];
274        }
275      }
276    }
277  }
278
279  $from_idx         = null;
280  $default_identity = null;
281  $return_path      = $MESSAGE->headers->others['return-path'];
282
283  // Select identity
284  foreach ($MESSAGE->identities as $idx => $ident) {
285    // save default identity ID
286    if ($ident['standard']) {
287      $default_identity = $idx;
288    }
289
290    // use From header
291    if (in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))) {
292      if ($MESSAGE->headers->from == $ident['ident']) {
293        $from_idx = $idx;
294        break;
295      }
296    }
297    // reply to yourself
298    else if ($compose_mode == RCUBE_COMPOSE_REPLY && $MESSAGE->headers->from == $ident['ident']) {
299      $from_idx = $idx;
300      break;
301    }
302    // use replied message recipients
303    else if (($found = array_search($ident['email_ascii'], $a_recipients)) !== false) {
304      // match identity name, prefer default identity
305      if ($from_idx === null || ($a_names[$found] && $ident['name'] && $a_names[$found] == $ident['name'])) {
306        $from_idx = $idx;
307      }
308    }
309  }
310
311  // Fallback using Return-Path
312  if ($from_idx === null && $return_path) {
313    foreach ($MESSAGE->identities as $idx => $ident) {
314      if (strpos($return_path, str_replace('@', '=', $ident['email_ascii']).'@') !== false) {
315        $from_idx = $idx;
316        break;
317      }
318    }
319  }
320
321  // Still no ID, use default/first identity
322  if ($from_idx === null) {
323    $from_idx = $default_identity !== null ? $default_identity : key(reset($MESSAGE->identities));
324  }
325
326  $ident   = $MESSAGE->identities[$from_idx];
327  $from_id = $ident['identity_id'];
328
329  $MESSAGE->compose['from_email'] = $ident['email'];
330  $MESSAGE->compose['from']       = $from_id;
331}
332
333// Set other headers
334$a_recipients = array();
335$parts        = array('to', 'cc', 'bcc', 'replyto', 'followupto');
336$separator    = trim($RCMAIL->config->get('recipients_separator', ',')) . ' ';
337
338foreach ($parts as $header) {
339  $fvalue = '';
340  $decode_header = true;
341
342  // we have a set of recipients stored is session
343  if ($header == 'to' && ($mailto_id = $_SESSION['compose']['param']['mailto'])
344      && $_SESSION['mailto'][$mailto_id]
345  ) {
346    $fvalue = urldecode($_SESSION['mailto'][$mailto_id]);
347    $decode_header = false;
348  }
349  else if (!empty($_POST['_'.$header])) {
350    $fvalue = get_input_value('_'.$header, RCUBE_INPUT_POST, TRUE);
351  }
352  else if (!empty($_SESSION['compose']['param'][$header])) {
353    $fvalue = $_SESSION['compose']['param'][$header];
354  }
355  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
356    // get recipent address(es) out of the message headers
357    if ($header == 'to') {
358      $mailfollowup = $MESSAGE->headers->others['mail-followup-to'];
359      $mailreplyto  = $MESSAGE->headers->others['mail-reply-to'];
360
361      if ($MESSAGE->reply_all == 'list' && $mailfollowup)
362        $fvalue = $mailfollowup;
363      else if ($MESSAGE->reply_all == 'list'
364        && preg_match('/<mailto:([^>]+)>/i', $MESSAGE->headers->others['list-post'], $m))
365        $fvalue = $m[1];
366      else if ($MESSAGE->reply_all && $mailfollowup)
367        $fvalue = $mailfollowup;
368      else if ($mailreplyto)
369        $fvalue = $mailreplyto;
370      else if (!empty($MESSAGE->headers->replyto))
371        $fvalue = $MESSAGE->headers->replyto;
372      else if (!empty($MESSAGE->headers->from))
373        $fvalue = $MESSAGE->headers->from;
374    }
375    // add recipient of original message if reply to all
376    else if ($header == 'cc' && !empty($MESSAGE->reply_all) && $MESSAGE->reply_all != 'list') {
377      if ($v = $MESSAGE->headers->to)
378        $fvalue .= $v;
379      if ($v = $MESSAGE->headers->cc)
380        $fvalue .= (!empty($fvalue) ? $separator : '') . $v;
381    }
382  }
383  else if (in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))) {
384    // get drafted headers
385    if ($header=='to' && !empty($MESSAGE->headers->to))
386      $fvalue = $MESSAGE->get_header('to');
387    else if ($header=='cc' && !empty($MESSAGE->headers->cc))
388      $fvalue = $MESSAGE->get_header('cc');
389    else if ($header=='bcc' && !empty($MESSAGE->headers->bcc))
390      $fvalue = $MESSAGE->get_header('bcc');
391    else if ($header=='replyto' && !empty($MESSAGE->headers->others['mail-reply-to']))
392      $fvalue = $MESSAGE->get_header('mail-reply-to');
393    else if ($header=='replyto' && !empty($MESSAGE->headers->replyto))
394      $fvalue = $MESSAGE->get_header('reply-to');
395    else if ($header=='followupto' && !empty($MESSAGE->headers->others['mail-followup-to']))
396      $fvalue = $MESSAGE->get_header('mail-followup-to');
397  }
398
399  // split recipients and put them back together in a unique way
400  if (!empty($fvalue) && in_array($header, array('to', 'cc', 'bcc'))) {
401    $to_addresses = $IMAP->decode_address_list($fvalue, null, $decode_header);
402    $fvalue = array();
403
404    foreach ($to_addresses as $addr_part) {
405      if (empty($addr_part['mailto']))
406        continue;
407
408      $mailto = mb_strtolower(rcube_idn_to_utf8($addr_part['mailto']));
409
410      if (!in_array($mailto, $a_recipients)
411        && ($header == 'to' || empty($MESSAGE->compose['from_email']) || $mailto != $MESSAGE->compose['from_email'])
412      ) {
413        if ($addr_part['name'] && $addr_part['mailto'] != $addr_part['name'])
414          $string = format_email_recipient($mailto, $addr_part['name']);
415        else
416          $string = $mailto;
417
418        $fvalue[] = $string;
419        $a_recipients[] = $addr_part['mailto'];
420      }
421    }
422
423    $fvalue = implode($separator, $fvalue);
424  }
425
426  $MESSAGE->compose[$header] = $fvalue;
427}
428unset($a_recipients);
429
430// process $MESSAGE body/attachments, set $MESSAGE_BODY/$HTML_MODE vars and some session data
431$MESSAGE_BODY = rcmail_prepare_message_body();
432
433
434/****** compose mode functions ********/
435
436function rcmail_compose_headers($attrib)
437{
438  global $MESSAGE;
439
440  list($form_start, $form_end) = get_form_tags($attrib);
441
442  $out  = '';
443  $part = strtolower($attrib['part']);
444
445  switch ($part)
446  {
447    case 'from':
448      return $form_start . rcmail_compose_header_from($attrib);
449
450    case 'to':
451    case 'cc':
452    case 'bcc':
453      $fname = '_' . $part;
454      $header = $param = $part;
455
456      $allow_attrib = array('id', 'class', 'style', 'cols', 'rows', 'tabindex');
457      $field_type = 'html_textarea';
458      break;
459
460    case 'replyto':
461    case 'reply-to':
462      $fname = '_replyto';
463      $param = 'replyto';
464      $header = 'reply-to';
465
466    case 'followupto':
467    case 'followup-to':
468      if (!$fname) {
469        $fname = '_followupto';
470        $param = 'followupto';
471        $header = 'mail-followup-to';
472      }
473
474      $allow_attrib = array('id', 'class', 'style', 'size', 'tabindex');
475      $field_type = 'html_inputfield';
476      break;
477  }
478
479  if ($fname && $field_type)
480  {
481    // pass the following attributes to the form class
482    $field_attrib = array('name' => $fname, 'spellcheck' => 'false');
483    foreach ($attrib as $attr => $value)
484      if (in_array($attr, $allow_attrib))
485        $field_attrib[$attr] = $value;
486
487    // create teaxtarea object
488    $input = new $field_type($field_attrib);
489    $out = $input->show($MESSAGE->compose[$param]);
490  }
491
492  if ($form_start)
493    $out = $form_start.$out;
494
495  // configure autocompletion
496  rcube_autocomplete_init();
497
498  return $out;
499}
500
501
502function rcmail_compose_header_from($attrib)
503{
504  global $MESSAGE, $OUTPUT;
505
506  // pass the following attributes to the form class
507  $field_attrib = array('name' => '_from');
508  foreach ($attrib as $attr => $value)
509    if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
510      $field_attrib[$attr] = $value;
511
512  if (count($MESSAGE->identities))
513  {
514    $a_signatures = array();
515
516    $field_attrib['onchange'] = JS_OBJECT_NAME.".change_identity(this)";
517    $select_from = new html_select($field_attrib);
518
519    // create SELECT element
520    foreach ($MESSAGE->identities as $sql_arr)
521    {
522      $identity_id = $sql_arr['identity_id'];
523      $select_from->add(format_email_recipient($sql_arr['email'], $sql_arr['name']), $identity_id);
524
525      // add signature to array
526      if (!empty($sql_arr['signature']) && empty($_SESSION['compose']['param']['nosig']))
527      {
528        $a_signatures[$identity_id]['text'] = $sql_arr['signature'];
529        $a_signatures[$identity_id]['is_html'] = ($sql_arr['html_signature'] == 1) ? true : false;
530        if ($a_signatures[$identity_id]['is_html'])
531        {
532            $h2t = new html2text($a_signatures[$identity_id]['text'], false, false);
533            $a_signatures[$identity_id]['plain_text'] = trim($h2t->get_text());
534        }
535      }
536    }
537
538    $out = $select_from->show($MESSAGE->compose['from']);
539
540    // add signatures to client
541    $OUTPUT->set_env('signatures', $a_signatures);
542  }
543  // no identities, display text input field
544  else {
545    $field_attrib['class'] = 'from_address';
546    $input_from = new html_inputfield($field_attrib);
547    $out = $input_from->show($MESSAGE->compose['from']);
548  }
549
550  return $out;
551}
552
553
554function rcmail_compose_editor_mode()
555{
556  global $RCMAIL, $MESSAGE, $compose_mode;
557  static $useHtml;
558
559  if ($useHtml !== null)
560    return $useHtml;
561
562  $html_editor = intval($RCMAIL->config->get('htmleditor'));
563
564  if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
565    $useHtml = $MESSAGE->has_html_part();
566  }
567  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
568    $useHtml = ($html_editor == 1 || ($html_editor == 2 && $MESSAGE->has_html_part()));
569  }
570  else { // RCUBE_COMPOSE_FORWARD or NEW
571    $useHtml = ($html_editor == 1);
572  }
573
574  return $useHtml;
575}
576
577
578function rcmail_prepare_message_body()
579{
580  global $RCMAIL, $MESSAGE, $compose_mode, $LINE_LENGTH, $HTML_MODE;
581
582  // use posted message body
583  if (!empty($_POST['_message'])) {
584    $body = get_input_value('_message', RCUBE_INPUT_POST, true);
585    $isHtml = (bool) get_input_value('_is_html', RCUBE_INPUT_POST);
586  }
587  else if ($_SESSION['compose']['param']['body']) {
588    $body = $_SESSION['compose']['param']['body'];
589    $isHtml = false;
590  }
591  // forward as attachment
592  else if ($compose_mode == RCUBE_COMPOSE_FORWARD && $MESSAGE->forward_attachment) {
593    $isHtml = rcmail_compose_editor_mode();
594    $body = '';
595    if (empty($_SESSION['compose']['attachments']))
596      rcmail_write_forward_attachment($MESSAGE);
597  }
598  // reply/edit/draft/forward
599  else if ($compose_mode) {
600    $has_html_part = $MESSAGE->has_html_part();
601    $isHtml = rcmail_compose_editor_mode();
602
603    if ($isHtml) {
604      if ($has_html_part) {
605        $body = $MESSAGE->first_html_part();
606      }
607      else {
608        $body = $MESSAGE->first_text_part();
609        // try to remove the signature
610        if ($RCMAIL->config->get('strip_existing_sig', true))
611          $body = rcmail_remove_signature($body);
612        // add HTML formatting
613        $body = rcmail_plain_body($body);
614        if ($body)
615          $body = '<pre>' . $body . '</pre>';
616      }
617    }
618    else {
619      if ($has_html_part) {
620        // use html part if it has been used for message (pre)viewing
621        // decrease line length for quoting
622        $len = $compose_mode == RCUBE_COMPOSE_REPLY ? $LINE_LENGTH-2 : $LINE_LENGTH;
623        $txt = new html2text($MESSAGE->first_html_part(), false, true, $len);
624        $body = $txt->get_text();
625      }
626      else {
627        $body = $MESSAGE->first_text_part($part);
628        if ($body && $part && $part->ctype_secondary == 'plain'
629            && $part->ctype_parameters['format'] == 'flowed'
630        ) {
631          $body = rcube_message::unfold_flowed($body);
632        }
633      }
634    }
635
636    // compose reply-body
637    if ($compose_mode == RCUBE_COMPOSE_REPLY)
638      $body = rcmail_create_reply_body($body, $isHtml);
639    // forward message body inline
640    else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
641      $body = rcmail_create_forward_body($body, $isHtml);
642    // load draft message body
643    else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
644      $body = rcmail_create_draft_body($body, $isHtml);
645  }
646  else { // new message
647    $isHtml = rcmail_compose_editor_mode();
648  }
649
650  $plugin = $RCMAIL->plugins->exec_hook('message_compose_body',
651    array('body' => $body, 'html' => $isHtml, 'mode' => $compose_mode));
652  $body = $plugin['body'];
653  unset($plugin);
654
655  // add blocked.gif attachment (#1486516)
656  if ($isHtml && preg_match('#<img src="\./program/blocked\.gif"#', $body)) {
657    if ($attachment = rcmail_save_image('program/blocked.gif', 'image/gif')) {
658      $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
659      $body = preg_replace('#\./program/blocked\.gif#',
660        $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$_SESSION['compose']['id'],
661        $body);
662    }
663  }
664
665  $HTML_MODE = $isHtml;
666
667  return $body;
668}
669
670function rcmail_compose_body($attrib)
671{
672  global $RCMAIL, $CONFIG, $OUTPUT, $MESSAGE, $compose_mode, $LINE_LENGTH, $HTML_MODE, $MESSAGE_BODY;
673
674  list($form_start, $form_end) = get_form_tags($attrib);
675  unset($attrib['form']);
676
677  if (empty($attrib['id']))
678    $attrib['id'] = 'rcmComposeBody';
679
680  $attrib['name'] = '_message';
681
682  $isHtml = $HTML_MODE;
683
684  $out = $form_start ? "$form_start\n" : '';
685
686  $saveid = new html_hiddenfield(array('name' => '_draft_saveid', 'value' => $compose_mode==RCUBE_COMPOSE_DRAFT ? str_replace(array('<','>'), "", $MESSAGE->headers->messageID) : ''));
687  $out .= $saveid->show();
688
689  $drafttoggle = new html_hiddenfield(array('name' => '_draft', 'value' => 'yes'));
690  $out .= $drafttoggle->show();
691
692  $msgtype = new html_hiddenfield(array('name' => '_is_html', 'value' => ($isHtml?"1":"0")));
693  $out .= $msgtype->show();
694
695  // If desired, set this textarea to be editable by TinyMCE
696  if ($isHtml) {
697    $attrib['class'] = 'mce_editor';
698    $textarea = new html_textarea($attrib);
699    $out .= $textarea->show($MESSAGE_BODY);
700  }
701  else {
702    $textarea = new html_textarea($attrib);
703    $out .= $textarea->show('');
704    // quote plain text, inject into textarea
705    $table = get_html_translation_table(HTML_SPECIALCHARS);
706    $MESSAGE_BODY = strtr($MESSAGE_BODY, $table);
707    $out = substr($out, 0, -11) . $MESSAGE_BODY . '</textarea>';
708  }
709
710  $out .= $form_end ? "\n$form_end" : '';
711
712  $OUTPUT->set_env('composebody', $attrib['id']);
713
714  // include HTML editor
715  rcube_html_editor();
716
717  // include GoogieSpell
718  if (!empty($CONFIG['enable_spellcheck'])) {
719    $engine           = $RCMAIL->config->get('spellcheck_engine','googie');
720    $dictionary       = (bool) $RCMAIL->config->get('spellcheck_dictionary');
721    $spellcheck_langs = (array) $RCMAIL->config->get('spellcheck_languages',
722      array('da'=>'Dansk', 'de'=>'Deutsch', 'en' => 'English', 'es'=>'Español',
723            'fr'=>'Français', 'it'=>'Italiano', 'nl'=>'Nederlands', 'pl'=>'Polski',
724            'pt'=>'Português', 'fi'=>'Suomi', 'sv'=>'Svenska'));
725
726    // googie works only with two-letter codes
727    if ($engine == 'googie') {
728      $lang = strtolower(substr($_SESSION['language'], 0, 2));
729
730      $spellcheck_langs_googie = array();
731      foreach ($spellcheck_langs as $key => $name)
732        $spellcheck_langs_googie[strtolower(substr($key,0,2))] = $name;
733        $spellcheck_langs = $spellcheck_langs_googie;
734    }
735    else {
736      $lang = $_SESSION['language'];
737
738      // if not found in the list, try with two-letter code
739      if (!$spellcheck_langs[$lang])
740        $lang = strtolower(substr($lang, 0, 2));
741    }
742
743    if (!$spellcheck_langs[$lang])
744      $lang = 'en';
745
746    $editor_lang_set = array();
747    foreach ($spellcheck_langs as $key => $name) {
748      $editor_lang_set[] = ($key == $lang ? '+' : '') . JQ($name).'='.JQ($key);
749    }
750
751    $OUTPUT->include_script('googiespell.js');
752    $OUTPUT->add_script(sprintf(
753      "var googie = new GoogieSpell('\$__skin_path/images/googiespell/','?_task=utils&_action=spell&lang=', %s);\n".
754      "googie.lang_chck_spell = \"%s\";\n".
755      "googie.lang_rsm_edt = \"%s\";\n".
756      "googie.lang_close = \"%s\";\n".
757      "googie.lang_revert = \"%s\";\n".
758      "googie.lang_no_error_found = \"%s\";\n".
759      "googie.lang_learn_word = \"%s\";\n".
760      "googie.setLanguages(%s);\n".
761      "googie.setCurrentLanguage('%s');\n".
762      "googie.setSpellContainer('spellcheck-control');\n".
763      "googie.decorateTextarea('%s');\n".
764      "%s.set_env('spellcheck', googie);",
765      !empty($dictionary) ? 'true' : 'false',
766      JQ(Q(rcube_label('checkspelling'))),
767      JQ(Q(rcube_label('resumeediting'))),
768      JQ(Q(rcube_label('close'))),
769      JQ(Q(rcube_label('revertto'))),
770      JQ(Q(rcube_label('nospellerrors'))),
771      JQ(Q(rcube_label('addtodict'))),
772      json_serialize($spellcheck_langs),
773      $lang,
774      $attrib['id'],
775      JS_OBJECT_NAME), 'foot');
776
777    $OUTPUT->add_label('checking');
778    $OUTPUT->set_env('spellcheck_langs', join(',', $editor_lang_set));
779  }
780
781  $out .= "\n".'<iframe name="savetarget" src="program/blank.gif" style="width:0;height:0;border:none;visibility:hidden;"></iframe>';
782
783  return $out;
784}
785
786
787function rcmail_create_reply_body($body, $bodyIsHtml)
788{
789  global $RCMAIL, $MESSAGE, $LINE_LENGTH;
790
791  // build reply prefix
792  $from = array_pop($RCMAIL->imap->decode_address_list($MESSAGE->get_header('from'), 1, false));
793  $prefix = rcube_label(array(
794    'name' => 'mailreplyintro',
795    'vars' => array(
796      'date' => format_date($MESSAGE->headers->date, $RCMAIL->config->get('date_long')),
797      'sender' => $from['name'] ? $from['name'] : rcube_idn_to_utf8($from['mailto']),
798    )
799  ));
800
801  if (!$bodyIsHtml) {
802    $body = preg_replace('/\r?\n/', "\n", $body);
803
804    // try to remove the signature
805    if ($RCMAIL->config->get('strip_existing_sig', true))
806      $body = rcmail_remove_signature($body);
807
808    // soft-wrap and quote message text
809    $body = rcmail_wrap_and_quote(rtrim($body, "\n"), $LINE_LENGTH);
810
811    $prefix .= "\n";
812    $suffix = '';
813
814    if ($RCMAIL->config->get('top_posting'))
815      $prefix = "\n\n\n" . $prefix;
816  }
817  else {
818    // save inline images to files
819    $cid_map = rcmail_write_inline_attachments($MESSAGE);
820    // set is_safe flag (we need this for html body washing)
821    rcmail_check_safe($MESSAGE);
822    // clean up html tags
823    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
824
825    // build reply (quote content)
826    $prefix = '<p>' . Q($prefix) . "</p>\n";
827    $prefix .= '<blockquote>';
828
829    if ($RCMAIL->config->get('top_posting')) {
830      $prefix = '<br>' . $prefix;
831      $suffix = '</blockquote>';
832    }
833    else {
834      $suffix = '</blockquote><p></p>';
835    }
836  }
837
838  return $prefix.$body.$suffix;
839}
840
841
842function rcmail_create_forward_body($body, $bodyIsHtml)
843{
844  global $RCMAIL, $MESSAGE;
845
846  // add attachments
847  if (!isset($_SESSION['compose']['forward_attachments']) && is_array($MESSAGE->mime_parts))
848    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
849
850  $date    = format_date($MESSAGE->headers->date, $RCMAIL->config->get('date_long'));
851  $charset = $RCMAIL->output->get_charset();
852
853  if (!$bodyIsHtml)
854  {
855    $prefix = "\n\n\n-------- " . rcube_label('originalmessage') . " --------\n";
856    $prefix .= rcube_label('subject') . ': ' . $MESSAGE->subject . "\n";
857    $prefix .= rcube_label('date')    . ': ' . $date . "\n";
858    $prefix .= rcube_label('from')    . ': ' . $MESSAGE->get_header('from') . "\n";
859    $prefix .= rcube_label('to')      . ': ' . $MESSAGE->get_header('to') . "\n";
860
861    if ($MESSAGE->headers->cc)
862      $prefix .= rcube_label('cc') . ': ' . $MESSAGE->get_header('cc') . "\n";
863    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
864      $prefix .= rcube_label('replyto') . ': ' . $MESSAGE->get_header('replyto') . "\n";
865
866    $prefix .= "\n";
867  }
868  else
869  {
870    // set is_safe flag (we need this for html body washing)
871    rcmail_check_safe($MESSAGE);
872    // clean up html tags
873    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
874
875    $prefix = sprintf(
876      "<br /><p>-------- " . rcube_label('originalmessage') . " --------</p>" .
877        "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" .
878        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>" .
879        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>" .
880        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>" .
881        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
882      rcube_label('subject'), Q($MESSAGE->subject),
883      rcube_label('date'), Q($date),
884      rcube_label('from'), htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $charset),
885      rcube_label('to'), htmlspecialchars(Q($MESSAGE->get_header('to'), 'replace'), ENT_COMPAT, $charset));
886
887    if ($MESSAGE->headers->cc)
888      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
889        rcube_label('cc'),
890        htmlspecialchars(Q($MESSAGE->get_header('cc'), 'replace'), ENT_COMPAT, $charset));
891
892    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
893      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
894        rcube_label('replyto'),
895        htmlspecialchars(Q($MESSAGE->get_header('replyto'), 'replace'), ENT_COMPAT, $charset));
896
897    $prefix .= "</tbody></table><br>";
898  }
899
900  return $prefix.$body;
901}
902
903
904function rcmail_create_draft_body($body, $bodyIsHtml)
905{
906  global $MESSAGE, $OUTPUT;
907
908  /**
909   * add attachments
910   * sizeof($MESSAGE->mime_parts can be 1 - e.g. attachment, but no text!
911   */
912  if (empty($_SESSION['compose']['forward_attachments'])
913      && is_array($MESSAGE->mime_parts)
914      && count($MESSAGE->mime_parts) > 0)
915  {
916    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
917
918    // replace cid with href in inline images links
919    if ($cid_map)
920      $body = str_replace(array_keys($cid_map), array_values($cid_map), $body);
921  }
922
923  return $body;
924}
925
926
927function rcmail_remove_signature($body)
928{
929  global $RCMAIL;
930
931  $len = strlen($body);
932  $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
933
934  while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
935    if ($sp == 0 || $body[$sp-1] == "\n") {
936      // do not touch blocks with more that X lines
937      if (substr_count($body, "\n", $sp) < $sig_max_lines) {
938        $body = substr($body, 0, max(0, $sp-1));
939      }
940      break;
941    }
942  }
943
944  return $body;
945}
946
947
948function rcmail_write_compose_attachments(&$message, $bodyIsHtml)
949{
950  global $RCMAIL;
951
952  $cid_map = $messages = array();
953  foreach ((array)$message->mime_parts as $pid => $part)
954  {
955    if (($part->ctype_primary != 'message' || !$bodyIsHtml) && $part->ctype_primary != 'multipart' &&
956        ($part->disposition == 'attachment' || ($part->disposition == 'inline' && $bodyIsHtml) || $part->filename)
957        && $part->mimetype != 'application/ms-tnef'
958    ) {
959      $skip = false;
960      if ($part->mimetype == 'message/rfc822') {
961        $messages[] = $part->mime_id;
962      } else if ($messages) {
963        // skip attachments included in message/rfc822 attachment (#1486487)
964        foreach ($messages as $mimeid)
965          if (strpos($part->mime_id, $mimeid.'.') === 0) {
966            $skip = true;
967            break;
968          }
969      }
970
971      if (!$skip && ($attachment = rcmail_save_attachment($message, $pid))) {
972        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
973        if ($bodyIsHtml && ($part->content_id || $part->content_location)) {
974          $url = $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$_SESSION['compose']['id'];
975          if ($part->content_id)
976            $cid_map['cid:'.$part->content_id] = $url;
977          else
978            $cid_map[$part->content_location] = $url;
979        }
980      }
981    }
982  }
983
984  $_SESSION['compose']['forward_attachments'] = true;
985
986  return $cid_map;
987}
988
989
990function rcmail_write_inline_attachments(&$message)
991{
992  global $RCMAIL;
993
994  $cid_map = array();
995  foreach ((array)$message->mime_parts as $pid => $part) {
996    if (($part->content_id || $part->content_location) && $part->filename) {
997      if ($attachment = rcmail_save_attachment($message, $pid)) {
998        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
999        $url = $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$_SESSION['compose']['id'];
1000        if ($part->content_id)
1001          $cid_map['cid:'.$part->content_id] = $url;
1002        else
1003          $cid_map[$part->content_location] = $url;
1004      }
1005    }
1006  }
1007
1008  return $cid_map;
1009}
1010
1011// Creates an attachment from the forwarded message
1012function rcmail_write_forward_attachment(&$message)
1013{
1014  global $RCMAIL;
1015
1016  if (strlen($message->subject)) {
1017    $name = mb_substr($message->subject, 0, 64) . '.eml';
1018  }
1019  else {
1020    $name = 'message_rfc822.eml';
1021  }
1022
1023  $mem_limit = parse_bytes(ini_get('memory_limit'));
1024  $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
1025  $data = $path = null;
1026
1027  // don't load too big attachments into memory
1028  if ($mem_limit > 0 && $message->size > $mem_limit - $curr_mem) {
1029    $temp_dir = unslashify($RCMAIL->config->get('temp_dir'));
1030    $path = tempnam($temp_dir, 'rcmAttmnt');
1031    if ($fp = fopen($path, 'w')) {
1032      $RCMAIL->imap->get_raw_body($message->uid, $fp);
1033      fclose($fp);
1034    } else
1035      return false;
1036  } else {
1037    $data = $RCMAIL->imap->get_raw_body($message->uid);
1038  }
1039
1040  $attachment = array(
1041    'group' => $_SESSION['compose']['id'],
1042    'name' => $name,
1043    'mimetype' => 'message/rfc822',
1044    'data' => $data,
1045    'path' => $path,
1046    'size' => $path ? filesize($path) : strlen($data),
1047  );
1048
1049  $attachment = $RCMAIL->plugins->exec_hook('attachment_save', $attachment);
1050
1051  if ($attachment['status']) {
1052    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1053    $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
1054    return true;
1055  } else if ($path) {
1056    @unlink($path);
1057  }
1058
1059  return false;
1060}
1061
1062
1063function rcmail_save_attachment(&$message, $pid)
1064{
1065  $rcmail = rcmail::get_instance();
1066  $part = $message->mime_parts[$pid];
1067  $mem_limit = parse_bytes(ini_get('memory_limit'));
1068  $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
1069  $data = $path = null;
1070
1071  // don't load too big attachments into memory
1072  if ($mem_limit > 0 && $part->size > $mem_limit - $curr_mem) {
1073    $temp_dir = unslashify($rcmail->config->get('temp_dir'));
1074    $path = tempnam($temp_dir, 'rcmAttmnt');
1075    if ($fp = fopen($path, 'w')) {
1076      $message->get_part_content($pid, $fp);
1077      fclose($fp);
1078    } else
1079      return false;
1080  } else {
1081    $data = $message->get_part_content($pid);
1082  }
1083
1084  $attachment = array(
1085    'group' => $_SESSION['compose']['id'],
1086    'name' => $part->filename ? $part->filename : 'Part_'.$pid.'.'.$part->ctype_secondary,
1087    'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
1088    'content_id' => $part->content_id,
1089    'data' => $data,
1090    'path' => $path,
1091    'size' => $path ? filesize($path) : strlen($data),
1092  );
1093
1094  $attachment = $rcmail->plugins->exec_hook('attachment_save', $attachment);
1095
1096  if ($attachment['status']) {
1097    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1098    return $attachment;
1099  } else if ($path) {
1100    @unlink($path);
1101  }
1102
1103  return false;
1104}
1105
1106function rcmail_save_image($path, $mimetype='')
1107{
1108  // handle attachments in memory
1109  $data = file_get_contents($path);
1110
1111  $attachment = array(
1112    'group' => $_SESSION['compose']['id'],
1113    'name' => rcmail_basename($path),
1114    'mimetype' => $mimetype ? $mimetype : rc_mime_content_type($path, $name),
1115    'data' => $data,
1116    'size' => strlen($data),
1117  );
1118
1119  $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
1120
1121  if ($attachment['status']) {
1122    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1123    return $attachment;
1124  }
1125
1126  return false;
1127}
1128
1129function rcmail_basename($filename)
1130{
1131  // basename() is not unicode safe and locale dependent
1132  if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
1133    return preg_replace('/^.*[\\\\\\/]/', '', $filename);
1134  } else {
1135    return preg_replace('/^.*[\/]/', '', $filename);
1136  }
1137}
1138
1139function rcmail_compose_subject($attrib)
1140{
1141  global $MESSAGE, $compose_mode;
1142 
1143  list($form_start, $form_end) = get_form_tags($attrib);
1144  unset($attrib['form']);
1145 
1146  $attrib['name'] = '_subject';
1147  $attrib['spellcheck'] = 'true';
1148  $textfield = new html_inputfield($attrib);
1149
1150  $subject = '';
1151
1152  // use subject from post
1153  if (isset($_POST['_subject'])) {
1154    $subject = get_input_value('_subject', RCUBE_INPUT_POST, TRUE);
1155  }
1156  // create a reply-subject
1157  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
1158    if (preg_match('/^re:/i', $MESSAGE->subject))
1159      $subject = $MESSAGE->subject;
1160    else
1161      $subject = 'Re: '.$MESSAGE->subject;
1162  }
1163  // create a forward-subject
1164  else if ($compose_mode == RCUBE_COMPOSE_FORWARD) {
1165    if (preg_match('/^fwd:/i', $MESSAGE->subject))
1166      $subject = $MESSAGE->subject;
1167    else
1168      $subject = 'Fwd: '.$MESSAGE->subject;
1169  }
1170  // creeate a draft-subject
1171  else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
1172    $subject = $MESSAGE->subject;
1173  }
1174  else if (!empty($_SESSION['compose']['param']['subject'])) {
1175    $subject = $_SESSION['compose']['param']['subject'];
1176  }
1177 
1178  $out = $form_start ? "$form_start\n" : '';
1179  $out .= $textfield->show($subject);
1180  $out .= $form_end ? "\n$form_end" : '';
1181
1182  return $out;
1183}
1184
1185
1186function rcmail_compose_attachment_list($attrib)
1187{
1188  global $OUTPUT, $CONFIG;
1189 
1190  // add ID if not given
1191  if (!$attrib['id'])
1192    $attrib['id'] = 'rcmAttachmentList';
1193 
1194  $out = "\n";
1195  $jslist = array();
1196
1197  if (is_array($_SESSION['compose']['attachments']))
1198  {
1199    if ($attrib['deleteicon']) {
1200      $button = html::img(array(
1201        'src' => $CONFIG['skin_path'] . $attrib['deleteicon'],
1202        'alt' => rcube_label('delete')
1203      ));
1204    }
1205    else
1206      $button = Q(rcube_label('delete'));
1207
1208    foreach ($_SESSION['compose']['attachments'] as $id => $a_prop)
1209    {
1210      if (empty($a_prop))
1211        continue;
1212     
1213      $out .= html::tag('li', array('id' => 'rcmfile'.$id),
1214        html::a(array(
1215            'href' => "#delete",
1216            'title' => rcube_label('delete'),
1217            'onclick' => sprintf("return %s.command('remove-attachment','rcmfile%s', this)", JS_OBJECT_NAME, $id)),
1218          $button) . Q($a_prop['name']));
1219       
1220        $jslist['rcmfile'.$id] = array('name' => $a_prop['name'], 'complete' => true, 'mimetype' => $a_prop['mimetype']);
1221    }
1222  }
1223
1224  if ($attrib['deleteicon'])
1225    $_SESSION['compose']['deleteicon'] = $CONFIG['skin_path'] . $attrib['deleteicon'];
1226  if ($attrib['cancelicon'])
1227    $OUTPUT->set_env('cancelicon', $CONFIG['skin_path'] . $attrib['cancelicon']);
1228  if ($attrib['loadingicon'])
1229    $OUTPUT->set_env('loadingicon', $CONFIG['skin_path'] . $attrib['loadingicon']);
1230
1231  $OUTPUT->set_env('attachments', $jslist);
1232  $OUTPUT->add_gui_object('attachmentlist', $attrib['id']);
1233   
1234  return html::tag('ul', $attrib, $out, html::$common_attrib);
1235}
1236
1237
1238function rcmail_compose_attachment_form($attrib)
1239{
1240  global $RCMAIL, $OUTPUT;
1241
1242  // add ID if not given
1243  if (!$attrib['id'])
1244    $attrib['id'] = 'rcmUploadbox';
1245
1246  // Get filesize, enable upload progress bar
1247  $max_filesize = rcube_upload_init();
1248
1249  $button = new html_inputfield(array('type' => 'button'));
1250
1251  $out = html::div($attrib,
1252    $OUTPUT->form_tag(array('name' => 'uploadform', 'method' => 'post', 'enctype' => 'multipart/form-data'),
1253      html::div(null, rcmail_compose_attachment_field(array('size' => $attrib['attachmentfieldsize']))) .
1254      html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize)))) .
1255      html::div('buttons',
1256        $button->show(rcube_label('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()")) . ' ' .
1257        $button->show(rcube_label('upload'), array('class' => 'button mainaction', 'onclick' => JS_OBJECT_NAME . ".command('send-attachment', this.form)"))
1258      )
1259    )
1260  );
1261
1262  $OUTPUT->add_gui_object('uploadbox', $attrib['id']);
1263  return $out;
1264}
1265
1266
1267function rcmail_compose_attachment_field($attrib)
1268{
1269  $attrib['type'] = 'file';
1270  $attrib['name'] = '_attachments[]';
1271  $attrib['multiple'] = 'multiple';
1272
1273  $field = new html_inputfield($attrib);
1274  return $field->show();
1275}
1276
1277
1278function rcmail_priority_selector($attrib)
1279{
1280  global $MESSAGE;
1281 
1282  list($form_start, $form_end) = get_form_tags($attrib);
1283  unset($attrib['form']);
1284
1285  $attrib['name'] = '_priority';
1286  $selector = new html_select($attrib);
1287
1288  $selector->add(array(rcube_label('lowest'),
1289                       rcube_label('low'),
1290                       rcube_label('normal'),
1291                       rcube_label('high'),
1292                       rcube_label('highest')),
1293                 array(5, 4, 0, 2, 1));
1294
1295  if (isset($_POST['_priority']))
1296    $sel = $_POST['_priority'];
1297  else if (intval($MESSAGE->headers->priority) != 3)
1298    $sel = intval($MESSAGE->headers->priority);
1299  else
1300    $sel = 0;
1301
1302  $out = $form_start ? "$form_start\n" : '';
1303  $out .= $selector->show($sel);
1304  $out .= $form_end ? "\n$form_end" : '';
1305
1306  return $out;
1307}
1308
1309
1310function rcmail_receipt_checkbox($attrib)
1311{
1312  global $RCMAIL, $MESSAGE, $compose_mode;
1313
1314  list($form_start, $form_end) = get_form_tags($attrib);
1315  unset($attrib['form']);
1316
1317  if (!isset($attrib['id']))
1318    $attrib['id'] = 'receipt'; 
1319
1320  $attrib['name'] = '_receipt';
1321  $attrib['value'] = '1';
1322  $checkbox = new html_checkbox($attrib);
1323
1324  if ($MESSAGE && in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT)))
1325    $mdn_default = (bool) $MESSAGE->headers->mdn_to;
1326  else
1327    $mdn_default = $RCMAIL->config->get('mdn_default');
1328
1329  $out = $form_start ? "$form_start\n" : '';
1330  $out .= $checkbox->show($mdn_default);
1331  $out .= $form_end ? "\n$form_end" : '';
1332
1333  return $out;
1334}
1335
1336
1337function rcmail_dsn_checkbox($attrib)
1338{
1339  global $RCMAIL;
1340
1341  list($form_start, $form_end) = get_form_tags($attrib);
1342  unset($attrib['form']);
1343
1344  if (!isset($attrib['id']))
1345    $attrib['id'] = 'dsn';
1346
1347  $attrib['name'] = '_dsn';
1348  $attrib['value'] = '1';
1349  $checkbox = new html_checkbox($attrib);
1350
1351  $out = $form_start ? "$form_start\n" : '';
1352  $out .= $checkbox->show($RCMAIL->config->get('dsn_default'));
1353  $out .= $form_end ? "\n$form_end" : '';
1354
1355  return $out;
1356}
1357
1358
1359function rcmail_editor_selector($attrib)
1360{
1361  global $CONFIG, $MESSAGE, $compose_mode;
1362
1363  // determine whether HTML or plain text should be checked
1364  $useHtml = rcmail_compose_editor_mode();
1365
1366  if (empty($attrib['editorid']))
1367    $attrib['editorid'] = 'rcmComposeBody';
1368
1369  if (empty($attrib['name']))
1370    $attrib['name'] = 'editorSelect';
1371
1372  $attrib['onchange'] = "return rcmail_toggle_editor(this, '".$attrib['editorid']."', '_is_html')";
1373
1374  $select = new html_select($attrib);
1375
1376  $select->add(Q(rcube_label('htmltoggle')), 'html');
1377  $select->add(Q(rcube_label('plaintoggle')), 'plain');
1378
1379  return $select->show($useHtml ? 'html' : 'plain');
1380
1381  foreach ($choices as $value => $text) {
1382    $attrib['id'] = '_' . $value;
1383    $attrib['value'] = $value;
1384    $selector .= $radio->show($chosenvalue, $attrib) . html::label($attrib['id'], Q(rcube_label($text)));
1385  }
1386
1387  return $selector;
1388}
1389
1390
1391function rcmail_store_target_selection($attrib)
1392{
1393  $attrib['name'] = '_store_target';
1394  $select = rcmail_mailbox_select(array_merge($attrib, array(
1395    'noselection' => '- '.rcube_label('dontsave').' -',
1396    'folder_filter' => 'mail',
1397    'folder_rights' => 'w',
1398  )));
1399  return $select->show($_SESSION['compose']['param']['sent_mbox'], $attrib);
1400}
1401
1402
1403function rcmail_check_sent_folder($folder, $create=false)
1404{
1405  global $IMAP;
1406
1407  if ($IMAP->mailbox_exists($folder, true)) {
1408    return true;
1409  }
1410
1411  // folder may exist but isn't subscribed (#1485241)
1412  if ($create) {
1413    if (!$IMAP->mailbox_exists($folder))
1414      return $IMAP->create_mailbox($folder, true);
1415    else
1416      return $IMAP->subscribe($folder);
1417  }
1418
1419  return false;
1420}
1421
1422
1423function get_form_tags($attrib)
1424{
1425  global $RCMAIL, $MESSAGE_FORM;
1426
1427  $form_start = '';
1428  if (!$MESSAGE_FORM)
1429  {
1430    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
1431    $hiddenfields->add(array('name' => '_action', 'value' => 'send'));
1432    $hiddenfields->add(array('name' => '_id', 'value' => $_SESSION['compose']['id']));
1433
1434    $form_start = empty($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
1435    $form_start .= $hiddenfields->show();
1436  }
1437
1438  $form_end = ($MESSAGE_FORM && !strlen($attrib['form'])) ? '</form>' : '';
1439  $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
1440
1441  if (!$MESSAGE_FORM)
1442    $RCMAIL->output->add_gui_object('messageform', $form_name);
1443
1444  $MESSAGE_FORM = $form_name;
1445
1446  return array($form_start, $form_end);
1447}
1448
1449
1450// register UI objects
1451$OUTPUT->add_handlers(array(
1452  'composeheaders' => 'rcmail_compose_headers',
1453  'composesubject' => 'rcmail_compose_subject',
1454  'composebody' => 'rcmail_compose_body',
1455  'composeattachmentlist' => 'rcmail_compose_attachment_list',
1456  'composeattachmentform' => 'rcmail_compose_attachment_form',
1457  'composeattachment' => 'rcmail_compose_attachment_field',
1458  'priorityselector' => 'rcmail_priority_selector',
1459  'editorselector' => 'rcmail_editor_selector',
1460  'receiptcheckbox' => 'rcmail_receipt_checkbox',
1461  'dsncheckbox' => 'rcmail_dsn_checkbox',
1462  'storetarget' => 'rcmail_store_target_selection',
1463));
1464
1465$OUTPUT->send('compose');
1466
1467
Note: See TracBrowser for help on using the repository browser.