source: subversion/trunk/roundcubemail/program/steps/mail/func.inc @ 211

Last change on this file since 211 was 211, checked in by cmcnulty, 7 years ago

Added undelete functionalist and support for delete toggle icon

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.0 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/steps/mail/func.inc                                           |
6 |                                                                       |
7 | This file is part of the RoundCube Webmail client                     |
8 | Copyright (C) 2005, RoundCube Dev. - Switzerland                      |
9 | Licensed under the GNU GPL                                            |
10 |                                                                       |
11 | PURPOSE:                                                              |
12 |   Provide webmail functionality and GUI objects                       |
13 |                                                                       |
14 +-----------------------------------------------------------------------+
15 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
16 +-----------------------------------------------------------------------+
17
18 $Id$
19
20*/
21
22require_once('lib/html2text.inc');
23require_once('lib/enriched.inc');
24
25
26$EMAIL_ADDRESS_PATTERN = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/i';
27
28// set imap properties and session vars
29if (strlen($_GET['_mbox']))
30  {
31  $IMAP->set_mailbox($_GET['_mbox']);
32  $_SESSION['mbox'] = $_GET['_mbox'];
33  }
34
35if (strlen($_GET['_page']))
36  {
37  $IMAP->set_page($_GET['_page']);
38  $_SESSION['page'] = $_GET['_page'];
39  }
40
41
42// set default sort col/order to session
43if (!isset($_SESSION['sort_col']))
44  $_SESSION['sort_col'] = $CONFIG['message_sort_col'];
45if (!isset($_SESSION['sort_order']))
46  $_SESSION['sort_order'] = $CONFIG['message_sort_order'];
47 
48
49// define url for getting message parts
50if (strlen($_GET['_uid']))
51  $GET_URL = sprintf('%s&_action=get&_mbox=%s&_uid=%d', $COMM_PATH, $IMAP->get_mailbox_name(), $_GET['_uid']);
52
53
54// set current mailbox in client environment
55$OUTPUT->add_script(sprintf("%s.set_env('mailbox', '%s');", $JS_OBJECT_NAME, $IMAP->get_mailbox_name()));
56
57
58if ($CONFIG['trash_mbox'])
59  $OUTPUT->add_script(sprintf("%s.set_env('trash_mailbox', '%s');", $JS_OBJECT_NAME, $CONFIG['trash_mbox']));
60
61
62
63// return the mailboxlist in HTML
64function rcmail_mailbox_list($attrib)
65  {
66  global $IMAP, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $COMM_PATH;
67  static $s_added_script = FALSE;
68  static $a_mailboxes;
69
70  // add some labels to client
71  rcube_add_label('purgefolderconfirm');
72 
73// $mboxlist_start = rcube_timer();
74 
75  $type = $attrib['type'] ? $attrib['type'] : 'ul';
76  $add_attrib = $type=='select' ? array('style', 'class', 'id', 'name', 'onchange') :
77                                  array('style', 'class', 'id');
78                                 
79  if ($type=='ul' && !$attrib['id'])
80    $attrib['id'] = 'rcmboxlist';
81
82  // allow the following attributes to be added to the <ul> tag
83  $attrib_str = create_attrib_string($attrib, $add_attrib);
84 
85  $out = '<' . $type . $attrib_str . ">\n";
86 
87  // add no-selection option
88  if ($type=='select' && $attrib['noselection'])
89    $out .= sprintf('<option value="0">%s</option>'."\n",
90                    rcube_label($attrib['noselection']));
91 
92  // get mailbox list
93  $mbox = $IMAP->get_mailbox_name();
94 
95  // for these mailboxes we have localized labels
96  $special_mailboxes = array('inbox', 'sent', 'drafts', 'trash', 'junk');
97
98
99  // build the folders tree
100  if (empty($a_mailboxes))
101    {
102    // get mailbox list
103    $a_folders = $IMAP->list_mailboxes();
104    $delimiter = $IMAP->get_hierarchy_delimiter();
105    $a_mailboxes = array();
106
107// rcube_print_time($mboxlist_start, 'list_mailboxes()');
108
109    foreach ($a_folders as $folder)
110      rcmail_build_folder_tree($a_mailboxes, $folder, $delimiter);
111    }
112
113// var_dump($a_mailboxes);
114
115  if ($type=='select')
116    $out .= rcmail_render_folder_tree_select($a_mailboxes, $special_mailboxes, $mbox, $attrib['maxlength']);
117   else
118    $out .= rcmail_render_folder_tree_html($a_mailboxes, $special_mailboxes, $mbox, $attrib['maxlength']);
119
120// rcube_print_time($mboxlist_start, 'render_folder_tree()');
121
122
123  if ($type=='ul')
124    $OUTPUT->add_script(sprintf("%s.gui_object('mailboxlist', '%s');", $JS_OBJECT_NAME, $attrib['id']));
125
126  return $out . "</$type>";
127  }
128
129
130
131
132// create a hierarchical array of the mailbox list
133function rcmail_build_folder_tree(&$arrFolders, $folder, $delm='/', $path='')
134  {
135  $pos = strpos($folder, $delm);
136  if ($pos !== false)
137    {
138    $subFolders = substr($folder, $pos+1);
139    $currentFolder = substr($folder, 0, $pos);
140    }
141  else
142    {
143    $subFolders = false;
144    $currentFolder = $folder;
145    }
146
147  $path .= $currentFolder;
148
149  if (!isset($arrFolders[$currentFolder]))
150    {
151    $arrFolders[$currentFolder] = array('id' => $path,
152                                        'name' => rcube_charset_convert($currentFolder, 'UTF-7'),
153                                        'folders' => array());
154    }
155
156  if (!empty($subFolders))
157    rcmail_build_folder_tree($arrFolders[$currentFolder]['folders'], $subFolders, $delm, $path.$delm);
158  }
159 
160
161// return html for a structured list <ul> for the mailbox tree
162function rcmail_render_folder_tree_html(&$arrFolders, &$special, &$mbox, $maxlength, $nestLevel=0)
163  {
164  global $JS_OBJECT_NAME, $COMM_PATH, $IMAP, $CONFIG, $OUTPUT;
165
166  $idx = 0;
167  $out = '';
168  foreach ($arrFolders as $key => $folder)
169    {
170    $zebra_class = ($nestLevel*$idx)%2 ? 'even' : 'odd';
171    $title = '';
172
173    $folder_lc = strtolower($folder['id']);
174    if (in_array($folder_lc, $special))
175      $foldername = rcube_label($folder_lc);
176    else
177      {
178      $foldername = $folder['name'];
179
180      // shorten the folder name to a given length
181      if ($maxlength && $maxlength>1)
182        {
183        $fname = abbrevate_string($foldername, $maxlength);
184        if ($fname != $foldername)
185          $title = ' title="'.rep_specialchars_output($foldername, 'html', 'all').'"';
186        $foldername = $fname;
187        }
188      }
189
190    // add unread message count display
191    if ($unread_count = $IMAP->messagecount($folder['id'], 'RECENT', ($folder['id']==$mbox)))
192      $foldername .= sprintf(' (%d)', $unread_count);
193
194    // make folder name safe for ids and class names
195    $folder_css = $class_name = preg_replace('/[^a-z0-9\-_]/', '', $folder_lc);
196
197    // set special class for Sent, Drafts, Trash and Junk
198    if ($folder['id']==$CONFIG['sent_mbox'])
199      $class_name = 'sent';
200    else if ($folder['id']==$CONFIG['drafts_mbox'])
201      $class_name = 'drafts';
202    else if ($folder['id']==$CONFIG['trash_mbox'])
203      $class_name = 'trash';
204    else if ($folder['id']==$CONFIG['junk_mbox'])
205      $class_name = 'junk';
206
207    $out .= sprintf('<li id="rcmbx%s" class="mailbox %s %s%s%s"><a href="%s&_mbox=%s"'.
208                    ' onclick="return %s.command(\'list\',\'%s\')"'.
209                    ' onmouseup="return %s.mbox_mouse_up(\'%s\')"%s>%s</a>',
210                    $folder_css,
211                    $class_name,
212                    $zebra_class,
213                    $unread_count ? ' unread' : '',
214                    $folder['id']==$mbox ? ' selected' : '',
215                    $COMM_PATH,
216                    urlencode($folder['id']),
217                    $JS_OBJECT_NAME,
218                    $folder['id'],
219                    $JS_OBJECT_NAME,
220                    $folder['id'],
221                    $title,
222                    rep_specialchars_output($foldername, 'html', 'all'));
223
224    if (!empty($folder['folders']))
225      $out .= "\n<ul>\n" . rcmail_render_folder_tree_html($folder['folders'], $special, $mbox, $maxlength, $nestLevel+1) . "</ul>\n";
226
227    $out .= "</li>\n";
228    $idx++;
229    }
230
231  return $out;
232  }
233
234
235// return html for a flat list <select> for the mailbox tree
236function rcmail_render_folder_tree_select(&$arrFolders, &$special, &$mbox, $maxlength, $nestLevel=0)
237  {
238  global $IMAP, $OUTPUT;
239
240  $idx = 0;
241  $out = '';
242  foreach ($arrFolders as $key=>$folder)
243    {
244    $folder_lc = strtolower($folder['id']);
245    if (in_array($folder_lc, $special))
246      $foldername = rcube_label($folder_lc);
247    else
248      {
249      $foldername = $folder['name'];
250     
251      // shorten the folder name to a given length
252      if ($maxlength && $maxlength>1)
253        $foldername = abbrevate_string($foldername, $maxlength);
254      }
255
256    $out .= sprintf('<option value="%s">%s%s</option>'."\n",
257                    $folder['id'],
258                    str_repeat('&nbsp;', $nestLevel*4),
259                    rep_specialchars_output($foldername, 'html', 'all'));
260
261    if (!empty($folder['folders']))
262      $out .= rcmail_render_folder_tree_select($folder['folders'], $special, $mbox, $maxlength, $nestLevel+1);
263
264    $idx++;
265    }
266
267  return $out;
268  }
269
270
271// return the message list as HTML table
272function rcmail_message_list($attrib)
273  {
274  global $IMAP, $CONFIG, $COMM_PATH, $OUTPUT, $JS_OBJECT_NAME;
275
276  $skin_path = $CONFIG['skin_path'];
277  $image_tag = '<img src="%s%s" alt="%s" border="0" />';
278
279  // check to see if we have some settings for sorting
280  $sort_col   = $_SESSION['sort_col'];
281  $sort_order = $_SESSION['sort_order'];
282
283  // get message headers
284  $a_headers = $IMAP->list_headers('', '', $sort_col, $sort_order);
285
286  // add id to message list table if not specified
287  if (!strlen($attrib['id']))
288    $attrib['id'] = 'rcubemessagelist';
289
290  // allow the following attributes to be added to the <table> tag
291  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
292
293  $out = '<table' . $attrib_str . ">\n";
294
295
296  // define list of cols to be displayed
297  $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
298  $a_sort_cols = array('subject', 'date', 'from', 'to');
299 
300  // show 'to' instead of from in sent messages
301  if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols))
302      && !array_search('to', $a_show_cols))
303    $a_show_cols[$f] = 'to';
304 
305  // add col definition
306  $out .= '<colgroup>';
307  $out .= '<col class="icon" />';
308
309  foreach ($a_show_cols as $col)
310    $out .= sprintf('<col class="%s" />', $col);
311
312  $out .= '<col class="icon" />';
313  $out .= "</colgroup>\n";
314
315  // add table title
316  $out .= "<thead><tr>\n<td class=\"icon\">&nbsp;</td>\n";
317
318  $javascript = '';
319  foreach ($a_show_cols as $col)
320    {
321    // get column name
322    $col_name = rep_specialchars_output(rcube_label($col));
323
324    // make sort links
325    $sort = '';
326    if ($IMAP->get_capability('sort') && in_array($col, $a_sort_cols))
327      {
328      // have buttons configured
329      if (!empty($attrib['sortdescbutton']) || !empty($attrib['sortascbutton']))
330        {
331        $sort = '&nbsp;&nbsp;';
332
333        // asc link
334        if (!empty($attrib['sortascbutton']))
335          {
336          $sort .= rcube_button(array('command' => 'sort',
337                                      'prop' => $col.'_ASC',
338                                      'image' => $attrib['sortascbutton'],
339                                      'align' => 'absmiddle',
340                                      'title' => 'sortasc'));
341          }       
342       
343        // desc link
344        if (!empty($attrib['sortdescbutton']))
345          {
346          $sort .= rcube_button(array('command' => 'sort',
347                                      'prop' => $col.'_DESC',
348                                      'image' => $attrib['sortdescbutton'],
349                                      'align' => 'absmiddle',
350                                      'title' => 'sortdesc'));       
351          }
352        }
353      // just add a link tag to the header
354      else
355        {
356        $col_name = sprintf('<a href="./#sort" onclick="return %s.command(\'sort\',\'%s\',this)" title="%s">%s</a>',
357                            $JS_OBJECT_NAME,
358                            $col,
359                            rcube_label('sortby'),
360                            $col_name);
361        }
362      }
363     
364    $sort_class = $col==$sort_col ? " sorted$sort_order" : '';
365
366    // put it all together
367    $out .= '<td class="'.$col.$sort_class.'" id="rcmHead'.$col.'">' . "$col_name$sort</td>\n";   
368    }
369
370  $out .= '<td class="icon">'.($attrib['attachmenticon'] ? sprintf($image_tag, $skin_path, $attrib['attachmenticon'], '') : '')."</td>\n";
371  $out .= "</tr></thead>\n<tbody>\n";
372
373  // no messages in this mailbox
374  if (!sizeof($a_headers))
375    {
376    $out .= rep_specialchars_output(
377                                sprintf('<tr><td colspan="%d">%s</td></tr>',
378                   sizeof($a_show_cols)+2,
379                   rcube_label('nomessagesfound')));
380    }
381
382
383  $a_js_message_arr = array();
384
385  // create row for each message
386  foreach ($a_headers as $i => $header)  //while (list($i, $header) = each($a_headers))
387    {
388    $message_icon = $attach_icon = '';
389    $js_row_arr = array();
390    $zebra_class = $i%2 ? 'even' : 'odd';
391
392    // set messag attributes to javascript array
393    if ($header->deleted)
394      $js_row_arr['deleted'] = true;
395    if (!$header->seen)
396      $js_row_arr['unread'] = true;
397    if ($header->answered)
398      $js_row_arr['replied'] = true;
399    // set message icon 
400    if ($attrib['deletedicon'] && $header->deleted)
401      $message_icon = $attrib['deletedicon'];
402    else if ($attrib['unreadicon'] && !$header->seen)
403      $message_icon = $attrib['unreadicon'];
404    else if ($attrib['repliedicon'] && $header->answered)
405      $message_icon = $attrib['repliedicon'];
406    else if ($attrib['messageicon'])
407      $message_icon = $attrib['messageicon'];
408   
409        // set attachment icon
410    if ($attrib['attachmenticon'] && preg_match("/multipart\/m/i", $header->ctype))
411      $attach_icon = $attrib['attachmenticon'];
412       
413    $out .= sprintf('<tr id="rcmrow%d" class="message%s%s %s">'."\n",
414                    $header->uid,
415                    $header->seen ? '' : ' unread',
416                    $header->deleted ? ' deleted' : '',
417                    $zebra_class);   
418   
419    $out .= sprintf("<td class=\"icon\">%s</td>\n", $message_icon ? sprintf($image_tag, $skin_path, $message_icon, '') : '');
420       
421    // format each col
422    foreach ($a_show_cols as $col)
423      {
424      if ($col=='from' || $col=='to')
425        $cont = rep_specialchars_output(rcmail_address_string($header->$col, 3, $attrib['addicon']));
426      else if ($col=='subject')
427        $cont = rep_specialchars_output($IMAP->decode_header($header->$col), 'html', 'all');
428      else if ($col=='size')
429        $cont = show_bytes($header->$col);
430      else if ($col=='date')
431        $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
432      else
433        $cont = rep_specialchars_output($header->$col, 'html', 'all');
434       
435          $out .= '<td class="'.$col.'">' . $cont . "</td>\n";
436      }
437
438    $out .= sprintf("<td class=\"icon\">%s</td>\n", $attach_icon ? sprintf($image_tag, $skin_path, $attach_icon, '') : '');
439    $out .= "</tr>\n";
440   
441    if (sizeof($js_row_arr))
442      $a_js_message_arr[$header->uid] = $js_row_arr;
443    }
444 
445  // complete message table
446  $out .= "</tbody></table>\n";
447 
448 
449  $message_count = $IMAP->messagecount();
450 
451  // set client env
452  $javascript .= sprintf("%s.gui_object('mailcontframe', '%s');\n", $JS_OBJECT_NAME, 'mailcontframe');
453  $javascript .= sprintf("%s.gui_object('messagelist', '%s');\n", $JS_OBJECT_NAME, $attrib['id']);
454  $javascript .= sprintf("%s.set_env('messagecount', %d);\n", $JS_OBJECT_NAME, $message_count);
455  $javascript .= sprintf("%s.set_env('current_page', %d);\n", $JS_OBJECT_NAME, $IMAP->list_page);
456  $javascript .= sprintf("%s.set_env('pagecount', %d);\n", $JS_OBJECT_NAME, ceil($message_count/$IMAP->page_size));
457  $javascript .= sprintf("%s.set_env('sort_col', '%s');\n", $JS_OBJECT_NAME, $sort_col);
458  $javascript .= sprintf("%s.set_env('sort_order', '%s');\n", $JS_OBJECT_NAME, $sort_order);
459 
460  if ($attrib['messageicon'])
461    $javascript .= sprintf("%s.set_env('messageicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['messageicon']);
462  if ($attrib['deletedicon'])
463    $javascript .= sprintf("%s.set_env('deletedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['deletedicon']);
464  if ($attrib['unreadicon'])
465    $javascript .= sprintf("%s.set_env('unreadicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['unreadicon']);
466  if ($attrib['repliedicon'])
467    $javascript .= sprintf("%s.set_env('repliedicon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['repliedicon']);
468  if ($attrib['attachmenticon'])
469    $javascript .= sprintf("%s.set_env('attachmenticon', '%s%s');\n", $JS_OBJECT_NAME, $skin_path, $attrib['attachmenticon']);
470   
471  $javascript .= sprintf("%s.set_env('messages', %s);", $JS_OBJECT_NAME, array2js($a_js_message_arr));
472 
473  $OUTPUT->add_script($javascript); 
474 
475  return $out;
476  }
477
478
479
480
481// return javascript commands to add rows to the message list
482function rcmail_js_message_list($a_headers, $insert_top=FALSE)
483  {
484  global $CONFIG, $IMAP;
485
486  $commands = '';
487  $a_show_cols = is_array($CONFIG['list_cols']) ? $CONFIG['list_cols'] : array('subject');
488
489  // show 'to' instead of from in sent messages
490  if (strtolower($IMAP->get_mailbox_name())=='sent' && ($f = array_search('from', $a_show_cols))
491      && !array_search('to', $a_show_cols))
492    $a_show_cols[$f] = 'to';
493
494  // loop through message headers
495  for ($n=0; $a_headers[$n]; $n++)
496    {
497    $header = $a_headers[$n];
498    $a_msg_cols = array();
499    $a_msg_flags = array();
500     
501    // format each col; similar as in rcmail_message_list()
502    foreach ($a_show_cols as $col)
503      {
504      if ($col=='from' || $col=='to')
505        $cont = rep_specialchars_output(rcmail_address_string($header->$col, 3));
506      else if ($col=='subject')
507        $cont = rep_specialchars_output($IMAP->decode_header($header->$col), 'html', 'all');
508      else if ($col=='size')
509        $cont = show_bytes($header->$col);
510      else if ($col=='date')
511        $cont = format_date($header->date); //date('m.d.Y G:i:s', strtotime($header->date));
512      else
513        $cont = rep_specialchars_output($header->$col, 'html', 'all');
514         
515      $a_msg_cols[$col] = $cont;
516      }
517
518    $a_msg_flags['deleted'] = $header->deleted ? 1 : 0;
519    $a_msg_flags['unread'] = $header->seen ? 0 : 1;
520    $a_msg_flags['replied'] = $header->answered ? 1 : 0;
521    $commands .= sprintf("this.add_message_row(%s, %s, %s, %b, %b);\n",
522                         $header->uid,
523                         array2js($a_msg_cols),
524                         array2js($a_msg_flags),
525                         preg_match("/multipart\/m/i", $header->ctype),
526                         $insert_top);
527    }
528
529  return $commands;
530  }
531
532
533// return code for search function
534function rcmail_search_form($attrib)
535  {
536  global $OUTPUT, $JS_OBJECT_NAME;
537
538  // add some labels to client
539  rcube_add_label('searching');
540
541  $attrib['name'] = '_q';
542 
543  if (empty($attrib['id']))
544    $attrib['id'] = 'rcmqsearchbox';
545 
546  $input_q = new textfield($attrib);
547  $out = $input_q->show();
548
549  $OUTPUT->add_script(sprintf("%s.gui_object('qsearchbox', '%s');",
550                              $JS_OBJECT_NAME,
551                              $attrib['id']));
552
553  // add form tag around text field
554  if (empty($attrib['form']))
555    $out = sprintf('<form name="rcmqsearchform" action="./" '.
556                   'onsubmit="%s.command(\'search\');return false" style="display:inline;">%s</form>',
557                   $JS_OBJECT_NAME,
558                   $out);
559
560  return $out;
561  }
562
563
564function rcmail_messagecount_display($attrib)
565  {
566  global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
567 
568  if (!$attrib['id'])
569    $attrib['id'] = 'rcmcountdisplay';
570
571  $OUTPUT->add_script(sprintf("%s.gui_object('countdisplay', '%s');",
572                              $JS_OBJECT_NAME,
573                              $attrib['id']));
574
575  // allow the following attributes to be added to the <span> tag
576  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
577
578 
579  $out = '<span' . $attrib_str . '>';
580  $out .= rcmail_get_messagecount_text();
581  $out .= '</span>';
582  return $out;
583  }
584
585
586function rcmail_quota_display($attrib)
587  {
588  global $IMAP, $OUTPUT, $JS_OBJECT_NAME;
589
590  if (!$attrib['id'])
591    $attrib['id'] = 'rcmquotadisplay';
592
593  $OUTPUT->add_script(sprintf("%s.gui_object('quotadisplay', '%s');", $JS_OBJECT_NAME, $attrib['id']));
594
595  // allow the following attributes to be added to the <span> tag
596  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
597 
598  if (!$IMAP->get_capability('QUOTA'))
599    $quota_text = rcube_label('unknown');
600  else if (!($quota_text = $IMAP->get_quota()))
601    $quota_text = rcube_label('unlimited');
602
603  $out = '<span' . $attrib_str . '>';
604  $out .= $quota_text;
605  $out .= '</span>';
606  return $out;
607  }
608
609
610function rcmail_get_messagecount_text($count=NULL, $page=NULL)
611  {
612  global $IMAP, $MESSAGE;
613 
614  if (isset($MESSAGE['index']))
615    {
616    return rcube_label(array('name' => 'messagenrof',
617                             'vars' => array('nr'  => $MESSAGE['index']+1,
618                                             'count' => $count!==NULL ? $count : $IMAP->messagecount())));
619    }
620
621  if ($page===NULL)
622    $page = $IMAP->list_page;
623   
624  $start_msg = ($page-1) * $IMAP->page_size + 1;
625  $max = $count!==NULL ? $count : $IMAP->messagecount();
626
627  if ($max==0)
628    $out = rcube_label('mailboxempty');
629  else
630    $out = rcube_label(array('name' => 'messagesfromto',
631                              'vars' => array('from'  => $start_msg,
632                                              'to'    => min($max, $start_msg + $IMAP->page_size - 1),
633                                              'count' => $max)));
634
635  return rep_specialchars_output($out);
636  }
637
638
639function rcmail_print_body($part, $safe=FALSE, $plain=FALSE) // $body, $ctype_primary='text', $ctype_secondary='plain', $encoding='7bit', $safe=FALSE, $plain=FALSE)
640  {
641  global $IMAP, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
642
643  // extract part properties: body, ctype_primary, ctype_secondary, encoding, parameters
644  extract($part);
645 
646  $block = $plain ? '%s' : '%s'; //'<div style="display:block;">%s</div>';
647  $body = $IMAP->mime_decode($body, $encoding); 
648  $body = $IMAP->charset_decode($body, $parameters);
649
650  // text/html
651  if ($ctype_secondary=='html')
652    {
653    if (!$safe)  // remove remote images and scripts
654      {
655      $remote_patterns = array('/(src|background)=(["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)(\2|\s|>)/Ui',
656                           //  '/(src|background)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Ui',
657                               '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
658                               '/(<link.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i',
659                               '/url\s*\(["\']?([hftps]{3,5}:\/{2}[^"\'\s]+)["\']?\)/i',
660                               '/url\s*\(["\']?([\.\/]+[^"\'\s]+)["\']?\)/i',
661                               '/<script.+<\/script>/Umis');
662
663      $remote_replaces = array('',  // '\\1=\\2#\\4',
664                            // '\\1=\\2#\\4',
665                               '',
666                               '',  // '\\1#\\3',
667                               'none',
668                               'none',
669                               '');
670     
671      // set flag if message containes remote obejcts that where blocked
672      foreach ($remote_patterns as $pattern)
673        {
674        if (preg_match($pattern, $body))
675          {
676          $REMOTE_OBJECTS = TRUE;
677          break;
678          }
679        }
680
681      $body = preg_replace($remote_patterns, $remote_replaces, $body);
682      }
683
684    return sprintf($block, rep_specialchars_output($body, 'html', '', FALSE));
685    }
686
687  // text/enriched
688  if ($ctype_secondary=='enriched')
689    {
690    $body = enriched_to_html($body);
691    return sprintf($block, rep_specialchars_output($body, 'html'));
692    }
693  else
694    {
695    // make links and email-addresses clickable
696    $convert_patterns = $convert_replaces = $replace_strings = array();
697   
698    $url_chars = 'a-z0-9_\-\+\*\$\/&%=@#:';
699    $url_chars_within = '\?\.~,!';
700
701    $convert_patterns[] = "/([\w]+):\/\/([a-z0-9\-\.]+[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
702    $convert_replaces[] = "rcmail_str_replacement('<a href=\"\\1://\\2\" target=\"_blank\">\\1://\\2</a>', \$replace_strings)";
703
704    $convert_patterns[] = "/([^\/:]|\s)(www\.)([a-z0-9\-]{2,}[a-z]{2,4}([$url_chars$url_chars_within]*[$url_chars])?)/ie";
705    $convert_replaces[] = "rcmail_str_replacement('\\1<a href=\"http://\\2\\3\" target=\"_blank\">\\2\\3</a>', \$replace_strings)";
706   
707    $convert_patterns[] = '/([a-z0-9][a-z0-9\-\.\+\_]*@[a-z0-9]([a-z0-9\-][.]?)*[a-z0-9]\\.[a-z]{2,5})/ie';
708    $convert_replaces[] = "rcmail_str_replacement('<a href=\"mailto:\\1\" onclick=\"return $JS_OBJECT_NAME.command(\'compose\',\'\\1\',this)\">\\1</a>', \$replace_strings)";
709
710    $body = wordwrap(trim($body), 80);
711    $body = preg_replace($convert_patterns, $convert_replaces, $body);
712
713    // split body into single lines
714    $a_lines = preg_split('/\r?\n/', $body);
715
716    // colorize quoted parts
717    for($n=0; $n<sizeof($a_lines); $n++)
718      {
719      $line = $a_lines[$n];
720
721      if ($line{2}=='>')
722        $color = 'red';
723      else if ($line{1}=='>')
724        $color = 'green';
725      else if ($line{0}=='>')
726        $color = 'blue';
727      else
728        $color = FALSE;
729
730      $line = rep_specialchars_output($line, 'html', 'replace', FALSE);
731       
732      if ($color)
733        $a_lines[$n] = sprintf('<font color="%s">%s</font>', $color, $line);
734      else
735        $a_lines[$n] = $line;
736      }
737
738    // insert the links for urls and mailtos
739    $body = preg_replace("/##string_replacement\{([0-9]+)\}##/e", "\$replace_strings[\\1]", join("\n", $a_lines));
740   
741    return sprintf($block, "<pre>\n".$body."\n</pre>");
742    }
743  }
744
745
746
747// add a string to the replacement array and return a replacement string
748function rcmail_str_replacement($str, &$rep)
749  {
750  static $count = 0;
751  $rep[$count] = stripslashes($str);
752  return "##string_replacement{".($count++)."}##";
753  }
754
755
756function rcmail_parse_message($structure, $arg=array(), $recursive=FALSE)
757  {
758  global $IMAP;
759  static $sa_inline_objects = array();
760
761  // arguments are: (bool)$prefer_html, (string)$get_url
762  extract($arg);
763
764  $a_attachments = array();
765  $a_return_parts = array();
766  $out = '';
767
768  $message_ctype_primary = strtolower($structure->ctype_primary);
769  $message_ctype_secondary = strtolower($structure->ctype_secondary);
770
771  // show message headers
772  if ($recursive && is_array($structure->headers) && isset($structure->headers['subject']))
773    $a_return_parts[] = array('type' => 'headers',
774                              'headers' => $structure->headers);
775
776  // print body if message doesn't have multiple parts
777  if ($message_ctype_primary=='text')
778    {
779    $a_return_parts[] = array('type' => 'content',
780                              'body' => $structure->body,
781                              'ctype_primary' => $message_ctype_primary,
782                              'ctype_secondary' => $message_ctype_secondary,
783                              'parameters' => $structure->ctype_parameters,
784                              'encoding' => $structure->headers['content-transfer-encoding']);
785    }
786
787  // message contains alternative parts
788  else if ($message_ctype_primary=='multipart' && $message_ctype_secondary=='alternative' && is_array($structure->parts))
789    {
790    // get html/plaintext parts
791    $plain_part = $html_part = $print_part = $related_part = NULL;
792   
793    foreach ($structure->parts as $p => $sub_part)
794      {
795      $sub_ctype_primary = strtolower($sub_part->ctype_primary);
796      $sub_ctype_secondary = strtolower($sub_part->ctype_secondary);
797
798      // check if sub part is
799      if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='plain')
800        $plain_part = $p;
801      else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='html')
802        $html_part = $p;
803      else if ($sub_ctype_primary=='text' && $sub_ctype_secondary=='enriched')
804        $enriched_part = $p;
805      else if ($sub_ctype_primary=='multipart' && $sub_ctype_secondary=='related')
806        $related_part = $p;
807      }
808
809    // parse related part (alternative part could be in here)
810    if ($related_part!==NULL && $prefer_html)
811      {
812      list($parts, $attachmnts) = rcmail_parse_message($structure->parts[$related_part], $arg, TRUE);
813      $a_return_parts = array_merge($a_return_parts, $parts);
814      $a_attachments = array_merge($a_attachments, $attachmnts);
815      }
816
817    // print html/plain part
818    else if ($html_part!==NULL && $prefer_html)
819      $print_part = $structure->parts[$html_part];
820    else if ($enriched_part!==NULL)
821      $print_part = $structure->parts[$enriched_part];
822    else if ($plain_part!==NULL)
823      $print_part = $structure->parts[$plain_part];
824
825    // show message body
826    if (is_object($print_part))
827      $a_return_parts[] = array('type' => 'content',
828                                'body' => $print_part->body,
829                                'ctype_primary' => strtolower($print_part->ctype_primary),
830                                'ctype_secondary' => strtolower($print_part->ctype_secondary),
831                                'parameters' => $print_part->ctype_parameters,
832                                'encoding' => $print_part->headers['content-transfer-encoding']);
833    // show plaintext warning
834    else if ($html_part!==NULL)
835      $a_return_parts[] = array('type' => 'content',
836                                'body' => rcube_label('htmlmessage'),
837                                'ctype_primary' => 'text',
838                                'ctype_secondary' => 'plain');
839                               
840    // add html part as attachment
841    if ($html_part!==NULL && $structure->parts[$html_part]!==$print_part)
842      {
843      $html_part = $structure->parts[$html_part];
844      $a_attachments[] = array('filename' => rcube_label('htmlmessage'),
845                               'encoding' => $html_part->headers['content-transfer-encoding'],
846                               'mimetype' => 'text/html',
847                               'part_id'  => $html_part->mime_id,
848                               'size'     => strlen($IMAP->mime_decode($html_part->body, $html_part->headers['content-transfer-encoding'])));
849      }
850    }
851
852  // message contains multiple parts
853  else if ($message_ctype_primary=='multipart' && is_array($structure->parts))
854    {
855    foreach ($structure->parts as $mail_part)
856      {
857      $primary_type = strtolower($mail_part->ctype_primary);
858      $secondary_type = strtolower($mail_part->ctype_secondary);
859
860      // multipart/alternative
861      if ($primary_type=='multipart') // && ($secondary_type=='alternative' || $secondary_type=='mixed' || $secondary_type=='related'))
862        {
863        list($parts, $attachmnts) = rcmail_parse_message($mail_part, $arg, TRUE);
864
865        $a_return_parts = array_merge($a_return_parts, $parts);
866        $a_attachments = array_merge($a_attachments, $attachmnts);
867        }
868
869      // part text/[plain|html] OR message/delivery-status
870      else if (($primary_type=='text' && ($secondary_type=='plain' || $secondary_type=='html') && $mail_part->disposition!='attachment') ||
871               ($primary_type=='message' && $secondary_type=='delivery-status'))
872        {
873        $a_return_parts[] = array('type' => 'content',
874                                  'body' => $mail_part->body,
875                                  'ctype_primary' => $primary_type,
876                                  'ctype_secondary' => $secondary_type,
877                                  'parameters' => $mail_part->ctype_parameters,
878                                  'encoding' => $mail_part->headers['content-transfer-encoding']);
879        }
880
881      // part message/*
882      else if ($primary_type=='message')
883        {
884        /* don't parse headers here; they're parsed within the recursive call to rcmail_parse_message()
885        if ($mail_part->parts[0]->headers)
886          $a_return_parts[] = array('type' => 'headers',
887                                    'headers' => $mail_part->parts[0]->headers);
888        */
889                                     
890        list($parts, $attachmnts) = rcmail_parse_message($mail_part->parts[0], $arg, TRUE);
891
892        $a_return_parts = array_merge($a_return_parts, $parts);
893        $a_attachments = array_merge($a_attachments, $attachmnts);
894        }
895
896      // part is file/attachment
897      else if ($mail_part->disposition=='attachment' || $mail_part->disposition=='inline' || $mail_part->headers['content-id'] ||
898               (empty($mail_part->disposition) && ($mail_part->d_parameters['filename'] || $mail_part->ctype_parameters['name'])))
899        {
900        if ($message_ctype_secondary=='related' && $mail_part->headers['content-id'])
901          $sa_inline_objects[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
902                                       'mimetype' => strtolower("$primary_type/$secondary_type"),
903                                       'part_id'  => $mail_part->mime_id,
904                                       'content_id' => preg_replace(array('/^</', '/>$/'), '', $mail_part->headers['content-id']));
905
906        else if ($mail_part->d_parameters['filename'])
907          $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->d_parameters['filename']),
908                                   'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
909                                   'mimetype' => strtolower("$primary_type/$secondary_type"),
910                                   'part_id'  => $mail_part->mime_id,
911                                   'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
912                                   'content'  => $mail_part->body */);
913                                   
914        else if ($mail_part->ctype_parameters['name'])
915          $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->ctype_parameters['name']),
916                                   'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
917                                   'mimetype' => strtolower("$primary_type/$secondary_type"),
918                                   'part_id'  => $mail_part->mime_id,
919                                   'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
920                                   'content'  => $mail_part->body */);
921                                   
922        else if ($mail_part->headers['content-description'])
923          $a_attachments[] = array('filename' => rcube_imap::decode_mime_string($mail_part->headers['content-description']),
924                                   'encoding' => strtolower($mail_part->headers['content-transfer-encoding']),
925                                   'mimetype' => strtolower("$primary_type/$secondary_type"),
926                                   'part_id'  => $mail_part->mime_id,
927                                   'size'     => strlen($IMAP->mime_decode($mail_part->body, $mail_part->headers['content-transfer-encoding'])) /*,
928                                   'content'  => $mail_part->body */);
929        }
930      }
931
932
933    // if this was a related part try to resolve references
934    if ($message_ctype_secondary=='related' && sizeof($sa_inline_objects))
935      {
936      $a_replace_patters = array();
937      $a_replace_strings = array();
938       
939      foreach ($sa_inline_objects as $inline_object)
940        {
941        $a_replace_patters[] = 'cid:'.$inline_object['content_id'];
942        $a_replace_strings[] = sprintf($get_url, $inline_object['part_id']);
943        }
944     
945      foreach ($a_return_parts as $i => $return_part)
946        {
947        if ($return_part['type']!='content')
948          continue;
949
950        // decode body and replace cid:...
951        $a_return_parts[$i]['body'] = str_replace($a_replace_patters, $a_replace_strings, $IMAP->mime_decode($return_part['body'], $return_part['encoding']));
952        $a_return_parts[$i]['encoding'] = '7bit';
953        }
954      }
955    }
956   
957
958  // join all parts together
959  //$out .= join($part_delimiter, $a_return_parts);
960
961  return array($a_return_parts, $a_attachments);
962  }
963
964
965
966
967// return table with message headers
968function rcmail_message_headers($attrib, $headers=NULL)
969  {
970  global $IMAP, $OUTPUT, $MESSAGE;
971  static $sa_attrib;
972 
973  // keep header table attrib
974  if (is_array($attrib) && !$sa_attrib)
975    $sa_attrib = $attrib;
976  else if (!is_array($attrib) && is_array($sa_attrib))
977    $attrib = $sa_attrib;
978 
979 
980  if (!isset($MESSAGE))
981    return FALSE;
982
983  // get associative array of headers object
984  if (!$headers)
985    $headers = is_object($MESSAGE['headers']) ? get_object_vars($MESSAGE['headers']) : $MESSAGE['headers'];
986   
987  $header_count = 0;
988 
989  // allow the following attributes to be added to the <table> tag
990  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id', 'cellpadding', 'cellspacing', 'border', 'summary'));
991  $out = '<table' . $attrib_str . ">\n";
992
993  // show these headers
994  $standard_headers = array('subject', 'from', 'organization', 'to', 'cc', 'bcc', 'reply-to', 'date');
995 
996  foreach ($standard_headers as $hkey)
997    {
998    if (!$headers[$hkey])
999      continue;
1000
1001    if ($hkey=='date' && !empty($headers[$hkey]))
1002      $header_value = format_date(strtotime($headers[$hkey]));
1003    else if (in_array($hkey, array('from', 'to', 'cc', 'bcc', 'reply-to')))
1004      $header_value = rep_specialchars_output(rcmail_address_string($IMAP->decode_header($headers[$hkey]), NULL, $attrib['addicon']));
1005    else
1006      $header_value = rep_specialchars_output($IMAP->decode_header($headers[$hkey]), '', 'all');
1007
1008    $out .= "\n<tr>\n";
1009    $out .= '<td class="header-title">'.rep_specialchars_output(rcube_label($hkey)).":&nbsp;</td>\n";
1010    $out .= '<td class="'.$hkey.'" width="90%">'.$header_value."</td>\n</tr>";
1011    $header_count++;
1012    }
1013
1014  $out .= "\n</table>\n\n";
1015
1016  return $header_count ? $out : ''; 
1017  }
1018
1019
1020
1021function rcmail_message_body($attrib)
1022  {
1023  global $CONFIG, $OUTPUT, $MESSAGE, $GET_URL, $REMOTE_OBJECTS, $JS_OBJECT_NAME;
1024 
1025  if (!is_array($MESSAGE['parts']) && !$MESSAGE['body'])
1026    return '';
1027   
1028  if (!$attrib['id'])
1029    $attrib['id'] = 'rcmailMsgBody';
1030
1031  $safe_mode = (bool)$_GET['_safe'];
1032  $attrib_str = create_attrib_string($attrib, array('style', 'class', 'id'));
1033  $out = '<div '. $attrib_str . ">\n";
1034 
1035  $header_attrib = array();
1036  foreach ($attrib as $attr => $value)
1037    if (preg_match('/^headertable([a-z]+)$/i', $attr, $regs))
1038      $header_attrib[$regs[1]] = $value;
1039
1040
1041  // this is an ecrypted message
1042  // -> create a plaintext body with the according message
1043  if (!sizeof($MESSAGE['parts']) && $MESSAGE['headers']->ctype=='multipart/encrypted')
1044    {
1045    $MESSAGE['parts'][0] = array('type' => 'content',
1046                                 'ctype_primary' => 'text',
1047                                 'ctype_secondary' => 'plain',
1048                                 'body' => rcube_label('encryptedmessage'));
1049    }
1050 
1051  if ($MESSAGE['parts'])
1052    {
1053    foreach ($MESSAGE['parts'] as $i => $part)
1054      {
1055      if ($part['type']=='headers')
1056        $out .= rcmail_message_headers(sizeof($header_attrib) ? $header_attrib : NULL, $part['headers']);
1057      else if ($part['type']=='content')
1058        {
1059        if (empty($part['parameters']) || empty($part['parameters']['charset']))
1060          $part['parameters']['charset'] = $MESSAGE['headers']->charset;
1061       
1062        // $body = rcmail_print_body($part['body'], $part['ctype_primary'], $part['ctype_secondary'], $part['encoding'], $safe_mode);
1063        $body = rcmail_print_body($part, $safe_mode);
1064        $out .= '<div class="message-part">';
1065       
1066        if ($part['ctype_secondary']!='plain')
1067          $out .= rcmail_mod_html_body($body, $attrib['id']);
1068        else
1069          $out .= $body;
1070
1071        $out .= "</div>\n";
1072        }
1073      }
1074    }
1075  else
1076    $out .= $MESSAGE['body'];
1077
1078
1079  $ctype_primary = strtolower($MESSAGE['structure']->ctype_primary);
1080  $ctype_secondary = strtolower($MESSAGE['structure']->ctype_secondary);
1081 
1082  // list images after mail body
1083  if (get_boolean($attrib['showimages']) && $ctype_primary=='multipart' && $ctype_secondary=='mixed' &&
1084      sizeof($MESSAGE['attachments']) && !strstr($message_body, '<html') && strlen($GET_URL))
1085    {
1086    foreach ($MESSAGE['attachments'] as $attach_prop)
1087      {
1088      if (strpos($attach_prop['mimetype'], 'image/')===0)
1089        $out .= sprintf("\n<hr />\n<p align=\"center\"><img src=\"%s&_part=%s\" alt=\"%s\" title=\"%s\" /></p>\n",
1090                        $GET_URL, $attach_prop['part_id'],
1091                        $attach_prop['filename'],
1092                        $attach_prop['filename']);
1093      }
1094    }
1095 
1096  // tell client that there are blocked remote objects
1097  if ($REMOTE_OBJECTS && !$safe_mode)
1098    $OUTPUT->add_script(sprintf("%s.set_env('blockedobjects', true);", $JS_OBJECT_NAME));
1099
1100  $out .= "\n</div>";
1101  return $out;
1102  }
1103
1104
1105
1106// modify a HTML message that it can be displayed inside a HTML page
1107function rcmail_mod_html_body($body, $container_id)
1108  {
1109  // remove any null-byte characters before parsing
1110  $body = preg_replace('/\x00/', '', $body);
1111 
1112  $last_style_pos = 0;
1113  $body_lc = strtolower($body);
1114 
1115  // find STYLE tags
1116  while (($pos = strpos($body_lc, '<style', $last_style_pos)) && ($pos2 = strpos($body_lc, '</style>', $pos)))
1117    {
1118    $pos2 += 8;
1119    $body_pre = substr($body, 0, $pos);
1120    $styles = substr($body, $pos, $pos2-$pos);
1121    $body_post = substr($body, $pos2, strlen($body)-$pos2);
1122   
1123    // replace all css definitions with #container [def]
1124    $styles = rcmail_mod_css_styles($styles, $container_id);
1125   
1126    $body = $body_pre . $styles . $body_post;
1127    $last_style_pos = $pos2;
1128    }
1129
1130
1131  // remove SCRIPT tags
1132  foreach (array('script', 'applet', 'object', 'embed', 'iframe') as $tag)
1133    {
1134    while (($pos = strpos($body_lc, '<'.$tag)) && ($pos2 = strpos($body_lc, '</'.$tag.'>', $pos)))
1135      {
1136      $pos2 += 8;
1137      $body = substr($body, 0, $pos) . substr($body, $pos2, strlen($body)-$pos2);
1138      $body_lc = strtolower($body);
1139      }
1140    }
1141
1142  // replace event handlers on any object
1143  $body = preg_replace('/\s(on[a-z]+)=/im', ' __removed=', $body); 
1144
1145  // resolve <base href>
1146  $base_reg = '/(<base.*href=["\']?)([hftps]{3,5}:\/{2}[^"\'\s]+)([^<]*>)/i';
1147  if (preg_match($base_reg, $body, $regs))
1148    {
1149    $base_url = $regs[2];
1150    $body = preg_replace('/(src|background|href)=(["\']?)([\.\/]+[^"\'\s]+)(\2|\s|>)/Uie', "'\\1=\"'.make_absolute_url('\\3', '$base_url').'\"'", $body);
1151    $body = preg_replace('/(url\s*\()(["\']?)([\.\/]+[^"\'\)\s]+)(\2)\)/Uie', "'\\1\''.make_absolute_url('\\3', '$base_url').'\')'", $body);
1152    $body = preg_replace($base_reg, '', $body);
1153    }
1154
1155  // add comments arround html and other tags
1156  $out = preg_replace(array('/(<\/?html[^>]*>)/i',
1157                            '/(<\/?head[^>]*>)/i',
1158                            '/(<title[^>]*>.+<\/title>)/ui',
1159                            '/(<\/?meta[^>]*>)/i'),
1160                      '<!--\\1-->',
1161                      $body);
1162                     
1163  $out = preg_replace(array('/(<body[^>]*>)/i',
1164                            '/(<\/body>)/i'),
1165                      array('<div class="rcmBody">',
1166                            '</div>'),
1167                      $out);
1168
1169 
1170  return $out;
1171  }
1172
1173
1174
1175// replace all css definitions with #container [def]
1176function rcmail_mod_css_styles($source, $container_id)
1177  {
1178  $a_css_values = array();
1179  $last_pos = 0;
1180 
1181  // cut out all contents between { and }
1182  while (($pos = strpos($source, '{', $last_pos)) && ($pos2 = strpos($source, '}', $pos)))
1183    {
1184    $key = sizeof($a_css_values);
1185    $a_css_values[$key] = substr($source, $pos+1, $pos2-($pos+1));
1186    $source = substr($source, 0, $pos+1) . "<<str_replacement[$key]>>" . substr($source, $pos2, strlen($source)-$pos2);
1187    $last_pos = $pos+2;
1188    }
1189 
1190  $styles = preg_replace('/(^\s*|,\s*)([a-z0-9\._][a-z0-9\.\-_]*)/im', "\\1#$container_id \\2", $source);
1191  $styles = preg_replace('/<<str_replacement\[([0-9]+)\]>>/e', "\$a_css_values[\\1]", $styles);
1192 
1193  // replace body definition because we also stripped off the <body> tag
1194  $styles = preg_replace("/$container_id\s+body/i", "$container_id div.rcmBody", $styles);
1195 
1196  return $styles;
1197  }
1198
1199
1200
1201// return first text part of a message
1202function rcmail_first_text_part($message_parts)
1203  {
1204  if (!is_array($message_parts))
1205    return FALSE;
1206   
1207  $html_part = NULL;
1208     
1209  // check all message parts
1210  foreach ($message_parts as $pid => $part)
1211    {
1212    $mimetype = strtolower($part->ctype_primary.'/'.$part->ctype_secondary);
1213    if ($mimetype=='text/plain')
1214      {
1215      $body = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1216      $body = rcube_imap::charset_decode($body, $part->ctype_parameters);
1217      return $body;
1218      }
1219    else if ($mimetype=='text/html')
1220      {
1221      $html_part = rcube_imap::mime_decode($part->body, $part->headers['content-transfer-encoding']);
1222      $html_part = rcube_imap::charset_decode($html_part, $part->ctype_parameters);
1223      }
1224    }
1225   
1226
1227  // convert HTML to plain text
1228  if ($html_part)
1229    {   
1230    // remove special chars encoding
1231    $trans = array_flip(get_html_translation_table(HTML_ENTITIES));
1232    $html_part = strtr($html_part, $trans);
1233
1234    // create instance of html2text class
1235    $txt = new html2text($html_part);
1236    return $txt->get_text();
1237    }
1238
1239  return FALSE;
1240  }
1241
1242
1243// get source code of a specific message and cache it
1244function rcmail_message_source($uid)
1245  {
1246  global $IMAP, $DB, $CONFIG;
1247
1248  // get message ID if uid is given
1249  $cache_key = $IMAP->mailbox.'.msg';
1250  $cached = $IMAP->get_cached_message($cache_key, $uid, FALSE);
1251 
1252  // message is cached in database
1253  if ($cached && !empty($cached->body))
1254    return $cached->body;
1255
1256  if (!$cached)
1257    $headers = $IMAP->get_headers($uid);
1258  else
1259    $headers = &$cached;
1260
1261  // create unique identifier based on message_id
1262  if (!empty($headers->messageID))
1263    $message_id = md5($headers->messageID);
1264  else
1265    $message_id = md5($headers->uid.'@'.$_SESSION['imap_host']);
1266 
1267  $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '');
1268  $cache_dir = $temp_dir.$_SESSION['client_id'];
1269  $cache_path = $cache_dir.'/'.$message_id;
1270
1271  // message is cached in temp dir
1272  if ($CONFIG['enable_caching'] && is_dir($cache_dir) && is_file($cache_path))
1273    {
1274    if ($fp = fopen($cache_path, 'r'))
1275      {
1276      $msg_source = fread($fp, filesize($cache_path));
1277      fclose($fp);
1278      return $msg_source;
1279      }
1280    }
1281
1282
1283  // get message from server
1284  $msg_source = $IMAP->get_raw_body($uid);
1285 
1286  // return message source without caching
1287  if (!$CONFIG['enable_caching'])
1288    return $msg_source;
1289
1290
1291  // let's cache the message body within the database
1292  if ($cached && ($CONFIG['db_max_length'] -300) > $headers->size)
1293    {
1294    $DB->query("UPDATE ".get_table_name('messages')."
1295                SET    body=?
1296                WHERE  user_id=?
1297                AND    cache_key=?
1298                AND    uid=?",
1299               $msg_source,
1300               $_SESSION['user_id'],
1301               $cache_key,
1302               $uid);
1303
1304    return $msg_source;
1305    }
1306
1307
1308  // create dir for caching
1309  if (!is_dir($cache_dir))
1310    $dir = mkdir($cache_dir);
1311  else
1312    $dir = true;
1313
1314  // attempt to write a file with the message body   
1315  if ($dir && ($fp = fopen($cache_path, 'w')))
1316    {
1317    fwrite($fp, $msg_source);
1318    fclose($fp);
1319    }
1320  else
1321    {
1322    raise_error(array('code' => 403, 'type' => 'php', 'line' => __LINE__, 'file' => __FILE__,
1323                      'message' => "Failed to write to temp dir"), TRUE, FALSE);
1324    }
1325
1326  return $msg_source;
1327  }
1328
1329
1330// decode address string and re-format it as HTML links
1331function rcmail_address_string($input, $max=NULL, $addicon=NULL)
1332  {
1333  global $IMAP, $PRINT_MODE, $CONFIG, $OUTPUT, $JS_OBJECT_NAME, $EMAIL_ADDRESS_PATTERN;
1334 
1335  $a_parts = $IMAP->decode_address_list($input);
1336
1337  if (!sizeof($a_parts))
1338    return $input;
1339
1340  $c = count($a_parts);
1341  $j = 0;
1342  $out = '';
1343
1344  foreach ($a_parts as $part)
1345    {
1346    $j++;
1347    if ($PRINT_MODE)
1348      $out .= sprintf('%s &lt;%s&gt;', rep_specialchars_output($part['name']), $part['mailto']);
1349    else if (preg_match($EMAIL_ADDRESS_PATTERN, $part['mailto']))
1350      {
1351      $out .= sprintf('<a href="mailto:%s" onclick="return %s.command(\'compose\',\'%s\',this)" class="rcmContactAddress" title="%s">%s</a>',
1352                      $part['mailto'],
1353                      $JS_OBJECT_NAME,
1354                      $part['mailto'],
1355                      $part['mailto'],
1356                      rep_specialchars_output($part['name']));
1357                     
1358      if ($addicon)
1359        $out .= sprintf('&nbsp;<a href="#add" onclick="return %s.command(\'add-contact\',\'%s\',this)" title="%s"><img src="%s%s" alt="add" border="0" /></a>',
1360                        $JS_OBJECT_NAME,
1361                        urlencode($part['string']),
1362                        rcube_label('addtoaddressbook'),
1363                        $CONFIG['skin_path'],
1364                        $addicon);
1365      }
1366    else
1367      {
1368      if ($part['name'])
1369        $out .= rep_specialchars_output($part['name']);
1370      if ($part['mailto'])
1371        $out .= (strlen($out) ? ' ' : '') . sprintf('&lt;%s&gt;', $part['mailto']);
1372      }
1373     
1374    if ($c>$j)
1375      $out .= ','.($max ? '&nbsp;' : ' ');
1376       
1377    if ($max && $j==$max && $c>$j)
1378      {
1379      $out .= '...';
1380      break;
1381      }       
1382    }
1383   
1384  return $out;
1385  }
1386
1387
1388function rcmail_message_part_controls()
1389  {
1390  global $CONFIG, $IMAP, $MESSAGE;
1391 
1392  if (!is_array($MESSAGE) || !is_array($MESSAGE['parts']) || !($_GET['_uid'] && $_GET['_part']) || !$MESSAGE['parts'][$_GET['_part']])
1393    return '';
1394   
1395  $part = $MESSAGE['parts'][$_GET['_part']];
1396 
1397  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'cellspacing', 'cellpadding', 'border', 'summary'));
1398  $out = '<table '. $attrib_str . ">\n";
1399 
1400  $filename = $part->d_parameters['filename'] ? $part->d_parameters['filename'] : $part->ctype_parameters['name'];
1401  $filesize = strlen($IMAP->mime_decode($part->body, $part->headers['content-transfer-encoding']));
1402 
1403  if ($filename)
1404    {
1405    $out .= sprintf('<tr><td class="title">%s</td><td>%s</td><td>[<a href="./?%s">%s</a>]</tr>'."\n",
1406                    rcube_label('filename'),
1407                    rep_specialchars_output($filename),
1408                    str_replace('_frame=', '_download=', $_SERVER['QUERY_STRING']),
1409                    rcube_label('download'));
1410    }
1411   
1412  if ($filesize)
1413    $out .= sprintf('<tr><td class="title">%s</td><td>%s</td></tr>'."\n",
1414                    rcube_label('filesize'),
1415                    show_bytes($filesize));
1416 
1417  $out .= "\n</table>";
1418 
1419  return $out;
1420  }
1421
1422
1423
1424function rcmail_message_part_frame($attrib)
1425  {
1426  global $MESSAGE;
1427 
1428  $part = $MESSAGE['parts'][$_GET['_part']];
1429  $ctype_primary = strtolower($part->ctype_primary);
1430
1431  $attrib['src'] = './?'.str_replace('_frame=', ($ctype_primary=='text' ? '_show=' : '_preload='), $_SERVER['QUERY_STRING']);
1432
1433  $attrib_str = create_attrib_string($attrib, array('id', 'class', 'style', 'src', 'width', 'height'));
1434  $out = '<iframe '. $attrib_str . "></ifame>";
1435   
1436  return $out;
1437  }
1438
1439
1440// create temp dir for attachments
1441function rcmail_create_compose_tempdir()
1442  {
1443  global $CONFIG;
1444 
1445  if ($_SESSION['compose']['temp_dir'])
1446    return $_SESSION['compose']['temp_dir'];
1447 
1448  if (!empty($CONFIG['temp_dir']))
1449    $temp_dir = $CONFIG['temp_dir'].(!eregi('\/$', $CONFIG['temp_dir']) ? '/' : '').$_SESSION['compose']['id'];
1450
1451  // create temp-dir for uploaded attachments
1452  if (!empty($CONFIG['temp_dir']) && is_writeable($CONFIG['temp_dir']))
1453    {
1454    mkdir($temp_dir);
1455    $_SESSION['compose']['temp_dir'] = $temp_dir;
1456    }
1457
1458  return $_SESSION['compose']['temp_dir'];
1459  }
1460
1461
1462// clear message composing settings
1463function rcmail_compose_cleanup()
1464  {
1465  if (!isset($_SESSION['compose']))
1466    return;
1467 
1468  // remove attachment files from temp dir
1469  if (is_array($_SESSION['compose']['attachments']))
1470    foreach ($_SESSION['compose']['attachments'] as $attachment)
1471      @unlink($attachment['path']);
1472
1473  // kill temp dir
1474  if ($_SESSION['compose']['temp_dir'])
1475    @rmdir($_SESSION['compose']['temp_dir']);
1476 
1477  unset($_SESSION['compose']);
1478  }
1479 
1480 
1481?>
Note: See TracBrowser for help on using the repository browser.