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

Last change on this file was 78c270c, checked in by Aleksander Machniak <alec@…>, 2 weeks ago

Fix bugs caught by static analysis

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