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

Last change on this file was 6073, checked in by alec, 14 months ago
  • Merge devel-framework branch, resolved conflicts
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.2 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    $attrib['class'] = 'mce_editor';
774    $textarea = new html_textarea($attrib);
775    $out .= $textarea->show($MESSAGE_BODY);
776  }
777  else {
778    $textarea = new html_textarea($attrib);
779    $out .= $textarea->show('');
780    // quote plain text, inject into textarea
781    $table = get_html_translation_table(HTML_SPECIALCHARS);
782    $MESSAGE_BODY = strtr($MESSAGE_BODY, $table);
783    $out = substr($out, 0, -11) . $MESSAGE_BODY . '</textarea>';
784  }
785
786  $out .= $form_end ? "\n$form_end" : '';
787
788  $OUTPUT->set_env('composebody', $attrib['id']);
789
790  // include HTML editor
791  rcube_html_editor();
792
793  // Set language list
794  if (!empty($CONFIG['enable_spellcheck'])) {
795    $engine           = $RCMAIL->config->get('spellcheck_engine','googie');
796    $dictionary       = (bool) $RCMAIL->config->get('spellcheck_dictionary');
797    $spellcheck_langs = (array) $RCMAIL->config->get('spellcheck_languages',
798      array('da'=>'Dansk', 'de'=>'Deutsch', 'en' => 'English', 'es'=>'Español',
799            'fr'=>'Français', 'it'=>'Italiano', 'nl'=>'Nederlands', 'pl'=>'Polski',
800            'pt'=>'Português', 'ru'=>'РусскОй', 'fi'=>'Suomi', 'sv'=>'Svenska'));
801
802    // googie works only with two-letter codes
803    if ($engine == 'googie') {
804      $lang = strtolower(substr($_SESSION['language'], 0, 2));
805
806      $spellcheck_langs_googie = array();
807      foreach ($spellcheck_langs as $key => $name)
808        $spellcheck_langs_googie[strtolower(substr($key,0,2))] = $name;
809        $spellcheck_langs = $spellcheck_langs_googie;
810    }
811    else {
812      $lang = $_SESSION['language'];
813
814      // if not found in the list, try with two-letter code
815      if (!$spellcheck_langs[$lang])
816        $lang = strtolower(substr($lang, 0, 2));
817    }
818
819    if (!$spellcheck_langs[$lang])
820      $lang = 'en';
821
822    $OUTPUT->set_env('spell_langs', $spellcheck_langs);
823    $OUTPUT->set_env('spell_lang', $lang);
824
825    $editor_lang_set = array();
826    foreach ($spellcheck_langs as $key => $name) {
827      $editor_lang_set[] = ($key == $lang ? '+' : '') . JQ($name).'='.JQ($key);
828    }
829
830    // include GoogieSpell
831    $OUTPUT->include_script('googiespell.js');
832    $OUTPUT->add_script(sprintf(
833      "var googie = new GoogieSpell('%s/images/googiespell/','%s&lang=', %s);\n".
834      "googie.lang_chck_spell = \"%s\";\n".
835      "googie.lang_rsm_edt = \"%s\";\n".
836      "googie.lang_close = \"%s\";\n".
837      "googie.lang_revert = \"%s\";\n".
838      "googie.lang_no_error_found = \"%s\";\n".
839      "googie.lang_learn_word = \"%s\";\n".
840      "googie.setLanguages(%s);\n".
841      "googie.setCurrentLanguage('%s');\n".
842      "googie.setDecoration(false);\n".
843      "googie.decorateTextarea('%s');\n".
844      "%s.set_env('spellcheck', googie);",
845      $RCMAIL->output->get_skin_path(),
846      $RCMAIL->url(array('_task' => 'utils', '_action' => 'spell')),
847      !empty($dictionary) ? 'true' : 'false',
848      JQ(Q(rcube_label('checkspelling'))),
849      JQ(Q(rcube_label('resumeediting'))),
850      JQ(Q(rcube_label('close'))),
851      JQ(Q(rcube_label('revertto'))),
852      JQ(Q(rcube_label('nospellerrors'))),
853      JQ(Q(rcube_label('addtodict'))),
854      json_serialize($spellcheck_langs),
855      $lang,
856      $attrib['id'],
857      JS_OBJECT_NAME), 'foot');
858
859    $OUTPUT->add_label('checking');
860    $OUTPUT->set_env('spellcheck_langs', join(',', $editor_lang_set));
861  }
862
863  $out .= "\n".'<iframe name="savetarget" src="program/blank.gif" style="width:0;height:0;border:none;visibility:hidden;"></iframe>';
864
865  return $out;
866}
867
868
869function rcmail_create_reply_body($body, $bodyIsHtml)
870{
871  global $RCMAIL, $MESSAGE, $LINE_LENGTH;
872
873  // build reply prefix
874  $from = array_pop(rcube_mime::decode_address_list($MESSAGE->get_header('from'), 1, false, $MESSAGE->headers->charset));
875  $prefix = rcube_label(array(
876    'name' => 'mailreplyintro',
877    'vars' => array(
878      'date' => format_date($MESSAGE->headers->date, $RCMAIL->config->get('date_long')),
879      'sender' => $from['name'] ? $from['name'] : rcube_idn_to_utf8($from['mailto']),
880    )
881  ));
882
883  if (!$bodyIsHtml) {
884    $body = preg_replace('/\r?\n/', "\n", $body);
885
886    // soft-wrap and quote message text
887    $body = rcmail_wrap_and_quote(rtrim($body, "\n"), $LINE_LENGTH);
888
889    $prefix .= "\n";
890    $suffix = '';
891
892    if ($RCMAIL->config->get('top_posting'))
893      $prefix = "\n\n\n" . $prefix;
894  }
895  else {
896    // save inline images to files
897    $cid_map = rcmail_write_inline_attachments($MESSAGE);
898    // set is_safe flag (we need this for html body washing)
899    rcmail_check_safe($MESSAGE);
900    // clean up html tags
901    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
902
903    // build reply (quote content)
904    $prefix = '<p>' . Q($prefix) . "</p>\n";
905    $prefix .= '<blockquote>';
906
907    if ($RCMAIL->config->get('top_posting')) {
908      $prefix = '<br>' . $prefix;
909      $suffix = '</blockquote>';
910    }
911    else {
912      $suffix = '</blockquote><p></p>';
913    }
914  }
915
916  return $prefix.$body.$suffix;
917}
918
919
920function rcmail_create_forward_body($body, $bodyIsHtml)
921{
922  global $RCMAIL, $MESSAGE, $COMPOSE;
923
924  // add attachments
925  if (!isset($COMPOSE['forward_attachments']) && is_array($MESSAGE->mime_parts))
926    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
927
928  $date    = format_date($MESSAGE->headers->date, $RCMAIL->config->get('date_long'));
929  $charset = $RCMAIL->output->get_charset();
930
931  if (!$bodyIsHtml)
932  {
933    $prefix = "\n\n\n-------- " . rcube_label('originalmessage') . " --------\n";
934    $prefix .= rcube_label('subject') . ': ' . $MESSAGE->subject . "\n";
935    $prefix .= rcube_label('date')    . ': ' . $date . "\n";
936    $prefix .= rcube_label('from')    . ': ' . $MESSAGE->get_header('from') . "\n";
937    $prefix .= rcube_label('to')      . ': ' . $MESSAGE->get_header('to') . "\n";
938
939    if ($MESSAGE->headers->cc)
940      $prefix .= rcube_label('cc') . ': ' . $MESSAGE->get_header('cc') . "\n";
941    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
942      $prefix .= rcube_label('replyto') . ': ' . $MESSAGE->get_header('replyto') . "\n";
943
944    $prefix .= "\n";
945  }
946  else
947  {
948    // set is_safe flag (we need this for html body washing)
949    rcmail_check_safe($MESSAGE);
950    // clean up html tags
951    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
952
953    $prefix = sprintf(
954      "<br /><p>-------- " . rcube_label('originalmessage') . " --------</p>" .
955        "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" .
956        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>" .
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      rcube_label('subject'), Q($MESSAGE->subject),
961      rcube_label('date'), Q($date),
962      rcube_label('from'), htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $charset),
963      rcube_label('to'), htmlspecialchars(Q($MESSAGE->get_header('to'), 'replace'), ENT_COMPAT, $charset));
964
965    if ($MESSAGE->headers->cc)
966      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
967        rcube_label('cc'),
968        htmlspecialchars(Q($MESSAGE->get_header('cc'), 'replace'), ENT_COMPAT, $charset));
969
970    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
971      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">%s: </th><td>%s</td></tr>",
972        rcube_label('replyto'),
973        htmlspecialchars(Q($MESSAGE->get_header('replyto'), 'replace'), ENT_COMPAT, $charset));
974
975    $prefix .= "</tbody></table><br>";
976  }
977
978  return $prefix.$body;
979}
980
981
982function rcmail_create_draft_body($body, $bodyIsHtml)
983{
984  global $MESSAGE, $OUTPUT, $COMPOSE;
985
986  /**
987   * add attachments
988   * sizeof($MESSAGE->mime_parts can be 1 - e.g. attachment, but no text!
989   */
990  if (empty($COMPOSE['forward_attachments'])
991      && is_array($MESSAGE->mime_parts)
992      && count($MESSAGE->mime_parts) > 0)
993  {
994    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
995
996    // replace cid with href in inline images links
997    if ($cid_map)
998      $body = str_replace(array_keys($cid_map), array_values($cid_map), $body);
999  }
1000
1001  return $body;
1002}
1003
1004
1005function rcmail_remove_signature($body)
1006{
1007  global $RCMAIL;
1008
1009  $body = str_replace("\r\n", "\n", $body);
1010  $len  = strlen($body);
1011  $sig_max_lines = $RCMAIL->config->get('sig_max_lines', 15);
1012
1013  while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
1014    if ($sp == 0 || $body[$sp-1] == "\n") {
1015      // do not touch blocks with more that X lines
1016      if (substr_count($body, "\n", $sp) < $sig_max_lines) {
1017        $body = substr($body, 0, max(0, $sp-1));
1018      }
1019      break;
1020    }
1021  }
1022
1023  return $body;
1024}
1025
1026
1027function rcmail_write_compose_attachments(&$message, $bodyIsHtml)
1028{
1029  global $RCMAIL, $COMPOSE;
1030
1031  $cid_map = $messages = array();
1032  foreach ((array)$message->mime_parts as $pid => $part)
1033  {
1034    if (($part->ctype_primary != 'message' || !$bodyIsHtml) && $part->ctype_primary != 'multipart' &&
1035        ($part->disposition == 'attachment' || ($part->disposition == 'inline' && $bodyIsHtml) || $part->filename)
1036        && $part->mimetype != 'application/ms-tnef'
1037    ) {
1038      $skip = false;
1039      if ($part->mimetype == 'message/rfc822') {
1040        $messages[] = $part->mime_id;
1041      } else if ($messages) {
1042        // skip attachments included in message/rfc822 attachment (#1486487)
1043        foreach ($messages as $mimeid)
1044          if (strpos($part->mime_id, $mimeid.'.') === 0) {
1045            $skip = true;
1046            break;
1047          }
1048      }
1049
1050      if (!$skip && ($attachment = rcmail_save_attachment($message, $pid))) {
1051        $COMPOSE['attachments'][$attachment['id']] = $attachment;
1052        if ($bodyIsHtml && ($part->content_id || $part->content_location)) {
1053          $url = $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$COMPOSE['id'];
1054          if ($part->content_id)
1055            $cid_map['cid:'.$part->content_id] = $url;
1056          else
1057            $cid_map[$part->content_location] = $url;
1058        }
1059      }
1060    }
1061  }
1062
1063  $COMPOSE['forward_attachments'] = true;
1064
1065  return $cid_map;
1066}
1067
1068
1069function rcmail_write_inline_attachments(&$message)
1070{
1071  global $RCMAIL, $COMPOSE;
1072
1073  $cid_map = array();
1074  foreach ((array)$message->mime_parts as $pid => $part) {
1075    if (($part->content_id || $part->content_location) && $part->filename) {
1076      if ($attachment = rcmail_save_attachment($message, $pid)) {
1077        $COMPOSE['attachments'][$attachment['id']] = $attachment;
1078        $url = $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$COMPOSE['id'];
1079        if ($part->content_id)
1080          $cid_map['cid:'.$part->content_id] = $url;
1081        else
1082          $cid_map[$part->content_location] = $url;
1083      }
1084    }
1085  }
1086
1087  return $cid_map;
1088}
1089
1090// Creates an attachment from the forwarded message
1091function rcmail_write_forward_attachment(&$message)
1092{
1093  global $RCMAIL, $COMPOSE;
1094
1095  if (strlen($message->subject)) {
1096    $name = mb_substr($message->subject, 0, 64) . '.eml';
1097  }
1098  else {
1099    $name = 'message_rfc822.eml';
1100  }
1101
1102  $mem_limit = parse_bytes(ini_get('memory_limit'));
1103  $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
1104  $data = $path = null;
1105
1106  // don't load too big attachments into memory
1107  if ($mem_limit > 0 && $message->size > $mem_limit - $curr_mem) {
1108    $temp_dir = unslashify($RCMAIL->config->get('temp_dir'));
1109    $path = tempnam($temp_dir, 'rcmAttmnt');
1110    if ($fp = fopen($path, 'w')) {
1111      $RCMAIL->storage->get_raw_body($message->uid, $fp);
1112      fclose($fp);
1113    } else
1114      return false;
1115  } else {
1116    $data = $RCMAIL->storage->get_raw_body($message->uid);
1117  }
1118
1119  $attachment = array(
1120    'group' => $COMPOSE['id'],
1121    'name' => $name,
1122    'mimetype' => 'message/rfc822',
1123    'data' => $data,
1124    'path' => $path,
1125    'size' => $path ? filesize($path) : strlen($data),
1126  );
1127
1128  $attachment = $RCMAIL->plugins->exec_hook('attachment_save', $attachment);
1129
1130  if ($attachment['status']) {
1131    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1132    $COMPOSE['attachments'][$attachment['id']] = $attachment;
1133    return true;
1134  } else if ($path) {
1135    @unlink($path);
1136  }
1137
1138  return false;
1139}
1140
1141
1142function rcmail_save_attachment(&$message, $pid)
1143{
1144  global $COMPOSE;
1145
1146  $rcmail = rcmail::get_instance();
1147  $part = $message->mime_parts[$pid];
1148  $mem_limit = parse_bytes(ini_get('memory_limit'));
1149  $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
1150  $data = $path = null;
1151
1152  // don't load too big attachments into memory
1153  if ($mem_limit > 0 && $part->size > $mem_limit - $curr_mem) {
1154    $temp_dir = unslashify($rcmail->config->get('temp_dir'));
1155    $path = tempnam($temp_dir, 'rcmAttmnt');
1156    if ($fp = fopen($path, 'w')) {
1157      $message->get_part_content($pid, $fp);
1158      fclose($fp);
1159    } else
1160      return false;
1161  } else {
1162    $data = $message->get_part_content($pid);
1163  }
1164
1165  $mimetype = $part->ctype_primary . '/' . $part->ctype_secondary;
1166  $filename = $part->filename;
1167  if (!strlen($filename)) {
1168    if ($mimetype == 'text/html') {
1169      $filename = rcube_label('htmlmessage');
1170    }
1171    else {
1172      $filename = 'Part_'.$pid;
1173    }
1174    $filename .= '.' . $part->ctype_secondary;
1175  }
1176
1177  $attachment = array(
1178    'group' => $COMPOSE['id'],
1179    'name' => $filename,
1180    'mimetype' => $mimetype,
1181    'content_id' => $part->content_id,
1182    'data' => $data,
1183    'path' => $path,
1184    'size' => $path ? filesize($path) : strlen($data),
1185  );
1186
1187  $attachment = $rcmail->plugins->exec_hook('attachment_save', $attachment);
1188
1189  if ($attachment['status']) {
1190    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1191    return $attachment;
1192  } else if ($path) {
1193    @unlink($path);
1194  }
1195
1196  return false;
1197}
1198
1199function rcmail_save_image($path, $mimetype='')
1200{
1201  global $COMPOSE;
1202
1203  // handle attachments in memory
1204  $data = file_get_contents($path);
1205
1206  $attachment = array(
1207    'group' => $COMPOSE['id'],
1208    'name' => rcmail_basename($path),
1209    'mimetype' => $mimetype ? $mimetype : rc_mime_content_type($path, $name),
1210    'data' => $data,
1211    'size' => strlen($data),
1212  );
1213
1214  $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
1215
1216  if ($attachment['status']) {
1217    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
1218    return $attachment;
1219  }
1220
1221  return false;
1222}
1223
1224function rcmail_basename($filename)
1225{
1226  // basename() is not unicode safe and locale dependent
1227  if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
1228    return preg_replace('/^.*[\\\\\\/]/', '', $filename);
1229  } else {
1230    return preg_replace('/^.*[\/]/', '', $filename);
1231  }
1232}
1233
1234function rcmail_compose_subject($attrib)
1235{
1236  global $MESSAGE, $COMPOSE, $compose_mode;
1237
1238  list($form_start, $form_end) = get_form_tags($attrib);
1239  unset($attrib['form']);
1240
1241  $attrib['name'] = '_subject';
1242  $attrib['spellcheck'] = 'true';
1243  $textfield = new html_inputfield($attrib);
1244
1245  $subject = '';
1246
1247  // use subject from post
1248  if (isset($_POST['_subject'])) {
1249    $subject = get_input_value('_subject', RCUBE_INPUT_POST, TRUE);
1250  }
1251  // create a reply-subject
1252  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
1253    if (preg_match('/^re:/i', $MESSAGE->subject))
1254      $subject = $MESSAGE->subject;
1255    else
1256      $subject = 'Re: '.$MESSAGE->subject;
1257  }
1258  // create a forward-subject
1259  else if ($compose_mode == RCUBE_COMPOSE_FORWARD) {
1260    if (preg_match('/^fwd:/i', $MESSAGE->subject))
1261      $subject = $MESSAGE->subject;
1262    else
1263      $subject = 'Fwd: '.$MESSAGE->subject;
1264  }
1265  // creeate a draft-subject
1266  else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
1267    $subject = $MESSAGE->subject;
1268  }
1269  else if (!empty($COMPOSE['param']['subject'])) {
1270    $subject = $COMPOSE['param']['subject'];
1271  }
1272
1273  $out = $form_start ? "$form_start\n" : '';
1274  $out .= $textfield->show($subject);
1275  $out .= $form_end ? "\n$form_end" : '';
1276
1277  return $out;
1278}
1279
1280
1281function rcmail_compose_attachment_list($attrib)
1282{
1283  global $OUTPUT, $CONFIG, $COMPOSE;
1284
1285  // add ID if not given
1286  if (!$attrib['id'])
1287    $attrib['id'] = 'rcmAttachmentList';
1288
1289  $out = "\n";
1290  $jslist = array();
1291
1292  if (is_array($COMPOSE['attachments'])) {
1293    if ($attrib['deleteicon']) {
1294      $button = html::img(array(
1295        'src' => $CONFIG['skin_path'] . $attrib['deleteicon'],
1296        'alt' => rcube_label('delete')
1297      ));
1298    }
1299    else
1300      $button = Q(rcube_label('delete'));
1301
1302    foreach ($COMPOSE['attachments'] as $id => $a_prop) {
1303      if (empty($a_prop))
1304        continue;
1305
1306      $out .= html::tag('li', array('id' => 'rcmfile'.$id, 'class' => rcmail_filetype2classname($a_prop['mimetype'], $a_prop['name'])),
1307        html::a(array(
1308            'href' => "#delete",
1309            'title' => rcube_label('delete'),
1310            'onclick' => sprintf("return %s.command('remove-attachment','rcmfile%s', this)", JS_OBJECT_NAME, $id),
1311            'class' => 'delete'),
1312          $button) . Q($a_prop['name']));
1313
1314        $jslist['rcmfile'.$id] = array('name' => $a_prop['name'], 'complete' => true, 'mimetype' => $a_prop['mimetype']);
1315    }
1316  }
1317
1318  if ($attrib['deleteicon'])
1319    $COMPOSE['deleteicon'] = $CONFIG['skin_path'] . $attrib['deleteicon'];
1320  if ($attrib['cancelicon'])
1321    $OUTPUT->set_env('cancelicon', $CONFIG['skin_path'] . $attrib['cancelicon']);
1322  if ($attrib['loadingicon'])
1323    $OUTPUT->set_env('loadingicon', $CONFIG['skin_path'] . $attrib['loadingicon']);
1324
1325  $OUTPUT->set_env('attachments', $jslist);
1326  $OUTPUT->add_gui_object('attachmentlist', $attrib['id']);
1327
1328  return html::tag('ul', $attrib, $out, html::$common_attrib);
1329}
1330
1331
1332function rcmail_compose_attachment_form($attrib)
1333{
1334  global $OUTPUT;
1335
1336  // set defaults
1337  $attrib += array('id' => 'rcmUploadbox', 'buttons' => 'yes');
1338
1339  // Get filesize, enable upload progress bar
1340  $max_filesize = rcube_upload_init();
1341
1342  $button = new html_inputfield(array('type' => 'button'));
1343
1344  $out = html::div($attrib,
1345    $OUTPUT->form_tag(array('id' => $attrib['id'].'Frm', 'name' => 'uploadform', 'method' => 'post', 'enctype' => 'multipart/form-data'),
1346      html::div(null, rcmail_compose_attachment_field(array('size' => $attrib['attachmentfieldsize']))) .
1347      html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize)))) .
1348      (get_boolean($attrib['buttons']) ? html::div('buttons',
1349        $button->show(rcube_label('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()")) . ' ' .
1350        $button->show(rcube_label('upload'), array('class' => 'button mainaction', 'onclick' => JS_OBJECT_NAME . ".command('send-attachment', this.form)"))
1351      ) : '')
1352    )
1353  );
1354
1355  $OUTPUT->add_gui_object('uploadform', $attrib['id'].'Frm');
1356  return $out;
1357}
1358
1359
1360function rcmail_compose_attachment_field($attrib)
1361{
1362  $attrib['type'] = 'file';
1363  $attrib['name'] = '_attachments[]';
1364  $attrib['multiple'] = 'multiple';
1365
1366  $field = new html_inputfield($attrib);
1367  return $field->show();
1368}
1369
1370
1371function rcmail_priority_selector($attrib)
1372{
1373  global $MESSAGE;
1374
1375  list($form_start, $form_end) = get_form_tags($attrib);
1376  unset($attrib['form']);
1377
1378  $attrib['name'] = '_priority';
1379  $selector = new html_select($attrib);
1380
1381  $selector->add(array(rcube_label('lowest'),
1382                       rcube_label('low'),
1383                       rcube_label('normal'),
1384                       rcube_label('high'),
1385                       rcube_label('highest')),
1386                 array(5, 4, 0, 2, 1));
1387
1388  if (isset($_POST['_priority']))
1389    $sel = $_POST['_priority'];
1390  else if (intval($MESSAGE->headers->priority) != 3)
1391    $sel = intval($MESSAGE->headers->priority);
1392  else
1393    $sel = 0;
1394
1395  $out = $form_start ? "$form_start\n" : '';
1396  $out .= $selector->show($sel);
1397  $out .= $form_end ? "\n$form_end" : '';
1398
1399  return $out;
1400}
1401
1402
1403function rcmail_receipt_checkbox($attrib)
1404{
1405  global $RCMAIL, $MESSAGE, $compose_mode;
1406
1407  list($form_start, $form_end) = get_form_tags($attrib);
1408  unset($attrib['form']);
1409
1410  if (!isset($attrib['id']))
1411    $attrib['id'] = 'receipt';
1412
1413  $attrib['name'] = '_receipt';
1414  $attrib['value'] = '1';
1415  $checkbox = new html_checkbox($attrib);
1416
1417  if (in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT)))
1418    $mdn_default = (bool) $MESSAGE->headers->mdn_to;
1419  else
1420    $mdn_default = $RCMAIL->config->get('mdn_default');
1421
1422  $out = $form_start ? "$form_start\n" : '';
1423  $out .= $checkbox->show($mdn_default);
1424  $out .= $form_end ? "\n$form_end" : '';
1425
1426  return $out;
1427}
1428
1429
1430function rcmail_dsn_checkbox($attrib)
1431{
1432  global $RCMAIL;
1433
1434  list($form_start, $form_end) = get_form_tags($attrib);
1435  unset($attrib['form']);
1436
1437  if (!isset($attrib['id']))
1438    $attrib['id'] = 'dsn';
1439
1440  $attrib['name'] = '_dsn';
1441  $attrib['value'] = '1';
1442  $checkbox = new html_checkbox($attrib);
1443
1444  $out = $form_start ? "$form_start\n" : '';
1445  $out .= $checkbox->show($RCMAIL->config->get('dsn_default'));
1446  $out .= $form_end ? "\n$form_end" : '';
1447
1448  return $out;
1449}
1450
1451
1452function rcmail_editor_selector($attrib)
1453{
1454  // determine whether HTML or plain text should be checked
1455  $useHtml = rcmail_compose_editor_mode();
1456
1457  if (empty($attrib['editorid']))
1458    $attrib['editorid'] = 'rcmComposeBody';
1459
1460  if (empty($attrib['name']))
1461    $attrib['name'] = 'editorSelect';
1462
1463  $attrib['onchange'] = "return rcmail_toggle_editor(this, '".$attrib['editorid']."', '_is_html')";
1464
1465  $select = new html_select($attrib);
1466
1467  $select->add(Q(rcube_label('htmltoggle')), 'html');
1468  $select->add(Q(rcube_label('plaintoggle')), 'plain');
1469
1470  return $select->show($useHtml ? 'html' : 'plain');
1471
1472  foreach ($choices as $value => $text) {
1473    $attrib['id'] = '_' . $value;
1474    $attrib['value'] = $value;
1475    $selector .= $radio->show($chosenvalue, $attrib) . html::label($attrib['id'], Q(rcube_label($text)));
1476  }
1477
1478  return $selector;
1479}
1480
1481
1482function rcmail_store_target_selection($attrib)
1483{
1484  global $COMPOSE;
1485
1486  $attrib['name'] = '_store_target';
1487  $select = rcmail_mailbox_select(array_merge($attrib, array(
1488    'noselection' => '- '.rcube_label('dontsave').' -',
1489    'folder_filter' => 'mail',
1490    'folder_rights' => 'w',
1491  )));
1492  return $select->show($COMPOSE['param']['sent_mbox'], $attrib);
1493}
1494
1495
1496function rcmail_check_sent_folder($folder, $create=false)
1497{
1498  global $RCMAIL;
1499
1500  if ($RCMAIL->storage->folder_exists($folder, true)) {
1501    return true;
1502  }
1503
1504  // folder may exist but isn't subscribed (#1485241)
1505  if ($create) {
1506    if (!$RCMAIL->storage->folder_exists($folder))
1507      return $RCMAIL->storage->create_folder($folder, true);
1508    else
1509      return $RCMAIL->storage->subscribe($folder);
1510  }
1511
1512  return false;
1513}
1514
1515
1516function get_form_tags($attrib)
1517{
1518  global $RCMAIL, $MESSAGE_FORM, $COMPOSE;
1519
1520  $form_start = '';
1521  if (!$MESSAGE_FORM)
1522  {
1523    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
1524    $hiddenfields->add(array('name' => '_action', 'value' => 'send'));
1525    $hiddenfields->add(array('name' => '_id', 'value' => $COMPOSE['id']));
1526
1527    $form_start = empty($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
1528    $form_start .= $hiddenfields->show();
1529  }
1530
1531  $form_end = ($MESSAGE_FORM && !strlen($attrib['form'])) ? '</form>' : '';
1532  $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
1533
1534  if (!$MESSAGE_FORM)
1535    $RCMAIL->output->add_gui_object('messageform', $form_name);
1536
1537  $MESSAGE_FORM = $form_name;
1538
1539  return array($form_start, $form_end);
1540}
1541
1542
1543function rcmail_addressbook_list($attrib = array())
1544{
1545    global $RCMAIL, $OUTPUT;
1546
1547    $attrib += array('id' => 'rcmdirectorylist');
1548
1549    $out = '';
1550    $line_templ = html::tag('li', array(
1551        'id' => 'rcmli%s', 'class' => '%s'),
1552        html::a(array('href' => '#list',
1553            'rel' => '%s',
1554            'onclick' => "return ".JS_OBJECT_NAME.".command('list-adresses','%s',this)"), '%s'));
1555
1556    foreach ($RCMAIL->get_address_sources() as $j => $source) {
1557        $id = strval(strlen($source['id']) ? $source['id'] : $j);
1558        $js_id = JQ($id);
1559
1560        // set class name(s)
1561        $class_name = 'addressbook';
1562        if ($source['class_name'])
1563            $class_name .= ' ' . $source['class_name'];
1564
1565        $out .= sprintf($line_templ,
1566            html_identifier($id),
1567            $class_name,
1568            $source['id'],
1569            $js_id, (!empty($source['name']) ? Q($source['name']) : Q($id)));
1570    }
1571
1572    $OUTPUT->add_gui_object('addressbookslist', $attrib['id']);
1573
1574    return html::tag('ul', $attrib, $out, html::$common_attrib);
1575}
1576
1577// return the contacts list as HTML table
1578function rcmail_contacts_list($attrib = array())
1579{
1580    global $OUTPUT;
1581
1582    $attrib += array('id' => 'rcmAddressList');
1583
1584    // set client env
1585    $OUTPUT->add_gui_object('contactslist', $attrib['id']);
1586    $OUTPUT->set_env('pagecount', 0);
1587    $OUTPUT->set_env('current_page', 0);
1588    $OUTPUT->include_script('list.js');
1589
1590    return rcube_table_output($attrib, array(), array('name'), 'ID');
1591}
1592
1593
1594
1595// register UI objects
1596$OUTPUT->add_handlers(array(
1597  'composeheaders' => 'rcmail_compose_headers',
1598  'composesubject' => 'rcmail_compose_subject',
1599  'composebody' => 'rcmail_compose_body',
1600  'composeattachmentlist' => 'rcmail_compose_attachment_list',
1601  'composeattachmentform' => 'rcmail_compose_attachment_form',
1602  'composeattachment' => 'rcmail_compose_attachment_field',
1603  'priorityselector' => 'rcmail_priority_selector',
1604  'editorselector' => 'rcmail_editor_selector',
1605  'receiptcheckbox' => 'rcmail_receipt_checkbox',
1606  'dsncheckbox' => 'rcmail_dsn_checkbox',
1607  'storetarget' => 'rcmail_store_target_selection',
1608  'addressbooks' => 'rcmail_addressbook_list',
1609  'addresslist' => 'rcmail_contacts_list',
1610));
1611
1612$OUTPUT->send('compose');
Note: See TracBrowser for help on using the repository browser.