source: github/program/steps/mail/compose.inc @ 5c7e54b

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