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

Last change on this file since 4009 was 4009, checked in by alec, 3 years ago
  • Add Internationalized Domain Name (IDNA) support (#1483894)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 39.1 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  if (!$bodyIsHtml) {
628    $body = preg_replace('/\r?\n/', "\n", $body);
629 
630    // try to remove the signature
631    if ($RCMAIL->config->get('strip_existing_sig', true)) {
632      $len = strlen($body);
633      while (($sp = strrpos($body, "-- \n", $sp ? -$len+$sp-1 : 0)) !== false) {
634        if ($sp == 0 || $body[$sp-1] == "\n") {
635          // do not touch blocks with more that X lines
636          if (substr_count($body, "\n", $sp) < $RCMAIL->config->get('sig_max_lines', 15)) {
637            $body = substr($body, 0, max(0, $sp-1));
638          }
639          break;
640        }
641      }
642    }
643
644    // soft-wrap and quote message text
645    $body = rcmail_wrap_and_quote(rtrim($body, "\n"), $LINE_LENGTH);
646
647    // add title line(s)
648    $prefix = sprintf("On %s, %s wrote:\n",
649      $MESSAGE->headers->date,
650      $MESSAGE->get_header('from'));
651
652    $suffix = '';
653   
654    if ($RCMAIL->config->get('top_posting'))
655      $prefix = "\n\n\n" . $prefix;
656  }
657  else {
658    // save inline images to files
659    $cid_map = rcmail_write_inline_attachments($MESSAGE);
660    // set is_safe flag (we need this for html body washing)
661    rcmail_check_safe($MESSAGE);
662    // clean up html tags
663    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
664
665    // build reply (quote content)
666    $prefix = sprintf("<p>On %s, %s wrote:</p>\n",
667      $MESSAGE->headers->date,
668      htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $RCMAIL->output->get_charset()));
669    $prefix .= '<blockquote>';
670
671    if ($RCMAIL->config->get('top_posting')) {
672      $prefix = '<br>' . $prefix;
673      $suffix = '</blockquote>';
674    }
675    else {
676      $suffix = '</blockquote><p></p>';
677    }
678  }
679
680  return $prefix.$body.$suffix;
681}
682
683
684function rcmail_create_forward_body($body, $bodyIsHtml)
685{
686  global $IMAP, $MESSAGE, $OUTPUT;
687
688  // add attachments
689  if (!isset($_SESSION['compose']['forward_attachments']) && is_array($MESSAGE->mime_parts))
690    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
691
692  if (!$bodyIsHtml)
693  {
694    $prefix = "\n\n\n-------- Original Message --------\n";
695    $prefix .= 'Subject: ' . $MESSAGE->subject . "\n";
696    $prefix .= 'Date: ' . $MESSAGE->headers->date . "\n";
697    $prefix .= 'From: ' . $MESSAGE->get_header('from') . "\n";
698    $prefix .= 'To: ' . $MESSAGE->get_header('to') . "\n";
699
700    if ($MESSAGE->headers->cc)
701      $prefix .= 'Cc: ' . $MESSAGE->get_header('cc') . "\n";
702    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
703      $prefix .= 'Reply-To: ' . $MESSAGE->get_header('replyto') . "\n";
704
705    $prefix .= "\n";
706  }
707  else
708  {
709    // set is_safe flag (we need this for html body washing)
710    rcmail_check_safe($MESSAGE);
711    // clean up html tags
712    $body = rcmail_wash_html($body, array('safe' => $MESSAGE->is_safe), $cid_map);
713
714    $prefix = sprintf(
715      "<br /><p>-------- Original Message --------</p>" .
716        "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tbody>" .
717        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Subject: </th><td>%s</td></tr>" .
718        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Date: </th><td>%s</td></tr>" .
719        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">From: </th><td>%s</td></tr>" .
720        "<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">To: </th><td>%s</td></tr>",
721      Q($MESSAGE->subject),
722      Q($MESSAGE->headers->date),
723      htmlspecialchars(Q($MESSAGE->get_header('from'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()),
724      htmlspecialchars(Q($MESSAGE->get_header('to'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
725
726    if ($MESSAGE->headers->cc)
727      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Cc: </th><td>%s</td></tr>",
728        htmlspecialchars(Q($MESSAGE->get_header('cc'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
729
730    if ($MESSAGE->headers->replyto && $MESSAGE->headers->replyto != $MESSAGE->headers->from)
731      $prefix .= sprintf("<tr><th align=\"right\" nowrap=\"nowrap\" valign=\"baseline\">Reply-To: </th><td>%s</td></tr>",
732        htmlspecialchars(Q($MESSAGE->get_header('replyto'), 'replace'), ENT_COMPAT, $OUTPUT->get_charset()));
733
734    $prefix .= "</tbody></table><br>";
735  }
736   
737  return $prefix.$body;
738}
739
740
741function rcmail_create_draft_body($body, $bodyIsHtml)
742{
743  global $MESSAGE, $OUTPUT;
744 
745  /**
746   * add attachments
747   * sizeof($MESSAGE->mime_parts can be 1 - e.g. attachment, but no text!
748   */
749  if (empty($_SESSION['compose']['forward_attachments'])
750      && is_array($MESSAGE->mime_parts)
751      && count($MESSAGE->mime_parts) > 0)
752  {
753    $cid_map = rcmail_write_compose_attachments($MESSAGE, $bodyIsHtml);
754
755    // replace cid with href in inline images links
756    if ($cid_map)
757      $body = str_replace(array_keys($cid_map), array_values($cid_map), $body);
758  }
759 
760  return $body;
761}
762 
763 
764function rcmail_write_compose_attachments(&$message, $bodyIsHtml)
765{
766  global $OUTPUT;
767
768  $cid_map = $messages = array();
769  foreach ((array)$message->mime_parts as $pid => $part)
770  {
771    if (($part->ctype_primary != 'message' || !$bodyIsHtml) && $part->ctype_primary != 'multipart' &&
772        ($part->disposition == 'attachment' || ($part->disposition == 'inline' && $bodyIsHtml) || $part->filename)
773        && $part->mimetype != 'application/ms-tnef'
774    ) {
775      $skip = false;
776      if ($part->mimetype == 'message/rfc822') {
777        $messages[] = $part->mime_id;
778      } else if ($messages) {
779        // skip attachments included in message/rfc822 attachment (#1486487)
780        foreach ($messages as $mimeid)
781          if (strpos($part->mime_id, $mimeid.'.') === 0) {
782            $skip = true;
783            break;
784          }
785      }
786
787      if (!$skip && ($attachment = rcmail_save_attachment($message, $pid))) {
788        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
789        if ($bodyIsHtml && ($part->content_id || $part->content_location)) {
790          $url = $OUTPUT->app->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'];
791          if ($part->content_id)
792            $cid_map['cid:'.$part->content_id] = $url;
793          else
794            $cid_map[$part->content_location] = $url;
795        }
796      }
797    }
798  }
799
800  $_SESSION['compose']['forward_attachments'] = true;
801
802  return $cid_map;
803}
804
805
806function rcmail_write_inline_attachments(&$message)
807{
808  global $OUTPUT;
809
810  $cid_map = array();
811  foreach ((array)$message->mime_parts as $pid => $part) {
812    if (($part->content_id || $part->content_location) && $part->filename) {
813      if ($attachment = rcmail_save_attachment($message, $pid)) {
814        $_SESSION['compose']['attachments'][$attachment['id']] = $attachment;
815        $url = $OUTPUT->app->comm_path.'&_action=display-attachment&_file=rcmfile'.$attachment['id'];
816        if ($part->content_id)
817          $cid_map['cid:'.$part->content_id] = $url;
818        else
819          $cid_map[$part->content_location] = $url;
820      }
821    }
822  }
823
824  return $cid_map;
825}
826
827function rcmail_save_attachment(&$message, $pid)
828{
829  $part = $message->mime_parts[$pid];
830  $mem_limit = parse_bytes(ini_get('memory_limit'));
831  $curr_mem = function_exists('memory_get_usage') ? memory_get_usage() : 16*1024*1024; // safe value: 16MB
832  $data = $path = null;
833
834  // don't load too big attachments into memory
835  if ($mem_limit > 0 && $part->size > $mem_limit - $curr_mem) {
836    $rcmail = rcmail::get_instance();
837    $temp_dir = unslashify($rcmail->config->get('temp_dir'));
838    $path = tempnam($temp_dir, 'rcmAttmnt');
839    if ($fp = fopen($path, 'w')) {
840      $message->get_part_content($pid, $fp);
841      fclose($fp);
842    } else
843      return false;
844  } else {
845    $data = $message->get_part_content($pid);
846  }
847
848  $attachment = array(
849    'name' => $part->filename ? $part->filename : 'Part_'.$pid.'.'.$part->ctype_secondary,
850    'mimetype' => $part->ctype_primary . '/' . $part->ctype_secondary,
851    'content_id' => $part->content_id,
852    'data' => $data,
853    'path' => $path,
854    'size' => $path ? filesize($path) : strlen($data),
855  );
856
857  $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
858
859  if ($attachment['status']) {
860    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
861    return $attachment;
862  } else if ($path) {
863    @unlink($path);
864  }
865 
866  return false;
867}
868
869function rcmail_save_image($path, $mimetype='')
870{
871  // handle attachments in memory
872  $data = file_get_contents($path);
873
874  $attachment = array(
875    'name' => rcmail_basename($path),
876    'mimetype' => $mimetype ? $mimetype : rc_mime_content_type($path, $name),
877    'data' => $data,
878    'size' => strlen($data),
879  );
880
881  $attachment = rcmail::get_instance()->plugins->exec_hook('attachment_save', $attachment);
882
883  if ($attachment['status']) {
884    unset($attachment['data'], $attachment['status'], $attachment['content_id'], $attachment['abort']);
885    return $attachment;
886  }
887 
888  return false;
889}
890
891function rcmail_basename($filename)
892{
893  // basename() is not unicode safe and locale dependent
894  if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
895    return preg_replace('/^.*[\\\\\\/]/', '', $filename);
896  } else {
897    return preg_replace('/^.*[\/]/', '', $filename);
898  }
899}
900
901function rcmail_compose_subject($attrib)
902{
903  global $MESSAGE, $compose_mode;
904 
905  list($form_start, $form_end) = get_form_tags($attrib);
906  unset($attrib['form']);
907 
908  $attrib['name'] = '_subject';
909  $attrib['spellcheck'] = 'true';
910  $textfield = new html_inputfield($attrib);
911
912  $subject = '';
913
914  // use subject from post
915  if (isset($_POST['_subject'])) {
916    $subject = get_input_value('_subject', RCUBE_INPUT_POST, TRUE);
917  }
918  // create a reply-subject
919  else if ($compose_mode == RCUBE_COMPOSE_REPLY) {
920    if (preg_match('/^re:/i', $MESSAGE->subject))
921      $subject = $MESSAGE->subject;
922    else
923      $subject = 'Re: '.$MESSAGE->subject;
924  }
925  // create a forward-subject
926  else if ($compose_mode == RCUBE_COMPOSE_FORWARD) {
927    if (preg_match('/^fwd:/i', $MESSAGE->subject))
928      $subject = $MESSAGE->subject;
929    else
930      $subject = 'Fwd: '.$MESSAGE->subject;
931  }
932  // creeate a draft-subject
933  else if ($compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT) {
934    $subject = $MESSAGE->subject;
935  }
936  else if (!empty($_SESSION['compose']['param']['subject'])) {
937    $subject = $_SESSION['compose']['param']['subject'];
938  }
939 
940  $out = $form_start ? "$form_start\n" : '';
941  $out .= $textfield->show($subject);
942  $out .= $form_end ? "\n$form_end" : '';
943
944  return $out;
945}
946
947
948function rcmail_compose_attachment_list($attrib)
949{
950  global $OUTPUT, $CONFIG;
951 
952  // add ID if not given
953  if (!$attrib['id'])
954    $attrib['id'] = 'rcmAttachmentList';
955 
956  $out = "\n";
957  $jslist = array();
958
959  if (is_array($_SESSION['compose']['attachments']))
960  {
961    if ($attrib['deleteicon']) {
962      $button = html::img(array(
963        'src' => $CONFIG['skin_path'] . $attrib['deleteicon'],
964        'alt' => rcube_label('delete')
965      ));
966    }
967    else
968      $button = Q(rcube_label('delete'));
969
970    foreach ($_SESSION['compose']['attachments'] as $id => $a_prop)
971    {
972      if (empty($a_prop))
973        continue;
974     
975      $out .= html::tag('li', array('id' => 'rcmfile'.$id),
976        html::a(array(
977            'href' => "#delete",
978            'title' => rcube_label('delete'),
979            'onclick' => sprintf("return %s.command('remove-attachment','rcmfile%s', this)", JS_OBJECT_NAME, $id)),
980          $button) . Q($a_prop['name']));
981       
982        $jslist['rcmfile'.$id] = array('name' => $a_prop['name'], 'complete' => true, 'mimetype' => $a_prop['mimetype']);
983    }
984  }
985
986  if ($attrib['deleteicon'])
987    $_SESSION['compose']['deleteicon'] = $CONFIG['skin_path'] . $attrib['deleteicon'];
988  if ($attrib['cancelicon'])
989    $OUTPUT->set_env('cancelicon', $CONFIG['skin_path'] . $attrib['cancelicon']);
990  if ($attrib['loadingicon'])
991    $OUTPUT->set_env('loadingicon', $CONFIG['skin_path'] . $attrib['loadingicon']);
992
993  $OUTPUT->set_env('attachments', $jslist);
994  $OUTPUT->add_gui_object('attachmentlist', $attrib['id']);
995   
996  return html::tag('ul', $attrib, $out, html::$common_attrib);
997}
998
999
1000function rcmail_compose_attachment_form($attrib)
1001{
1002  global $OUTPUT;
1003
1004  // add ID if not given
1005  if (!$attrib['id'])
1006    $attrib['id'] = 'rcmUploadbox';
1007
1008  // find max filesize value
1009  $max_filesize = parse_bytes(ini_get('upload_max_filesize'));
1010  $max_postsize = parse_bytes(ini_get('post_max_size'));
1011  if ($max_postsize && $max_postsize < $max_filesize)
1012    $max_filesize = $max_postsize;
1013  $max_filesize = show_bytes($max_filesize);
1014 
1015  $button = new html_inputfield(array('type' => 'button'));
1016 
1017  $out = html::div($attrib,
1018    $OUTPUT->form_tag(array('name' => 'uploadform', 'method' => 'post', 'enctype' => 'multipart/form-data'),
1019      html::div(null, rcmail_compose_attachment_field(array('size' => $attrib[attachmentfieldsize]))) .
1020      html::div('hint', rcube_label(array('name' => 'maxuploadsize', 'vars' => array('size' => $max_filesize)))) .
1021      html::div('buttons',
1022        $button->show(rcube_label('close'), array('class' => 'button', 'onclick' => "$('#$attrib[id]').hide()")) . ' ' .
1023        $button->show(rcube_label('upload'), array('class' => 'button mainaction', 'onclick' => JS_OBJECT_NAME . ".command('send-attachment', this.form)"))
1024      )
1025    )
1026  );
1027 
1028  $OUTPUT->add_gui_object('uploadbox', $attrib['id']);
1029  return $out;
1030}
1031
1032
1033function rcmail_compose_attachment_field($attrib)
1034{
1035  $attrib['type'] = 'file';
1036  $attrib['name'] = '_attachments[]';
1037  $field = new html_inputfield($attrib);
1038  return $field->show();
1039}
1040
1041
1042function rcmail_priority_selector($attrib)
1043{
1044  global $MESSAGE;
1045 
1046  list($form_start, $form_end) = get_form_tags($attrib);
1047  unset($attrib['form']);
1048
1049  $attrib['name'] = '_priority';
1050  $selector = new html_select($attrib);
1051
1052  $selector->add(array(rcube_label('lowest'),
1053                       rcube_label('low'),
1054                       rcube_label('normal'),
1055                       rcube_label('high'),
1056                       rcube_label('highest')),
1057                 array(5, 4, 0, 2, 1));
1058
1059  if (isset($_POST['_priority']))
1060    $sel = $_POST['_priority'];
1061  else if (intval($MESSAGE->headers->priority) != 3)
1062    $sel = intval($MESSAGE->headers->priority);
1063  else
1064    $sel = 0;
1065
1066  $out = $form_start ? "$form_start\n" : '';
1067  $out .= $selector->show($sel);
1068  $out .= $form_end ? "\n$form_end" : '';
1069
1070  return $out;
1071}
1072
1073
1074function rcmail_receipt_checkbox($attrib)
1075{
1076  global $MESSAGE, $compose_mode;
1077
1078  list($form_start, $form_end) = get_form_tags($attrib);
1079  unset($attrib['form']);
1080
1081  if (!isset($attrib['id']))
1082    $attrib['id'] = 'receipt'; 
1083
1084  $attrib['name'] = '_receipt';
1085  $attrib['value'] = '1';
1086  $checkbox = new html_checkbox($attrib);
1087
1088  $out = $form_start ? "$form_start\n" : '';
1089  $out .= $checkbox->show(in_array($compose_mode, array(RCUBE_COMPOSE_DRAFT, RCUBE_COMPOSE_EDIT))
1090        && $MESSAGE->headers->mdn_to ? 1 : 0);
1091  $out .= $form_end ? "\n$form_end" : '';
1092
1093  return $out;
1094}
1095
1096
1097function rcmail_editor_selector($attrib)
1098{
1099  global $CONFIG, $MESSAGE, $compose_mode;
1100
1101  // determine whether HTML or plain text should be checked
1102  if ($compose_mode)
1103    $useHtml = (($CONFIG['htmleditor'] || $compose_mode == RCUBE_COMPOSE_DRAFT || $compose_mode == RCUBE_COMPOSE_EDIT)
1104        && $MESSAGE->has_html_part());
1105  else
1106    $useHtml = $CONFIG['htmleditor'] ? true : false;
1107
1108  if (empty($attrib['editorid']))
1109    $attrib['editorid'] = 'rcmComposeBody';
1110
1111  if (empty($attrib['name']))
1112    $attrib['name'] = 'editorSelect';
1113
1114  $attrib['onchange'] = "return rcmail_toggle_editor(this, '".$attrib['editorid']."', '_is_html')";
1115
1116  $select = new html_select($attrib);
1117
1118  $select->add(Q(rcube_label('htmltoggle')), 'html');
1119  $select->add(Q(rcube_label('plaintoggle')), 'plain');
1120
1121  return $select->show($useHtml ? 'html' : 'plain');
1122
1123  foreach ($choices as $value => $text)
1124  {
1125    $attrib['id'] = '_' . $value;
1126    $attrib['value'] = $value;
1127    $selector .= $radio->show($chosenvalue, $attrib) . html::label($attrib['id'], Q(rcube_label($text)));
1128  }
1129
1130  return $selector;
1131}
1132
1133
1134function rcmail_store_target_selection($attrib)
1135{
1136  $attrib['name'] = '_store_target';
1137  $select = rcmail_mailbox_select(array_merge($attrib, array('noselection' => '- '.rcube_label('dontsave').' -')));
1138  return $select->show($_SESSION['compose']['param']['sent_mbox'], $attrib);
1139}
1140
1141
1142function get_form_tags($attrib)
1143{
1144  global $RCMAIL, $MESSAGE_FORM;
1145
1146  $form_start = '';
1147  if (!$MESSAGE_FORM)
1148  {
1149    $hiddenfields = new html_hiddenfield(array('name' => '_task', 'value' => $RCMAIL->task));
1150    $hiddenfields->add(array('name' => '_action', 'value' => 'send'));
1151
1152    $form_start = empty($attrib['form']) ? $RCMAIL->output->form_tag(array('name' => "form", 'method' => "post")) : '';
1153    $form_start .= $hiddenfields->show();
1154  }
1155   
1156  $form_end = ($MESSAGE_FORM && !strlen($attrib['form'])) ? '</form>' : '';
1157  $form_name = !empty($attrib['form']) ? $attrib['form'] : 'form';
1158 
1159  if (!$MESSAGE_FORM)
1160    $RCMAIL->output->add_gui_object('messageform', $form_name);
1161 
1162  $MESSAGE_FORM = $form_name;
1163
1164  return array($form_start, $form_end);
1165}
1166
1167
1168// register UI objects
1169$OUTPUT->add_handlers(array(
1170  'composeheaders' => 'rcmail_compose_headers',
1171  'composesubject' => 'rcmail_compose_subject',
1172  'composebody' => 'rcmail_compose_body',
1173  'composeattachmentlist' => 'rcmail_compose_attachment_list',
1174  'composeattachmentform' => 'rcmail_compose_attachment_form',
1175  'composeattachment' => 'rcmail_compose_attachment_field',
1176  'priorityselector' => 'rcmail_priority_selector',
1177  'editorselector' => 'rcmail_editor_selector',
1178  'receiptcheckbox' => 'rcmail_receipt_checkbox',
1179  'storetarget' => 'rcmail_store_target_selection',
1180));
1181
1182$OUTPUT->send('compose');
1183
1184
Note: See TracBrowser for help on using the repository browser.