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

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