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

Last change on this file since 5723 was 5723, checked in by thomasb, 17 months ago

Implement address book widget on compose screen

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