source: github/program/steps/mail/compose.inc @ 1f49ce5

HEADcourier-fixdev-browser-capabilitiespdorelease-0.6release-0.7release-0.8
Last change on this file since 1f49ce5 was 9f96643, checked in by alecpl <alec@…>, 3 years ago
  • Change reply prefix to display email address only if sender name doesn't exist (#1486550)
  • Property mode set to 100644
File size: 39.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-2009, Roundcube Dev. - Switzerland                 |
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
31// Nothing below is called during message composition, only at "new/forward/reply/draft" initialization or
32// if a compose-ID is given (i.e. when the compose step is opened in a new window/tab).
33// Since there are many ways to leave the compose page improperly, it seems necessary to clean-up an old
34// compose when a "new/forward/reply/draft" is called - otherwise the old session attachments will appear
35
36if (!is_array($_SESSION['compose']) || $_SESSION['compose']['id'] != get_input_value('_id', RCUBE_INPUT_GET))
37{
38  rcmail_compose_cleanup();
39  $_SESSION['compose'] = array(
40    'id' => uniqid(mt_rand()),
41    'param' => request2param(RCUBE_INPUT_GET),
42    'mailbox' => $IMAP->get_mailbox_name(),
43  );
44 
45  // process values like "mailto:foo@bar.com?subject=new+message&cc=another"
46  if ($_SESSION['compose']['param']['to']) {
47    // #1486037: remove "mailto:" prefix
48    $_SESSION['compose']['param']['to'] = preg_replace('/^mailto:/i', '', $_SESSION['compose']['param']['to']);
49    $mailto = explode('?', $_SESSION['compose']['param']['to']);
50    if (count($mailto) > 1) {
51      $_SESSION['compose']['param']['to'] = $mailto[0];
52      parse_str($mailto[1], $query);
53      foreach ($query as $f => $val)
54        $_SESSION['compose']['param'][$f] = $val;
55    }
56  }
57 
58  // select folder where to save the sent message
59  $_SESSION['compose']['param']['sent_mbox'] = $RCMAIL->config->get('sent_mbox');
60 
61  // pipe compose parameters thru plugins
62  $plugin = $RCMAIL->plugins->exec_hook('message_compose', $_SESSION['compose']);
63  $_SESSION['compose']['param'] = array_merge($_SESSION['compose']['param'], $plugin['param']);
64
65  // add attachments listed by message_compose hook
66  if (is_array($plugin['attachments'])) {
67    foreach ($plugin['attachments'] as $attach) {
68      // we have structured data
69      if (is_array($attach)) {
70        $attachment = $attach;
71      }
72      // only a file path is given
73      else {
74        $filename = basename($attach);
75        $attachment = array(
76          'name' => $filename,
77          'mimetype' => rc_mime_content_type($attach, $filename),
78          'path' => $attach
79        );
80      }
81     
82      // save attachment if valid
83      if (($attachment['data'] && $attachment['name']) || ($attachment['path'] && file_exists($attachment['path']))) {
84        $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
85      }
86     
87      if ($attachment['status'] && !$attachment['abort']) {
88        unset($attachment['data'], $attachment['status'], $attachment['abort']);
89        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
90      }
91    }
92  }
93
94  // check if folder for saving sent messages exists and is subscribed (#1486802)
95  if (($sent_folder = $_SESSION['compose']['param']['sent_mbox']) && !$IMAP->mailbox_exists($sent_folder, true)) {
96    // folder may exist but isn't subscribed (#1485241)
97    if (!$IMAP->mailbox_exists($sent_folder))
98      $IMAP->create_mailbox($sent_folder, true);
99    else
100      $IMAP->subscribe($sent_folder);
101  }
102
103  // redirect to a unique URL with all parameters stored in session
104  $OUTPUT->redirect(array('_action' => 'compose', '_id' => $_SESSION['compose']['id']));
105}
106
107
108// add some labels to client
109$OUTPUT->add_label('nosubject', 'nosenderwarning', 'norecipientwarning', 'nosubjectwarning', 'cancel',
110    'nobodywarning', 'notsentwarning', 'notuploadedwarning', 'savingmessage', 'sendingmessage',
111    'messagesaved', 'converting', 'editorwarning', 'searching', 'uploading', 'fileuploaderror');
112
113// add config parameters to client script
114if (!empty($CONFIG['drafts_mbox'])) {
115  $OUTPUT->set_env('drafts_mailbox', $CONFIG['drafts_mbox']);
116  $OUTPUT->set_env('draft_autosave', $CONFIG['draft_autosave']);
117}
118// set current mailbox in client environment
119$OUTPUT->set_env('mailbox', $IMAP->get_mailbox_name());
120$OUTPUT->set_env('sig_above', $CONFIG['sig_above']);
121$OUTPUT->set_env('top_posting', $CONFIG['top_posting']);
122
123// get reference message and set compose mode
124if ($msg_uid = $_SESSION['compose']['param']['reply_uid'])
125  $compose_mode = RCUBE_COMPOSE_REPLY;
126else if ($msg_uid = $_SESSION['compose']['param']['forward_uid'])
127  $compose_mode = RCUBE_COMPOSE_FORWARD;
128else if ($msg_uid = $_SESSION['compose']['param']['uid'])
129  $compose_mode = RCUBE_COMPOSE_EDIT;
130else if ($msg_uid = $_SESSION['compose']['param']['draft_uid']) {
131  $RCMAIL->imap->set_mailbox($CONFIG['drafts_mbox']);
132  $compose_mode = RCUBE_COMPOSE_DRAFT;
133}
134
135$config_show_sig = $RCMAIL->config->get('show_sig', 1);
136if ($config_show_sig == 1)
137  $OUTPUT->set_env('show_sig', true);
138else if ($config_show_sig == 2 && (empty($compose_mode) || $compose_mode == RCUBE_COMPOSE_EDIT || $compose_mode == RCUBE_COMPOSE_DRAFT))
139  $OUTPUT->set_env('show_sig', true);
140else if ($config_show_sig == 3 && ($compose_mode == RCUBE_COMPOSE_REPLY || $compose_mode == RCUBE_COMPOSE_FORWARD))
141  $OUTPUT->set_env('show_sig', true);
142else
143  $OUTPUT->set_env('show_sig', false);
144
145// set line length for body wrapping
146$LINE_LENGTH = $RCMAIL->config->get('line_length', 72);
147
148if (!empty($msg_uid))
149{
150  // similar as in program/steps/mail/show.inc
151  // re-set 'prefer_html' to have possibility to use html part for compose
152  $CONFIG['prefer_html'] = $CONFIG['prefer_html'] || $CONFIG['htmleditor'] || $compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT;
153  $MESSAGE = new rcube_message($msg_uid);
154 
155  // make sure message is marked as read
156  if ($MESSAGE && $MESSAGE->headers && !$MESSAGE->headers->seen)
157    $IMAP->set_flag($msg_uid, 'SEEN');
158
159  if (!empty($MESSAGE->headers->charset))
160    $IMAP->set_charset($MESSAGE->headers->charset);
161   
162  if ($compose_mode == RCUBE_COMPOSE_REPLY)
163  {
164    $_SESSION['compose']['reply_uid'] = $msg_uid;
165    $_SESSION['compose']['reply_msgid'] = $MESSAGE->headers->messageID;
166    $_SESSION['compose']['references']  = trim($MESSAGE->headers->references . " " . $MESSAGE->headers->messageID);
167
168    if (!empty($_SESSION['compose']['param']['all']))
169      $MESSAGE->reply_all = 1;
170
171    $OUTPUT->set_env('compose_mode', 'reply');
172  }
173  else if ($compose_mode == RCUBE_COMPOSE_DRAFT)
174  {
175    if ($MESSAGE->headers->others['x-draft-info'])
176    {
177      // get reply_uid/forward_uid to flag the original message when sending
178      $info = rcmail_draftinfo_decode($MESSAGE->headers->others['x-draft-info']);
179
180      if ($info['type'] == 'reply')
181        $_SESSION['compose']['reply_uid'] = $info['uid'];
182      else if ($info['type'] == 'forward')
183        $_SESSION['compose']['forward_uid'] = $info['uid'];
184
185      $_SESSION['compose']['mailbox'] = $info['folder'];
186    }
187   
188    if ($MESSAGE->headers->in_reply_to)
189      $_SESSION['compose']['reply_msgid'] = '<'.$MESSAGE->headers->in_reply_to.'>';
190
191    $_SESSION['compose']['references']  = $MESSAGE->headers->references;
192  }
193  else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
194  {
195    $_SESSION['compose']['forward_uid'] = $msg_uid;
196    $OUTPUT->set_env('compose_mode', 'forward');
197  }
198}
199
200// process $MESSAGE body/attachments, set $MESSAGE_BODY/$HTML_MODE vars and some session data
201$MESSAGE_BODY = rcmail_prepare_message_body();
202
203
204/****** compose mode functions ********/
205
206function rcmail_compose_headers($attrib)
207{
208  global $IMAP, $MESSAGE, $DB, $compose_mode;
209  static $sa_recipients = array();
210
211  list($form_start, $form_end) = get_form_tags($attrib);
212
213  $out = '';
214  $part = strtolower($attrib['part']);
215
216  switch ($part)
217  {
218    case 'from':
219      return $form_start . rcmail_compose_header_from($attrib);
220
221    case 'to':
222      $fname = '_to';
223      $header = $param = 'to';
224
225      // we have a set of recipients stored is session
226      if (($mailto_id = $_SESSION['compose']['param']['mailto']) && $_SESSION['mailto'][$mailto_id])
227        $fvalue = urldecode($_SESSION['mailto'][$mailto_id]);
228
229    case 'cc':
230      if (!$fname) {
231        $fname = '_cc';
232        $header = $param = 'cc';
233      }
234    case 'bcc':
235      if (!$fname) {
236        $fname = '_bcc';
237        $header = $param = 'bcc';
238      }
239
240      $allow_attrib = array('id', 'class', 'style', 'cols', 'rows', 'tabindex');
241      $field_type = 'html_textarea';
242      break;
243
244    case 'replyto':
245    case 'reply-to':
246      $fname = '_replyto';
247      $param = 'replyto';
248      $allow_attrib = array('id', 'class', 'style', 'size', 'tabindex');
249      $field_type = 'html_inputfield';
250      break;
251  }
252
253  if ($fname && !empty($_POST[$fname])) {
254    $fvalue = get_input_value($fname, RCUBE_INPUT_POST, TRUE);
255  }
256  else if ($fname && !$fvalue && !empty($_SESSION['compose']['param'][$param])) {
257    $fvalue = $_SESSION['compose']['param'][$param];
258  }
259  else if ($header && $compose_mode == RCUBE_COMPOSE_REPLY) {
260    // get recipent address(es) out of the message headers
261    if ($header=='to' && !empty($MESSAGE->headers->replyto))
262      $fvalue = $MESSAGE->headers->replyto;
263    else if ($header=='to' && !empty($MESSAGE->headers->from))
264      $fvalue = $MESSAGE->headers->from;
265    // add recipent of original message if reply to all
266    else if ($header=='cc' && !empty($MESSAGE->reply_all)) {
267      if ($v = $MESSAGE->headers->to)
268        $fvalue .= $v;
269
270      if ($v = $MESSAGE->headers->cc)
271        $fvalue .= (!empty($fvalue) ? ', ' : '') . $v;
272    }
273
274    // split recipients and put them back together in a unique way
275    if (!empty($fvalue)) {
276      $to_addresses = $IMAP->decode_address_list($fvalue);
277      $fvalue = '';
278
279      foreach ($to_addresses as $addr_part) {
280        if (empty($addr_part['mailto']))
281          continue;
282
283        $mailto = idn_to_utf8($addr_part['mailto']);
284
285        if (!in_array($mailto, $sa_recipients)
286            && (!$MESSAGE->compose_from
287                || !in_array_nocase($mailto, $MESSAGE->compose_from)
288                || (count($to_addresses)==1 && $header=='to')) // allow reply to yourself
289        ) {
290          if ($addr_part['name'] && $addr_part['mailto'] != $addr_part['name'])
291            $string = format_email_recipient($mailto, $addr_part['name']);
292          else
293            $string = $mailto;
294          $fvalue .= (strlen($fvalue) ? ', ':'') . $string;
295          $sa_recipients[] = $addr_part['mailto'];
296        }
297      }
298    }
299  }
300  else if ($header && in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))) {
301    // get drafted headers
302    if ($header=='to' && !empty($MESSAGE->headers->to))
303      $fvalue = $MESSAGE->get_header('to');
304    else if ($header=='cc' && !empty($MESSAGE->headers->cc))
305      $fvalue = $MESSAGE->get_header('cc');
306    else if ($header=='bcc' && !empty($MESSAGE->headers->bcc))
307      $fvalue = $MESSAGE->get_header('bcc');
308
309    $addresses = $IMAP->decode_address_list($fvalue);
310    $fvalue = '';
311
312    foreach ($addresses as $addr_part) {
313      if (empty($addr_part['mailto']))
314        continue;
315
316      $mailto = idn_to_utf8($addr_part['mailto']);
317
318      if ($addr_part['name'] && $addr_part['mailto'] != $addr_part['name'])
319        $string = format_email_recipient($mailto, $addr_part['name']);
320      else
321        $string = $mailto;
322      $fvalue .= (strlen($fvalue) ? ', ':'') . $string;
323    }
324  }
325
326
327  if ($fname && $field_type)
328  {
329    // pass the following attributes to the form class
330    $field_attrib = array('name' => $fname, 'spellcheck' => 'false');
331    foreach ($attrib as $attr => $value)
332      if (in_array($attr, $allow_attrib))
333        $field_attrib[$attr] = $value;
334
335    // create teaxtarea object
336    $input = new $field_type($field_attrib);
337    $out = $input->show($fvalue);
338  }
339 
340  if ($form_start)
341    $out = $form_start.$out;
342
343  return $out;
344}
345
346
347function rcmail_compose_header_from($attrib)
348{
349  global $IMAP, $MESSAGE, $DB, $USER, $OUTPUT, $compose_mode;
350   
351  // pass the following attributes to the form class
352  $field_attrib = array('name' => '_from');
353  foreach ($attrib as $attr => $value)
354    if (in_array($attr, array('id', 'class', 'style', 'size', 'tabindex')))
355      $field_attrib[$attr] = $value;
356
357  // extract all recipients of the reply-message
358  $a_recipients = array();
359  if ($compose_mode == RCUBE_COMPOSE_REPLY && is_object($MESSAGE->headers))
360  {
361    $MESSAGE->compose_from = array();
362
363    $a_to = $IMAP->decode_address_list($MESSAGE->headers->to);
364    foreach ($a_to as $addr)
365    {
366      if (!empty($addr['mailto']))
367        $a_recipients[] = mb_strtolower(idn_to_utf8($addr['mailto']));
368    }
369
370    if (!empty($MESSAGE->headers->cc))
371    {
372      $a_cc = $IMAP->decode_address_list($MESSAGE->headers->cc);
373      foreach ($a_cc as $addr)
374      {
375        if (!empty($addr['mailto']))
376          $a_recipients[] = mb_strtolower(idn_to_utf8($addr['mailto']));
377      }
378    }
379  }
380
381  // get this user's identities
382  $user_identities = $USER->list_identities();
383
384  if (count($user_identities))
385  {
386    $from_id = 0;
387    $a_signatures = array();
388
389    $field_attrib['onchange'] = JS_OBJECT_NAME.".change_identity(this)";
390    $select_from = new html_select($field_attrib);
391
392    foreach ($user_identities as $sql_arr)
393    {
394      $sql_arr['email'] = mb_strtolower(idn_to_utf8($sql_arr['email']));
395      $identity_id = $sql_arr['identity_id'];
396      $select_from->add(format_email_recipient($sql_arr['email'], $sql_arr['name']), $identity_id);
397
398      // add signature to array
399      if (!empty($sql_arr['signature']) && empty($_SESSION['compose']['param']['nosig']))
400      {
401        $a_signatures[$identity_id]['text'] = $sql_arr['signature'];
402        $a_signatures[$identity_id]['is_html'] = ($sql_arr['html_signature'] == 1) ? true : false;
403        if ($a_signatures[$identity_id]['is_html'])
404        {
405            $h2t = new html2text($a_signatures[$identity_id]['text'], false, false);
406            $a_signatures[$identity_id]['plain_text'] = trim($h2t->get_text());
407        }
408      }
409
410      if ($compose_mode == RCUBE_COMPOSE_REPLY && is_array($MESSAGE->compose_from))
411        $MESSAGE->compose_from[] = $sql_arr['email'];
412
413      if (empty($_POST['_from']) && empty($_SESSION['compose']['param']['from']))
414      {
415        // set draft's identity
416        if ($compose_mode == RCUBE_COMPOSE_DRAFT && strstr($MESSAGE->headers->from, $sql_arr['email']))
417          $from_id = $sql_arr['identity_id'];
418        // set identity if it's one of the reply-message recipients (with prio for default identity)
419        else if (in_array($sql_arr['email'], $a_recipients) && (empty($from_id) || $sql_arr['standard']))
420          $from_id = $sql_arr['identity_id'];
421      }
422    }
423
424    // overwrite identity selection with post parameter
425    if (!empty($_POST['_from']))
426      $from_id = get_input_value('_from', RCUBE_INPUT_POST);
427    else if (!empty($_SESSION['compose']['param']['from']))
428      $from_id = $_SESSION['compose']['param']['from'];
429
430    $out = $select_from->show($from_id);
431
432    // add signatures to client
433    $OUTPUT->set_env('signatures', $a_signatures);
434  }
435  else
436  {
437    $input_from = new html_inputfield($field_attrib);
438    $out = $input_from->show($_POST['_from']);
439  }
440
441  return $out;
442}
443
444
445function rcmail_prepare_message_body()
446{
447  global $RCMAIL, $CONFIG, $MESSAGE, $compose_mode, $LINE_LENGTH, $HTML_MODE;
448
449  if ($CONFIG['htmleditor'] || (($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) && $MESSAGE->has_html_part()))
450    $isHtml = true;
451  else
452    $isHtml = false;
453
454  $body = '';
455
456  // use posted message body
457  if (!empty($_POST['_message']))
458  {
459    $body = get_input_value('_message', RCUBE_INPUT_POST, true);
460  }
461  else if ($_SESSION['compose']['param']['body'])
462  {
463    $body = $_SESSION['compose']['param']['body'];
464    $isHtml = false;
465  }
466  else if ($compose_mode)
467  {
468    $has_html_part = $MESSAGE->has_html_part();
469    if (($isHtml || $compose_mode == RCUBE_COMPOSE_DRAFT) && $has_html_part)
470    {
471      $body = $MESSAGE->first_html_part();
472      $isHtml = true;
473    }
474    else if ($has_html_part)
475    {
476      // use html part if it has been used for message (pre)viewing
477      // decrease line length for quoting
478      $len = $compose_mode == RCUBE_COMPOSE_REPLY ? $LINE_LENGTH-2 : $LINE_LENGTH;
479      $txt = new html2text($MESSAGE->first_html_part(), false, true, $len);
480      $body = $txt->get_text();
481      $isHtml = false;
482    }
483    else
484    {
485      $body = $MESSAGE->first_text_part();
486      $isHtml = false;
487    }
488
489    // compose reply-body
490    if ($compose_mode == RCUBE_COMPOSE_REPLY)
491      $body = rcmail_create_reply_body($body, $isHtml);
492    // forward message body inline
493    else if ($compose_mode == RCUBE_COMPOSE_FORWARD)
494      $body = rcmail_create_forward_body($body, $isHtml);
495    // load draft message body
496    else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
497      $body = rcmail_create_draft_body($body, $isHtml);
498  }
499
500  $plugin = $RCMAIL->plugins->exec_hook('message_compose_body',
501    array('body' => $body, 'html' => $isHtml, 'mode' => $compose_mode));
502  $body = $plugin['body'];
503  unset($plugin);
504
505  // add blocked.gif attachment (#1486516)
506  if ($isHtml && preg_match('#<img src="\./program/blocked\.gif"#', $body)) {
507    if ($attachment = rcmail_save_image('program/blocked.gif', 'image/gif')) {
508      $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
509      $body = preg_replace('#\./program/blocked\.gif#',
510        $RCMAIL->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'],
511        $body);
512    }
513  }
514 
515  $HTML_MODE = $isHtml;
516 
517  return $body;
518}
519
520function rcmail_compose_body($attrib)
521{
522  global $RCMAIL, $CONFIG, $OUTPUT, $MESSAGE, $compose_mode, $LINE_LENGTH, $HTML_MODE, $MESSAGE_BODY;
523 
524  list($form_start, $form_end) = get_form_tags($attrib);
525  unset($attrib['form']);
526 
527  if (empty($attrib['id']))
528    $attrib['id'] = 'rcmComposeBody';
529
530  $attrib['name'] = '_message';
531
532  $isHtml = $HTML_MODE;
533 
534  $out = $form_start ? "$form_start\n" : '';
535
536  $saveid = new html_hiddenfield(array('name' => '_draft_saveid', 'value' => $compose_mode==RCUBE_COMPOSE_DRAFT ? str_replace(array('<','>'), "", $MESSAGE->headers->messageID) : ''));
537  $out .= $saveid->show();
538
539  $drafttoggle = new html_hiddenfield(array('name' => '_draft', 'value' => 'yes'));
540  $out .= $drafttoggle->show();
541
542  $msgtype = new html_hiddenfield(array('name' => '_is_html', 'value' => ($isHtml?"1":"0")));
543  $out .= $msgtype->show();
544
545  // If desired, set this textarea to be editable by TinyMCE
546  if ($isHtml) $attrib['class'] = 'mce_editor';
547  $textarea = new html_textarea($attrib);
548  $out .= $textarea->show($MESSAGE_BODY);
549  $out .= $form_end ? "\n$form_end" : '';
550
551  $OUTPUT->set_env('composebody', $attrib['id']);
552
553  // include HTML editor
554  rcube_html_editor();
555 
556  // include GoogieSpell
557  if (!empty($CONFIG['enable_spellcheck'])) {
558
559    $engine = $RCMAIL->config->get('spellcheck_engine','googie');
560    $spellcheck_langs = (array) $RCMAIL->config->get('spellcheck_languages',
561      array('da'=>'Dansk', 'de'=>'Deutsch', 'en' => 'English', 'es'=>'Español',
562            'fr'=>'Français', 'it'=>'Italiano', 'nl'=>'Nederlands', 'pl'=>'Polski',
563            'pt'=>'Português', 'fi'=>'Suomi', 'sv'=>'Svenska'));
564
565    // googie works only with two-letter codes
566    if ($engine == 'googie') {
567      $lang = strtolower(substr($_SESSION['language'], 0, 2));
568
569      $spellcheck_langs_googie = array();
570      foreach ($spellcheck_langs as $key => $name)
571        $spellcheck_langs_googie[strtolower(substr($key,0,2))] = $name;
572        $spellcheck_langs = $spellcheck_langs_googie;
573    }
574    else {
575      $lang = $_SESSION['language'];
576
577      // if not found in the list, try with two-letter code
578      if (!$spellcheck_langs[$lang])
579        $lang = strtolower(substr($lang, 0, 2));
580    }
581
582    if (!$spellcheck_langs[$lang])
583      $lang = 'en';
584
585    $editor_lang_set = array();
586    foreach ($spellcheck_langs as $key => $name) {
587      $editor_lang_set[] = ($key == $lang ? '+' : '') . JQ($name).'='.JQ($key);
588    }
589   
590    $OUTPUT->include_script('googiespell.js');
591    $OUTPUT->add_script(sprintf(
592      "var googie = new GoogieSpell('\$__skin_path/images/googiespell/','?_task=utils&_action=spell&lang=');\n".
593      "googie.lang_chck_spell = \"%s\";\n".
594      "googie.lang_rsm_edt = \"%s\";\n".
595      "googie.lang_close = \"%s\";\n".
596      "googie.lang_revert = \"%s\";\n".
597      "googie.lang_no_error_found = \"%s\";\n".
598      "googie.setLanguages(%s);\n".
599      "googie.setCurrentLanguage('%s');\n".
600      "googie.setSpellContainer('spellcheck-control');\n".
601      "googie.decorateTextarea('%s');\n".
602      "%s.set_env('spellcheck', googie);",
603      JQ(Q(rcube_label('checkspelling'))),
604      JQ(Q(rcube_label('resumeediting'))),
605      JQ(Q(rcube_label('close'))),
606      JQ(Q(rcube_label('revertto'))),
607      JQ(Q(rcube_label('nospellerrors'))),
608      json_serialize($spellcheck_langs),
609      $lang,
610      $attrib['id'],
611      JS_OBJECT_NAME), 'foot');
612
613    $OUTPUT->add_label('checking');
614    $OUTPUT->set_env('spellcheck_langs', join(',', $editor_lang_set));
615  }
616 
617  $out .= "\n".'<iframe name="savetarget" src="program/blank.gif" style="width:0;height:0;border:none;visibility:hidden;"></iframe>';
618
619  return $out;
620}
621
622
623function rcmail_create_reply_body($body, $bodyIsHtml)
624{
625  global $RCMAIL, $MESSAGE, $LINE_LENGTH;
626
627  // build reply prefix
628  $from = array_pop($RCMAIL->imap->decode_address_list($MESSAGE->get_header('from')));
629  $prefix = sprintf("On %s, %s wrote:",
630    $MESSAGE->headers->date, $from['name'] ? $from['name'] : idn_to_utf8($from['email']));
631
632  if (!$bodyIsHtml) {
633    $body = preg_replace('/\r?\n/', "\n", $body);
634
635    // try to remove the signature
636    if ($RCMAIL->config->get('strip_existing_sig', true)) {
637      $len = strlen($body);
638      while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
639        if ($sp == 0 || $body[$sp-1] == "\n") {
640          // do not touch blocks with more that X lines
641          if (substr_count($body, "\n", $sp) < $RCMAIL->config->get('sig_max_lines', 15)) {
642            $body = substr($body, 0, max(0, $sp-1));
643          }
644          break;
645        }
646      }
647    }
648
649    // soft-wrap and quote message text
650    $body = rcmail_wrap_and_quote(rtrim($body, "\n"), $LINE_LENGTH);
651
652    $prefix .= "\n";
653    $suffix = '';
654
655    if ($RCMAIL->config->get('top_posting'))
656      $prefix = "\n\n\n" . $prefix;
657  }
658  else {
659    // save inline images to files
660    $cid_map = rcmail_write_inline_attachments($MESSAGE);
661    // set is_safe flag (we need this for html body washing)
662    rcmail_check_safe($MESSAGE);
663    // clean up html tags
664    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
665
666    // build reply (quote content)
667    $prefix = '<p>' . Q($prefix) . "</p>\n";
668    $prefix .= '<blockquote>';
669
670    if ($RCMAIL->config->get('top_posting')) {
671      $prefix = '<br>' . $prefix;
672      $suffix = '</blockquote>';
673    }
674    else {
675      $suffix = '</blockquote><p></p>';
676    }
677  }
678
679  return $prefix.$body.$suffix;
680}
681
682
683function rcmail_create_forward_body($body, $bodyIsHtml)
684{
685  global $IMAP, $MESSAGE, $OUTPUT;
686
687  // add attachments
688  if (!isset($_SESSION['compose']['forward_attachments']) && is_array($MESSAGE->mime_parts))
689    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
690
691  if (!$bodyIsHtml)
692  {
693    $prefix = "\n\n\n-------- Original Message --------\n";
694    $prefix .= 'Subject: ' . $MESSAGE->subject . "\n";
695    $prefix .= 'Date: ' . $MESSAGE->headers->date . "\n";
696    $prefix .= 'From: ' . $MESSAGE->get_header('from') . "\n";
697    $prefix .= 'To: ' . $MESSAGE->get_header('to') . "\n";
698
699    if ($MESSAGE->headers->cc)
700      $prefix .= 'Cc: ' . $MESSAGE->get_header('cc') . "\n";
701    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
702      $prefix .= 'Reply-To: ' . $MESSAGE->get_header('replyto') . "\n";
703
704    $prefix .= "\n";
705  }
706  else
707  {
708    // set is_safe flag (we need this for html body washing)
709    rcmail_check_safe($MESSAGE);
710    // clean up html tags
711    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
712
713    $prefix = sprintf(
714      "<br /><p>-------- Original Message --------</p>" .
715        "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" .
716        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Subject: </th><td>%s</td></tr>" .
717        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Date: </th><td>%s</td></tr>" .
718        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">From: </th><td>%s</td></tr>" .
719        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">To: </th><td>%s</td></tr>",
720      Q($MESSAGE->subject),
721      Q($MESSAGE->headers->date),
722      htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()),
723      htmlspecialchars(Q($MESSAGE->get_header('to'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
724
725    if ($MESSAGE->headers->cc)
726      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Cc: </th><td>%s</td></tr>",
727        htmlspecialchars(Q($MESSAGE->get_header('cc'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
728
729    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
730      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Reply-To: </th><td>%s</td></tr>",
731        htmlspecialchars(Q($MESSAGE->get_header('replyto'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
732
733    $prefix .= "</tbody></table><br>";
734  }
735   
736  return $prefix.$body;
737}
738
739
740function rcmail_create_draft_body($body, $bodyIsHtml)
741{
742  global $MESSAGE, $OUTPUT;
743 
744  /**
745   * add attachments
746   * sizeof($MESSAGE->mime_parts can be 1 - e.g. attachment, but no text!
747   */
748  if (empty($_SESSION['compose']['forward_attachments'])
749      && is_array($MESSAGE->mime_parts)
750      && count($MESSAGE->mime_parts) > 0)
751  {
752    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
753
754    // replace cid with href in inline images links
755    if ($cid_map)
756      $body = str_replace(array_keys($cid_map), array_values($cid_map), $body);
757  }
758 
759  return $body;
760}
761 
762 
763function rcmail_write_compose_attachments(&$message, $bodyIsHtml)
764{
765  global $OUTPUT;
766
767  $cid_map = $messages = array();
768  foreach ((array)$message->mime_parts as $pid => $part)
769  {
770    if (($part->ctype_primary != 'message' || !$bodyIsHtml) && $part->ctype_primary != 'multipart' &&
771        ($part->disposition == 'attachment' || ($part->disposition == 'inline' && $bodyIsHtml) || $part->filename)
772        && $part->mimetype != 'application/ms-tnef'
773    ) {
774      $skip = false;
775      if ($part->mimetype == 'message/rfc822') {
776        $messages[] = $part->mime_id;
777      } else if ($messages) {
778        // skip attachments included in message/rfc822 attachment (#1486487)
779        foreach ($messages as $mimeid)
780          if (strpos($part->mime_id, $mimeid.'.') === 0) {
781            $skip = true;
782            break;
783          }
784      }
785
786      if (!$skip && ($attachment = rcmail_save_attachment($message, $pid))) {
787        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
788        if ($bodyIsHtml && ($part->content_id || $part->content_location)) {
789          $url = $OUTPUT->app->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'];
790          if ($part->content_id)
791            $cid_map['cid:'.$part->content_id] = $url;
792          else
793            $cid_map[$part->content_location] = $url;
794        }
795      }
796    }
797  }
798
799  $_SESSION['compose']['forward_attachments'] = true;
800
801  return $cid_map;
802}
803
804
805function rcmail_write_inline_attachments(&$message)
806{
807  global $OUTPUT;
808
809  $cid_map = array();
810  foreach ((array)$message->mime_parts as $pid => $part) {
811    if (($part->content_id || $part->content_location) && $part->filename) {
812      if ($attachment = rcmail_save_attachment($message, $pid)) {
813        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
814        $url = $OUTPUT->app->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'];
815        if ($part->content_id)
816          $cid_map['cid:'.$part->content_id] = $url;
817        else
818          $cid_map[$part->content_location] = $url;
819      }
820    }
821  }
822
823  return $cid_map;
824}
825
826function rcmail_save_attachment(&$message, $pid)
827{
828  $part = $message->mime_parts[$pid];
829  $mem_limit = parse_bytes(ini_get('memory_limit'));
830  $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
831  $data = $path = null;
832
833  // don't load too big attachments into memory
834  if ($mem_limit > 0 && $part->size > $mem_limit - $curr_mem) {
835    $rcmail = rcmail::get_instance();
836    $temp_dir = unslashify($rcmail->config->get('temp_dir'));
837    $path = tempnam($temp_dir, 'rcmAttmnt');
838    if ($fp = fopen($path, 'w')) {
839      $message->get_part_content($pid, $fp);
840      fclose($fp);
841    } else
842      return false;
843  } else {
844    $data = $message->get_part_content($pid);
845  }
846
847  $attachment = array(
848    'name' => $part->filename ? $part->filename : 'Part_'.$pid.'.'.$part->ctype_secondary,
849    'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
850    'content_id' => $part->content_id,
851    'data' => $data,
852    'path' => $path,
853    'size' => $path ? filesize($path) : strlen($data),
854  );
855
856  $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
857
858  if ($attachment['status']) {
859    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
860    return $attachment;
861  } else if ($path) {
862    @unlink($path);
863  }
864 
865  return false;
866}
867
868function rcmail_save_image($path, $mimetype='')
869{
870  // handle attachments in memory
871  $data = file_get_contents($path);
872
873  $attachment = array(
874    'name' => rcmail_basename($path),
875    'mimetype' => $mimetype ? $mimetype : rc_mime_content_type($path, $name),
876    'data' => $data,
877    'size' => strlen($data),
878  );
879
880  $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
881
882  if ($attachment['status']) {
883    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
884    return $attachment;
885  }
886 
887  return false;
888}
889
890function rcmail_basename($filename)
891{
892  // basename() is not unicode safe and locale dependent
893  if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
894    return preg_replace('/^.*[\\\\\\/]/', '', $filename);
895  } else {
896    return preg_replace('/^.*[\/]/', '', $filename);
897  }
898}
899
900function rcmail_compose_subject($attrib)
901{
902  global $MESSAGE, $compose_mode;
903 
904  list($form_start, $form_end) = get_form_tags($attrib);
905  unset($attrib['form']);
906 
907  $attrib['name'] = '_subject';
908  $attrib['spellcheck'] = 'true';
909  $textfield = new html_inputfield($attrib);
910
911  $subject = '';
912
913  // use subject from post
914  if (isset($_POST['_subject'])) {
915    $subject = get_input_value('_subject', RCUBE_INPUT_POST, TRUE);
916  }
917  // create a reply-subject
918  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
919    if (preg_match('/^re:/i', $MESSAGE->subject))
920      $subject = $MESSAGE->subject;
921    else
922      $subject = 'Re: '.$MESSAGE->subject;
923  }
924  // create a forward-subject
925  else if ($compose_mode == RCUBE_COMPOSE_FORWARD) {
926    if (preg_match('/^fwd:/i', $MESSAGE->subject))
927      $subject = $MESSAGE->subject;
928    else
929      $subject = 'Fwd: '.$MESSAGE->subject;
930  }
931  // creeate a draft-subject
932  else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
933    $subject = $MESSAGE->subject;
934  }
935  else if (!empty($_SESSION['compose']['param']['subject'])) {
936    $subject = $_SESSION['compose']['param']['subject'];
937  }
938 
939  $out = $form_start ? "$form_start\n" : '';
940  $out .= $textfield->show($subject);
941  $out .= $form_end ? "\n$form_end" : '';
942
943  return $out;
944}
945
946
947function rcmail_compose_attachment_list($attrib)
948{
949  global $OUTPUT, $CONFIG;
950 
951  // add ID if not given
952  if (!$attrib['id'])
953    $attrib['id'] = 'rcmAttachmentList';
954 
955  $out = "\n";
956  $jslist = array();
957
958  if (is_array($_SESSION['compose']['attachments']))
959  {
960    if ($attrib['deleteicon']) {
961      $button = html::img(array(
962        'src' => $CONFIG['skin_path'] . $attrib['deleteicon'],
963        'alt' => rcube_label('delete')
964      ));
965    }
966    else
967      $button = Q(rcube_label('delete'));
968
969    foreach ($_SESSION['compose']['attachments'] as $id => $a_prop)
970    {
971      if (empty($a_prop))
972        continue;
973     
974      $out .= html::tag('li', array('id' => 'rcmfile'.$id),
975        html::a(array(
976            'href' => "#delete",
977            'title' => rcube_label('delete'),
978            'onclick' => sprintf("return %s.command('remove-attachment','rcmfile%s', this)", JS_OBJECT_NAME, $id)),
979          $button) . Q($a_prop['name']));
980       
981        $jslist['rcmfile'.$id] = array('name' => $a_prop['name'], 'complete' => true, 'mimetype' => $a_prop['mimetype']);
982    }
983  }
984
985  if ($attrib['deleteicon'])
986    $_SESSION['compose']['deleteicon'] = $CONFIG['skin_path'] . $attrib['deleteicon'];
987  if ($attrib['cancelicon'])
988    $OUTPUT->set_env('cancelicon', $CONFIG['skin_path'] . $attrib['cancelicon']);
989  if ($attrib['loadingicon'])
990    $OUTPUT->set_env('loadingicon', $CONFIG['skin_path'] . $attrib['loadingicon']);
991
992  $OUTPUT->set_env('attachments', $jslist);
993  $OUTPUT->add_gui_object('attachmentlist', $attrib['id']);
994   
995  return html::tag('ul', $attrib, $out, html::$common_attrib);
996}
997
998
999function rcmail_compose_attachment_form($attrib)
1000{
1001  global $OUTPUT;
1002
1003  // add ID if not given
1004  if (!$attrib['id'])
1005    $attrib['id'] = 'rcmUploadbox';
1006
1007  // find max filesize value
1008  $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
1009  $max_postsize = parse_bytes(ini_get('post_max_size'));
1010  if ($max_postsize && $max_postsize < $max_filesize)
1011    $max_filesize = $max_postsize;
1012  $max_filesize = show_bytes($max_filesize);
1013 
1014  $button = new html_inputfield(array('type' => 'button'));
1015 
1016  $out = html::div($attrib,
1017    $OUTPUT->form_tag(array('name' => 'uploadform', 'method' => 'post', 'enctype' => 'multipart/form-data'),
1018      html::div(null, rcmail_compose_attachment_field(array('size' => $attrib[attachmentfieldsize]))) .
1019      html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize)))) .
1020      html::div('buttons',
1021        $button->show(rcube_label('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()")) . ' ' .
1022        $button->show(rcube_label('upload'), array('class' => 'button mainaction', 'onclick' => JS_OBJECT_NAME . ".command('send-attachment', this.form)"))
1023      )
1024    )
1025  );
1026 
1027  $OUTPUT->add_gui_object('uploadbox', $attrib['id']);
1028  return $out;
1029}
1030
1031
1032function rcmail_compose_attachment_field($attrib)
1033{
1034  $attrib['type'] = 'file';
1035  $attrib['name'] = '_attachments[]';
1036  $field = new html_inputfield($attrib);
1037  return $field->show();
1038}
1039
1040
1041function rcmail_priority_selector($attrib)
1042{
1043  global $MESSAGE;
1044 
1045  list($form_start, $form_end) = get_form_tags($attrib);
1046  unset($attrib['form']);
1047
1048  $attrib['name'] = '_priority';
1049  $selector = new html_select($attrib);
1050
1051  $selector->add(array(rcube_label('lowest'),
1052                       rcube_label('low'),
1053                       rcube_label('normal'),
1054                       rcube_label('high'),
1055                       rcube_label('highest')),
1056                 array(5, 4, 0, 2, 1));
1057
1058  if (isset($_POST['_priority']))
1059    $sel = $_POST['_priority'];
1060  else if (intval($MESSAGE->headers->priority) != 3)
1061    $sel = intval($MESSAGE->headers->priority);
1062  else
1063    $sel = 0;
1064
1065  $out = $form_start ? "$form_start\n" : '';
1066  $out .= $selector->show($sel);
1067  $out .= $form_end ? "\n$form_end" : '';
1068
1069  return $out;
1070}
1071
1072
1073function rcmail_receipt_checkbox($attrib)
1074{
1075  global $RCMAIL, $MESSAGE, $compose_mode;
1076
1077  list($form_start, $form_end) = get_form_tags($attrib);
1078  unset($attrib['form']);
1079
1080  if (!isset($attrib['id']))
1081    $attrib['id'] = 'receipt'; 
1082
1083  $attrib['name'] = '_receipt';
1084  $attrib['value'] = '1';
1085  $checkbox = new html_checkbox($attrib);
1086
1087  if ($MESSAGE && in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT)))
1088    $mdn_default = (bool) $MESSAGE->headers->mdn_to;
1089  else
1090    $mdn_default = $RCMAIL->config->get('mdn_default');
1091
1092  $out = $form_start ? "$form_start\n" : '';
1093  $out .= $checkbox->show($mdn_default);
1094  $out .= $form_end ? "\n$form_end" : '';
1095
1096  return $out;
1097}
1098
1099
1100function rcmail_editor_selector($attrib)
1101{
1102  global $CONFIG, $MESSAGE, $compose_mode;
1103
1104  // determine whether HTML or plain text should be checked
1105  if ($compose_mode)
1106    $useHtml = (($CONFIG['htmleditor'] || $compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
1107        && $MESSAGE->has_html_part());
1108  else
1109    $useHtml = $CONFIG['htmleditor'] ? true : false;
1110
1111  if (empty($attrib['editorid']))
1112    $attrib['editorid'] = 'rcmComposeBody';
1113
1114  if (empty($attrib['name']))
1115    $attrib['name'] = 'editorSelect';
1116
1117  $attrib['onchange'] = "return rcmail_toggle_editor(this, '".$attrib['editorid']."', '_is_html')";
1118
1119  $select = new html_select($attrib);
1120
1121  $select->add(Q(rcube_label('htmltoggle')), 'html');
1122  $select->add(Q(rcube_label('plaintoggle')), 'plain');
1123
1124  return $select->show($useHtml ? 'html' : 'plain');
1125
1126  foreach ($choices as $value => $text)
1127  {
1128    $attrib['id'] = '_' . $value;
1129    $attrib['value'] = $value;
1130    $selector .= $radio->show($chosenvalue, $attrib) . html::label($attrib['id'], Q(rcube_label($text)));
1131  }
1132
1133  return $selector;
1134}
1135
1136
1137function rcmail_store_target_selection($attrib)
1138{
1139  $attrib['name'] = '_store_target';
1140  $select = rcmail_mailbox_select(array_merge($attrib, array('noselection' => '- '.rcube_label('dontsave').' -')));
1141  return $select->show($_SESSION['compose']['param']['sent_mbox'], $attrib);
1142}
1143
1144
1145function get_form_tags($attrib)
1146{
1147  global $RCMAIL, $MESSAGE_FORM;
1148
1149  $form_start = '';
1150  if (!$MESSAGE_FORM)
1151  {
1152    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
1153    $hiddenfields->add(array('name' => '_action', 'value' => 'send'));
1154
1155    $form_start = empty($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
1156    $form_start .= $hiddenfields->show();
1157  }
1158   
1159  $form_end = ($MESSAGE_FORM && !strlen($attrib['form'])) ? '</form>' : '';
1160  $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
1161 
1162  if (!$MESSAGE_FORM)
1163    $RCMAIL->output->add_gui_object('messageform', $form_name);
1164 
1165  $MESSAGE_FORM = $form_name;
1166
1167  return array($form_start, $form_end);
1168}
1169
1170
1171// register UI objects
1172$OUTPUT->add_handlers(array(
1173  'composeheaders' => 'rcmail_compose_headers',
1174  'composesubject' => 'rcmail_compose_subject',
1175  'composebody' => 'rcmail_compose_body',
1176  'composeattachmentlist' => 'rcmail_compose_attachment_list',
1177  'composeattachmentform' => 'rcmail_compose_attachment_form',
1178  'composeattachment' => 'rcmail_compose_attachment_field',
1179  'priorityselector' => 'rcmail_priority_selector',
1180  'editorselector' => 'rcmail_editor_selector',
1181  'receiptcheckbox' => 'rcmail_receipt_checkbox',
1182  'storetarget' => 'rcmail_store_target_selection',
1183));
1184
1185$OUTPUT->send('compose');
1186
1187
Note: See TracBrowser for help on using the repository browser.