source: github/program/steps/mail/compose.inc @ ec86add

Last change on this file since ec86add was ec86add, checked in by Aleksander Machniak <alec@…>, 10 months ago

Define context (_remote=1) for spellcheck requests to send proper response on error

  • Property mode set to 100644
File size: 51.9 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
22// define constants for message compose mode
23define('RCUBE_COMPOSE_REPLY', 0x0106);
24define('RCUBE_COMPOSE_FORWARD', 0x0107);
25define('RCUBE_COMPOSE_DRAFT', 0x0108);
26define('RCUBE_COMPOSE_EDIT', 0x0109);
27
28$MESSAGE_FORM = null;
29$COMPOSE_ID   = get_input_value('_id', RCUBE_INPUT_GET);
30$COMPOSE      = null;
31
32if ($COMPOSE_ID && $_SESSION['compose_data_'.$COMPOSE_ID])
33  $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
34
35// give replicated session storage some time to synchronize
36$retries = 0;
37while ($COMPOSE_ID && !is_array($COMPOSE) && $RCMAIL->db->is_replicated() && $retries++ < 5) {
38  usleep(500000);
39  $RCMAIL->session->reload();
40  if ($_SESSION['compose_data_'.$COMPOSE_ID])
41    $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
42}
43
44// Nothing below is called during message composition, only at "new/forward/reply/draft" initialization or
45// if a compose-ID is given (i.e. when the compose step is opened in a new window/tab).
46if (!is_array($COMPOSE))
47{
48  // Infinite redirect prevention in case of broken session (#1487028)
49  if ($COMPOSE_ID)
50    raise_error(array('code' => 500, 'type' => 'php',
51      'file' => __FILE__, 'line' => __LINE__,
52      'message' => "Invalid compose ID"), true, true);
53
54  $COMPOSE_ID = uniqid(mt_rand());
55  $_SESSION['compose_data_'.$COMPOSE_ID] = array(
56    'id'      => $COMPOSE_ID,
57    'param'   => request2param(RCUBE_INPUT_GET),
58    'mailbox' => $RCMAIL->storage->get_folder(),
59  );
60  $COMPOSE =& $_SESSION['compose_data_'.$COMPOSE_ID];
61
62  // process values like "mailto:foo@bar.com?subject=new+message&cc=another"
63  if ($COMPOSE['param']['to']) {
64    // #1486037: remove "mailto:" prefix
65    $COMPOSE['param']['to'] = preg_replace('/^mailto:/i', '', $COMPOSE['param']['to']);
66    $mailto = explode('?', $COMPOSE['param']['to']);
67    if (count($mailto) > 1) {
68      $COMPOSE['param']['to'] = $mailto[0];
69      parse_str($mailto[1], $query);
70      foreach ($query as $f => $val)
71        $COMPOSE['param'][$f] = $val;
72    }
73  }
74
75  // select folder where to save the sent message
76  $COMPOSE['param']['sent_mbox'] = $RCMAIL->config->get('sent_mbox');
77
78  // pipe compose parameters thru plugins
79  $plugin = $RCMAIL->plugins->exec_hook('message_compose', $COMPOSE);
80  $COMPOSE['param'] = array_merge($COMPOSE['param'], $plugin['param']);
81
82  // add attachments listed by message_compose hook
83  if (is_array($plugin['attachments'])) {
84    foreach ($plugin['attachments'] as $attach) {
85      // we have structured data
86      if (is_array($attach)) {
87        $attachment = $attach;
88      }
89      // only a file path is given
90      else {
91        $filename = basename($attach);
92        $attachment = array(
93          'group' => $COMPOSE_ID,
94          'name' => $filename,
95          'mimetype' => rc_mime_content_type($attach, $filename),
96          'path' => $attach,
97        );
98      }
99
100      // save attachment if valid
101      if (($attachment['data'] && $attachment['name']) || ($attachment['path'] && file_exists($attachment['path']))) {
102        $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
103      }
104
105      if ($attachment['status'] && !$attachment['abort']) {
106        unset($attachment['data'], $attachment['status'], $attachment['abort']);
107        $COMPOSE['attachments'][$attachment['id']] = $attachment;
108      }
109    }
110  }
111
112  // check if folder for saving sent messages exists and is subscribed (#1486802)
113  if ($sent_folder = $COMPOSE['param']['sent_mbox']) {
114    rcmail_check_sent_folder($sent_folder, true);
115  }
116
117  // redirect to a unique URL with all parameters stored in session
118  $OUTPUT->redirect(array(
119    '_action' => 'compose',
120    '_id'     => $COMPOSE['id'],
121    '_search' => $_REQUEST['_search'],
122  ));
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->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}
244else {
245  $MESSAGE = new stdClass();
246}
247
248$MESSAGE->compose = array();
249
250// get user's identities
251$MESSAGE->identities = $RCMAIL->user->list_identities();
252if (count($MESSAGE->identities))
253{
254  foreach ($MESSAGE->identities as $idx => $ident) {
255    $email = mb_strtolower(rcube_idn_to_utf8($ident['email']));
256
257    $MESSAGE->identities[$idx]['email_ascii'] = $ident['email'];
258    $MESSAGE->identities[$idx]['ident']       = format_email_recipient($ident['email'], $ident['name']);
259    $MESSAGE->identities[$idx]['email']       = $email;
260  }
261}
262
263// Set From field value
264if (!empty($_POST['_from'])) {
265  $MESSAGE->compose['from'] = get_input_value('_from', RCUBE_INPUT_POST);
266}
267else if (!empty($COMPOSE['param']['from'])) {
268  $MESSAGE->compose['from'] = $COMPOSE['param']['from'];
269}
270else if (count($MESSAGE->identities)) {
271  $a_recipients = array();
272  $a_names      = array();
273
274  // extract all recipients of the reply-message
275  if (is_object($MESSAGE->headers) && in_array($compose_mode, array(RCUBE_COMPOSE_REPLY, RCUBE_COMPOSE_FORWARD)))
276  {
277    $a_to = rcube_mime::decode_address_list($MESSAGE->headers->to, null, true, $MESSAGE->headers->charset);
278    foreach ($a_to as $addr) {
279      if (!empty($addr['mailto'])) {
280        $a_recipients[] = strtolower($addr['mailto']);
281        $a_names[]      = $addr['name'];
282      }
283    }
284
285    if (!empty($MESSAGE->headers->cc)) {
286      $a_cc = rcube_mime::decode_address_list($MESSAGE->headers->cc, null, true, $MESSAGE->headers->charset);
287      foreach ($a_cc as $addr) {
288        if (!empty($addr['mailto'])) {
289          $a_recipients[] = strtolower($addr['mailto']);
290          $a_names[]      = $addr['name'];
291        }
292      }
293    }
294  }
295
296  $from_idx         = null;
297  $default_identity = null;
298  $return_path      = $MESSAGE->headers->others['return-path'];
299
300  // Select identity
301  foreach ($MESSAGE->identities as $idx => $ident) {
302    // save default identity ID
303    if ($ident['standard']) {
304      $default_identity = $idx;
305    }
306
307    // use From header
308    if (in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))) {
309      if ($MESSAGE->headers->from == $ident['ident']) {
310        $from_idx = $idx;
311        break;
312      }
313    }
314    // reply to yourself
315    else if ($compose_mode == RCUBE_COMPOSE_REPLY && $MESSAGE->headers->from == $ident['ident']) {
316      $from_idx = $idx;
317      break;
318    }
319    // use replied message recipients
320    else if (($found = array_search($ident['email_ascii'], $a_recipients)) !== false) {
321      // match identity name, prefer default identity
322      if ($from_idx === null || ($a_names[$found] && $ident['name'] && $a_names[$found] == $ident['name'])) {
323        $from_idx = $idx;
324      }
325    }
326  }
327
328  // Fallback using Return-Path
329  if ($from_idx === null && $return_path) {
330    foreach ($MESSAGE->identities as $idx => $ident) {
331      if (strpos($return_path, str_replace('@', '=', $ident['email_ascii']).'@') !== false) {
332        $from_idx = $idx;
333        break;
334      }
335    }
336  }
337
338  // Still no ID, use default/first identity
339  if ($from_idx === null) {
340    $from_idx = $default_identity !== null ? $default_identity : key(reset($MESSAGE->identities));
341  }
342
343  $ident   = $MESSAGE->identities[$from_idx];
344  $from_id = $ident['identity_id'];
345
346  $MESSAGE->compose['from_email'] = $ident['email'];
347  $MESSAGE->compose['from']       = $from_id;
348}
349
350// Set other headers
351$a_recipients = array();
352$parts        = array('to', 'cc', 'bcc', 'replyto', 'followupto');
353$separator    = trim($RCMAIL->config->get('recipients_separator', ',')) . ' ';
354
355foreach ($parts as $header) {
356  $fvalue = '';
357  $decode_header = true;
358
359  // we have a set of recipients stored is session
360  if ($header == 'to' && ($mailto_id = $COMPOSE['param']['mailto'])
361      && $_SESSION['mailto'][$mailto_id]
362  ) {
363    $fvalue = urldecode($_SESSION['mailto'][$mailto_id]);
364    $decode_header = false;
365
366    // make session to not grow up too much
367    unset($_SESSION['mailto'][$mailto_id]);
368    $COMPOSE['param']['to'] = $fvalue;
369  }
370  else if (!empty($_POST['_'.$header])) {
371    $fvalue = get_input_value('_'.$header, RCUBE_INPUT_POST, TRUE);
372  }
373  else if (!empty($COMPOSE['param'][$header])) {
374    $fvalue = $COMPOSE['param'][$header];
375  }
376  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
377    // get recipent address(es) out of the message headers
378    if ($header == 'to') {
379      $mailfollowup = $MESSAGE->headers->others['mail-followup-to'];
380      $mailreplyto  = $MESSAGE->headers->others['mail-reply-to'];
381
382      // Reply to mailing list...
383      if ($MESSAGE->reply_all == 'list' && $mailfollowup)
384        $fvalue = $mailfollowup;
385      else if ($MESSAGE->reply_all == 'list'
386        && preg_match('/<mailto:([^>]+)>/i', $MESSAGE->headers->others['list-post'], $m))
387        $fvalue = $m[1];
388      // Reply to...
389      else if ($MESSAGE->reply_all && $mailfollowup)
390        $fvalue = $mailfollowup;
391      else if ($mailreplyto)
392        $fvalue = $mailreplyto;
393      else if (!empty($MESSAGE->headers->replyto))
394        $fvalue = $MESSAGE->headers->replyto;
395      else if (!empty($MESSAGE->headers->from))
396        $fvalue = $MESSAGE->headers->from;
397
398      // Reply to message sent by yourself (#1487074)
399      if (!empty($ident) && $fvalue == $ident['ident']) {
400        $fvalue = $MESSAGE->headers->to;
401      }
402    }
403    // add recipient of original message if reply to all
404    else if ($header == 'cc' && !empty($MESSAGE->reply_all) && $MESSAGE->reply_all != 'list') {
405      if ($v = $MESSAGE->headers->to)
406        $fvalue .= $v;
407      if ($v = $MESSAGE->headers->cc)
408        $fvalue .= (!empty($fvalue) ? $separator : '') . $v;
409    }
410  }
411  else if (in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))) {
412    // get drafted headers
413    if ($header=='to' && !empty($MESSAGE->headers->to))
414      $fvalue = $MESSAGE->get_header('to');
415    else if ($header=='cc' && !empty($MESSAGE->headers->cc))
416      $fvalue = $MESSAGE->get_header('cc');
417    else if ($header=='bcc' && !empty($MESSAGE->headers->bcc))
418      $fvalue = $MESSAGE->get_header('bcc');
419    else if ($header=='replyto' && !empty($MESSAGE->headers->others['mail-reply-to']))
420      $fvalue = $MESSAGE->get_header('mail-reply-to');
421    else if ($header=='replyto' && !empty($MESSAGE->headers->replyto))
422      $fvalue = $MESSAGE->get_header('reply-to');
423    else if ($header=='followupto' && !empty($MESSAGE->headers->others['mail-followup-to']))
424      $fvalue = $MESSAGE->get_header('mail-followup-to');
425  }
426
427  // split recipients and put them back together in a unique way
428  if (!empty($fvalue) && in_array($header, array('to', 'cc', 'bcc'))) {
429    $to_addresses = rcube_mime::decode_address_list($fvalue, null, $decode_header, $MESSAGE->headers->charset);
430    $fvalue = array();
431
432    foreach ($to_addresses as $addr_part) {
433      if (empty($addr_part['mailto']))
434        continue;
435
436      $mailto = mb_strtolower(rcube_idn_to_utf8($addr_part['mailto']));
437
438      if (!in_array($mailto, $a_recipients)
439        && ($header == 'to' || empty($MESSAGE->compose['from_email']) || $mailto != $MESSAGE->compose['from_email'])
440      ) {
441        if ($addr_part['name'] && $addr_part['mailto'] != $addr_part['name'])
442          $string = format_email_recipient($mailto, $addr_part['name']);
443        else
444          $string = $mailto;
445
446        $fvalue[] = $string;
447        $a_recipients[] = $addr_part['mailto'];
448      }
449    }
450
451    $fvalue = implode($separator, $fvalue);
452  }
453
454  $MESSAGE->compose[$header] = $fvalue;
455}
456unset($a_recipients);
457
458// process $MESSAGE body/attachments, set $MESSAGE_BODY/$HTML_MODE vars and some session data
459$MESSAGE_BODY = rcmail_prepare_message_body();
460
461
462/****** compose mode functions ********/
463
464function rcmail_compose_headers($attrib)
465{
466  global $MESSAGE;
467
468  list($form_start, $form_end) = get_form_tags($attrib);
469
470  $out  = '';
471  $part = strtolower($attrib['part']);
472
473  switch ($part)
474  {
475    case 'from':
476      return $form_start . rcmail_compose_header_from($attrib);
477
478    case 'to':
479    case 'cc':
480    case 'bcc':
481      $fname = '_' . $part;
482      $header = $param = $part;
483
484      $allow_attrib = array('id', 'class', 'style', 'cols', 'rows', 'tabindex');
485      $field_type = 'html_textarea';
486      break;
487
488    case 'replyto':
489    case 'reply-to':
490      $fname = '_replyto';
491      $param = 'replyto';
492      $header = 'reply-to';
493
494    case 'followupto':
495    case 'followup-to':
496      if (!$fname) {
497        $fname = '_followupto';
498        $param = 'followupto';
499        $header = 'mail-followup-to';
500      }
501
502      $allow_attrib = array('id', 'class', 'style', 'size', 'tabindex');
503      $field_type = 'html_inputfield';
504      break;
505  }
506
507  if ($fname && $field_type)
508  {
509    // pass the following attributes to the form class
510    $field_attrib = array('name' => $fname, 'spellcheck' => 'false');
511    foreach ($attrib as $attr => $value)
512      if (in_array($attr, $allow_attrib))
513        $field_attrib[$attr] = $value;
514
515    // create teaxtarea object
516    $input = new $field_type($field_attrib);
517    $out = $input->show($MESSAGE->compose[$param]);
518  }
519
520  if ($form_start)
521    $out = $form_start.$out;
522
523  // configure autocompletion
524  rcube_autocomplete_init();
525
526  return $out;
527}
528
529
530function rcmail_compose_header_from($attrib)
531{
532  global $MESSAGE, $OUTPUT;
533
534  // pass the following attributes to the form class
535  $field_attrib = array('name' => '_from');
536  foreach ($attrib as $attr => $value)
537    if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
538      $field_attrib[$attr] = $value;
539
540  if (count($MESSAGE->identities))
541  {
542    $a_signatures = array();
543
544    $field_attrib['onchange'] = JS_OBJECT_NAME.".change_identity(this)";
545    $select_from = new html_select($field_attrib);
546
547    // create SELECT element
548    foreach ($MESSAGE->identities as $sql_arr)
549    {
550      $identity_id = $sql_arr['identity_id'];
551      $select_from->add(format_email_recipient($sql_arr['email'], $sql_arr['name']), $identity_id);
552
553      // add signature to array
554      if (!empty($sql_arr['signature']) && empty($COMPOSE['param']['nosig']))
555      {
556        $a_signatures[$identity_id]['text'] = $sql_arr['signature'];
557        $a_signatures[$identity_id]['is_html'] = ($sql_arr['html_signature'] == 1) ? true : false;
558        if ($a_signatures[$identity_id]['is_html'])
559        {
560            $h2t = new html2text($a_signatures[$identity_id]['text'], false, false);
561            $a_signatures[$identity_id]['plain_text'] = trim($h2t->get_text());
562        }
563      }
564    }
565
566    $out = $select_from->show($MESSAGE->compose['from']);
567
568    // add signatures to client
569    $OUTPUT->set_env('signatures', $a_signatures);
570  }
571  // no identities, display text input field
572  else {
573    $field_attrib['class'] = 'from_address';
574    $input_from = new html_inputfield($field_attrib);
575    $out = $input_from->show($MESSAGE->compose['from']);
576  }
577
578  return $out;
579}
580
581
582function rcmail_compose_editor_mode()
583{
584  global $RCMAIL, $MESSAGE, $compose_mode;
585  static $useHtml;
586
587  if ($useHtml !== null)
588    return $useHtml;
589
590  $html_editor = intval($RCMAIL->config->get('htmleditor'));
591
592  if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
593    $useHtml = $MESSAGE->has_html_part(false);
594  }
595  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
596    $useHtml = ($html_editor == 1 || ($html_editor == 2 && $MESSAGE->has_html_part(false)));
597  }
598  else { // RCUBE_COMPOSE_FORWARD or NEW
599    $useHtml = ($html_editor == 1);
600  }
601
602  return $useHtml;
603}
604
605
606function rcmail_prepare_message_body()
607{
608  global $RCMAIL, $MESSAGE, $COMPOSE, $compose_mode, $LINE_LENGTH, $HTML_MODE;
609
610  // use posted message body
611  if (!empty($_POST['_message'])) {
612    $body = get_input_value('_message', RCUBE_INPUT_POST, true);
613    $isHtml = (bool) get_input_value('_is_html', RCUBE_INPUT_POST);
614  }
615  else if ($COMPOSE['param']['body']) {
616    $body = $COMPOSE['param']['body'];
617    $isHtml = false;
618  }
619  // forward as attachment
620  else if ($compose_mode == RCUBE_COMPOSE_FORWARD && $MESSAGE->forward_attachment) {
621    $isHtml = rcmail_compose_editor_mode();
622    $body = '';
623    if (empty($COMPOSE['attachments']))
624      rcmail_write_forward_attachment($MESSAGE);
625  }
626  // reply/edit/draft/forward
627  else if ($compose_mode) {
628    $isHtml = rcmail_compose_editor_mode();
629
630    if (!empty($MESSAGE->parts)) {
631      foreach ($MESSAGE->parts as $part) {
632        // skip no-content and attachment parts (#1488557)
633        if ($part->type != 'content' || !$part->size || $MESSAGE->is_attachment($part)) {
634          continue;
635        }
636
637        if ($part_body = rcmail_compose_part_body($part, $isHtml)) {
638          $body .= ($body ? ($isHtml ? '<br/>' : "\n") : '') . $part_body;
639        }
640      }
641    }
642    else {
643      $body = rcmail_compose_part_body($MESSAGE, $isHtml);
644    }
645
646    // compose reply-body
647    if ($compose_mode == RCUBE_COMPOSE_REPLY)
648      $body = rcmail_create_reply_body($body, $isHtml);
649    // forward message body inline
650    else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
651      $body = rcmail_create_forward_body($body, $isHtml);
652    // load draft message body
653    else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
654      $body = rcmail_create_draft_body($body, $isHtml);
655  }
656  else { // new message
657    $isHtml = rcmail_compose_editor_mode();
658  }
659
660  $plugin = $RCMAIL->plugins->exec_hook('message_compose_body',
661    array('body' => $body, 'html' => $isHtml, 'mode' => $compose_mode));
662  $body = $plugin['body'];
663  unset($plugin);
664
665  // add blocked.gif attachment (#1486516)
666  if ($isHtml && preg_match('#<img src="\./program/resources/blocked\.gif"#', $body)) {
667    if ($attachment = rcmail_save_image('program/resources/blocked.gif', 'image/gif')) {
668      $COMPOSE['attachments'][$attachment['id']] = $attachment;
669      $body = preg_replace('#\./program/resources/blocked\.gif#',
670        $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'].'&_id='.$COMPOSE['id'],
671        $body);
672    }
673  }
674
675  $HTML_MODE = $isHtml;
676
677  return $body;
678}
679
680function rcmail_compose_part_body($part, $isHtml = false)
681{
682    global $RCMAIL, $MESSAGE, $compose_mode;
683
684    // Check if we have enough memory to handle the message in it
685    // #1487424: we need up to 10x more memory than the body
686    if (!rcmail_mem_check($part->size * 10)) {
687        return '';
688    }
689
690    if (empty($part->ctype_parameters) || empty($part->ctype_parameters['charset'])) {
691        $part->ctype_parameters['charset'] = $MESSAGE->headers->charset;
692    }
693
694    // fetch part if not available
695    if (!isset($part->body)) {
696        $part->body = $MESSAGE->get_part_content($part->mime_id);
697    }
698
699    // message is cached but not exists (#1485443), or other error
700    if ($part->body === false) {
701        return '';
702    }
703
704    $body = $part->body;
705
706    if ($isHtml) {
707        if ($part->ctype_secondary == 'html') {
708        }
709        else {
710            // try to remove the signature
711            if ($RCMAIL->config->get('strip_existing_sig', true)) {
712                $body = rcmail_remove_signature($body);
713            }
714            // add HTML formatting
715            $body = rcmail_plain_body($body);
716            if ($body) {
717                $body = '<pre>' . $body . '</pre>';
718            }
719        }
720    }
721    else {
722        if ($part->ctype_secondary == 'html') {
723            // use html part if it has been used for message (pre)viewing
724            // decrease line length for quoting
725            $len = $compose_mode == RCUBE_COMPOSE_REPLY ? $LINE_LENGTH-2 : $LINE_LENGTH;
726            $txt = new html2text($body, false, true, $len);
727            $body = $txt->get_text();
728        }
729        else {
730            if ($part->ctype_secondary == 'plain' && $part->ctype_parameters['format'] == 'flowed') {
731                $body = rcube_mime::unfold_flowed($body);
732            }
733
734            // try to remove the signature
735            if ($RCMAIL->config->get('strip_existing_sig', true)) {
736                $body = rcmail_remove_signature($body);
737            }
738        }
739    }
740
741    return $body;
742}
743
744function rcmail_compose_body($attrib)
745{
746  global $RCMAIL, $CONFIG, $OUTPUT, $MESSAGE, $compose_mode, $LINE_LENGTH, $HTML_MODE, $MESSAGE_BODY;
747
748  list($form_start, $form_end) = get_form_tags($attrib);
749  unset($attrib['form']);
750
751  if (empty($attrib['id']))
752    $attrib['id'] = 'rcmComposeBody';
753
754  $attrib['name'] = '_message';
755
756  $isHtml = $HTML_MODE;
757
758  $out = $form_start ? "$form_start\n" : '';
759
760  $saveid = new html_hiddenfield(array('name' => '_draft_saveid', 'value' => $compose_mode==RCUBE_COMPOSE_DRAFT ? str_replace(array('<','>'), "", $MESSAGE->headers->messageID) : ''));
761  $out .= $saveid->show();
762
763  $drafttoggle = new html_hiddenfield(array('name' => '_draft', 'value' => 'yes'));
764  $out .= $drafttoggle->show();
765
766  $msgtype = new html_hiddenfield(array('name' => '_is_html', 'value' => ($isHtml?"1":"0")));
767  $out .= $msgtype->show();
768
769  // If desired, set this textarea to be editable by TinyMCE
770  if ($isHtml) {
771    $MESSAGE_BODY = htmlentities($MESSAGE_BODY, ENT_NOQUOTES, RCMAIL_CHARSET);
772    $attrib['class'] = 'mce_editor';
773    $attrib['is_escaped'] = true;
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', '_remote' => 1)),
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/resources/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 a certain container as active area to drop files onto
1596 */
1597function compose_file_drop_area($attrib)
1598{
1599    global $OUTPUT;
1600
1601    if ($attrib['id']) {
1602        $OUTPUT->add_gui_object('filedrop', $attrib['id']);
1603        $OUTPUT->set_env('filedrop', array('action' => 'upload', 'fieldname' => '_attachments'));
1604    }
1605}
1606
1607
1608// register UI objects
1609$OUTPUT->add_handlers(array(
1610  'composeheaders' => 'rcmail_compose_headers',
1611  'composesubject' => 'rcmail_compose_subject',
1612  'composebody' => 'rcmail_compose_body',
1613  'composeattachmentlist' => 'rcmail_compose_attachment_list',
1614  'composeattachmentform' => 'rcmail_compose_attachment_form',
1615  'composeattachment' => 'rcmail_compose_attachment_field',
1616  'filedroparea'    => 'compose_file_drop_area',
1617  'priorityselector' => 'rcmail_priority_selector',
1618  'editorselector' => 'rcmail_editor_selector',
1619  'receiptcheckbox' => 'rcmail_receipt_checkbox',
1620  'dsncheckbox' => 'rcmail_dsn_checkbox',
1621  'storetarget' => 'rcmail_store_target_selection',
1622  'addressbooks' => 'rcmail_addressbook_list',
1623  'addresslist' => 'rcmail_contacts_list',
1624));
1625
1626$OUTPUT->send('compose');
Note: See TracBrowser for help on using the repository browser.