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

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