source: subversion/trunk/roundcubemail/program/include/rcube_imap.inc @ 25

Last change on this file since 25 was 25, checked in by roundcube, 8 years ago

Better support for Courier IMAP

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.4 KB
Line 
1<?php
2
3/*
4 +-----------------------------------------------------------------------+
5 | program/include/rcube_imap.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 |   IMAP wrapper that implements the Iloha IMAP Library (IIL)           |
13 |   See http://ilohamail.org/ for details                               |
14 |                                                                       |
15 +-----------------------------------------------------------------------+
16 | Author: Thomas Bruederli <roundcube@gmail.com>                        |
17 +-----------------------------------------------------------------------+
18
19 $Id$
20
21*/
22
23
24require_once('lib/imap.inc');
25require_once('lib/mime.inc');
26
27
28class rcube_imap
29  {
30  var $conn;
31  var $root_ns = '';
32  var $root_dir = '';
33  var $mailbox = 'INBOX';
34  var $list_page = 1;
35  var $page_size = 10;
36  var $delimiter = NULL;
37  var $caching_enabled = FALSE;
38  var $default_folders = array('inbox', 'drafts', 'sent', 'junk', 'trash');
39  var $cache = array();
40  var $cache_changes = array(); 
41  var $uid_id_map = array();
42  var $msg_headers = array();
43
44
45  // PHP 5 constructor
46  function __construct()
47    {
48   
49    }
50
51  // PHP 4 compatibility
52  function rcube_imap()
53    {
54    $this->__construct();
55    }
56
57
58  function connect($host, $user, $pass, $port=143, $use_ssl=FALSE)
59    {
60    global $ICL_PORT, $CONFIG;
61   
62    // check for Open-SSL support in PHP build
63    if ($use_ssl && in_array('openssl', get_loaded_extensions()))
64      $ICL_SSL = TRUE;
65    else if ($use_ssl)
66      {
67      raise_error(array('code' => 403,
68                        'type' => 'imap',
69                        'message' => 'Open SSL not available;'), TRUE, FALSE);
70      $port = 143;
71      }
72
73    $ICL_PORT = $port;
74    $this->conn = iil_Connect($host, $user, $pass, array('imap' => 'check'));
75    $this->host = $host;
76    $this->user = $user;
77    $this->pass = $pass;
78    $this->port = $port;
79    $this->ssl = $use_ssl;
80   
81    // print trace mesages
82    if ($this->conn && ($CONFIG['debug_level'] & 8))
83      console($this->conn->message);
84   
85    // write error log
86    else if (!$this->conn && $GLOBALS['iil_error'])
87      {
88      raise_error(array('code' => 403,
89                       'type' => 'imap',
90                       'message' => $GLOBALS['iil_error']), TRUE, FALSE);
91      }
92
93    // get account namespace
94    if ($this->conn)
95      {
96      iil_C_NameSpace($this->conn);
97     
98      if (!empty($this->conn->delimiter))
99        $this->delimiter = $this->conn->delimiter;
100      if (!empty($this->conn->rootdir))
101        $this->root_ns = $this->conn->rootdir;
102      }
103
104    return $this->conn ? TRUE : FALSE;
105    }
106
107
108  function close()
109    {   
110    if ($this->conn)
111      iil_Close($this->conn);
112    }
113
114
115  function reconnect()
116    {
117    $this->close();
118    $this->connect($this->host, $this->user, $this->pass, $this->port, $this->ssl);
119    }
120
121
122  function set_rootdir($root)
123    {
124    if (ereg('[\.\/]$', $root)) //(substr($root, -1, 1)==='/')
125      $root = substr($root, 0, -1);
126
127    $this->root_dir = $root;
128   
129    if (empty($this->delimiter))
130      $this->get_hierarchy_delimiter();
131    }
132
133
134  function set_default_mailboxes($arr)
135    {
136    if (is_array($arr))
137      {
138      $this->default_folders = array();
139     
140      // add mailbox names lower case
141      foreach ($arr as $mbox)
142        $this->default_folders[] = strtolower($mbox);
143     
144      // add inbox if not included
145      if (!in_array('inbox', $this->default_folders))
146        array_unshift($arr, 'inbox');
147      }
148    }
149
150
151  function set_mailbox($mbox)
152    {
153    $mailbox = $this->_mod_mailbox($mbox);
154
155    if ($this->mailbox == $mailbox)
156      return;
157
158    $this->mailbox = $mailbox;
159
160    // clear messagecount cache for this mailbox
161    $this->_clear_messagecount($mailbox);
162    }
163
164
165  function set_page($page)
166    {
167    $this->list_page = (int)$page;
168    }
169
170
171  function set_pagesize($size)
172    {
173    $this->page_size = (int)$size;
174    }
175
176
177  function get_mailbox_name()
178    {
179    return $this->conn ? $this->_mod_mailbox($this->mailbox, 'out') : '';
180    }
181
182
183  function get_hierarchy_delimiter()
184    {
185    if ($this->conn && empty($this->delimiter))
186      $this->delimiter = iil_C_GetHierarchyDelimiter($this->conn);
187
188    return $this->delimiter;
189    }
190
191  // public method for mailbox listing
192  // convert mailbox name with root dir first
193  function list_mailboxes($root='', $filter='*')
194    {
195    $a_out = array();
196    $a_mboxes = $this->_list_mailboxes($root, $filter);
197
198    foreach ($a_mboxes as $mbox)
199      {
200      $name = $this->_mod_mailbox($mbox, 'out');
201      if (strlen($name))
202        $a_out[] = $name;
203      }
204
205    // sort mailboxes
206    $a_out = $this->_sort_mailbox_list($a_out);
207
208    return $a_out;
209    }
210
211  // private method for mailbox listing
212  function _list_mailboxes($root='', $filter='*')
213    {
214    $a_defaults = $a_out = array();
215   
216    // get cached folder list   
217    $a_mboxes = $this->get_cache('mailboxes');
218    if (is_array($a_mboxes))
219      return $a_mboxes;
220
221    // retrieve list of folders from IMAP server
222    $a_folders = iil_C_ListSubscribed($this->conn, $this->_mod_mailbox($root), $filter);
223   
224    if (!is_array($a_folders) || !sizeof($a_folders))
225      $a_folders = array();
226
227    // create INBOX if it does not exist
228    if (!in_array_nocase('INBOX', $a_folders))
229      {
230      $this->create_mailbox('INBOX', TRUE);
231      array_unshift($a_folders, 'INBOX');
232      }
233
234    $a_mailbox_cache = array();
235
236    // write mailboxlist to cache
237    $this->update_cache('mailboxes', $a_folders);
238   
239    return $a_folders;
240    }
241
242
243  // get message count for a specific mailbox; acceptes modes are: ALL, UNSEEN
244  function messagecount($mbox='', $mode='ALL', $force=FALSE)
245    {
246    $mailbox = $mbox ? $this->_mod_mailbox($mbox) : $this->mailbox;
247    return $this->_messagecount($mailbox, $mode, $force);
248    }
249
250  // private method for getting nr of mesages
251  function _messagecount($mailbox='', $mode='ALL', $force=FALSE)
252    {
253    $a_mailbox_cache = FALSE;
254    $mode = strtoupper($mode);
255
256    if (!$mailbox)
257      $mailbox = $this->mailbox;
258
259    $a_mailbox_cache = $this->get_cache('messagecount');
260   
261    // return cached value
262    if (!$force && is_array($a_mailbox_cache[$mailbox]) && isset($a_mailbox_cache[$mailbox][$mode]))
263      return $a_mailbox_cache[$mailbox][$mode];     
264
265    // get message count and store in cache
266    if ($mode == 'UNSEEN')
267      $count = iil_C_CountUnseen($this->conn, $mailbox);
268    else
269      $count = iil_C_CountMessages($this->conn, $mailbox);
270
271//print "/**** get messagecount for $mailbox ($mode): $count ****/\n";
272
273    if (is_array($a_mailbox_cache[$mailbox]))
274      $a_mailbox_cache[$mailbox] = array();
275     
276    $a_mailbox_cache[$mailbox][$mode] = (int)$count;
277   
278    // write back to cache
279    $this->update_cache('messagecount', $a_mailbox_cache);
280
281//var_dump($a_mailbox_cache);
282
283    return (int)$count;
284    }
285
286
287  // public method for listing headers
288  // convert mailbox name with root dir first
289  function list_headers($mbox='', $page=NULL, $sort_field='date', $sort_order='DESC')
290    {
291    $mailbox = $mbox ? $this->_mod_mailbox($mbox) : $this->mailbox;
292    return $this->_list_headers($mailbox, $page, $sort_field, $sort_order);
293    }
294
295
296  // private method for listing message header
297  function _list_headers($mailbox='', $page=NULL, $sort_field='date', $sort_order='DESC')
298    {
299    $max = $this->_messagecount($mailbox /*, 'ALL', TRUE*/);
300    $a_out = array();
301   
302    if (!strlen($mailbox))
303      return $a_out;
304
305
306    // get cached headers
307    $a_msg_headers = $this->get_cache($mailbox.'.msg');
308
309// print "/**** count = $max; headers = ".sizeof($a_msg_headers)." ****/\n";
310
311    // retrieve headers from IMAP
312    if (!is_array($a_msg_headers) || sizeof($a_msg_headers) != $max)
313      {
314      $a_header_index = iil_C_FetchHeaders($this->conn, $mailbox, "1:$max");
315      $a_msg_headers = array();
316      foreach ($a_header_index as $i => $headers)
317        $a_msg_headers[$headers->uid] = $headers;
318       
319// print "/**** fetch headers ****/\n";
320      }
321    else
322      $headers_cached = TRUE;
323
324    // sort headers by a specific col
325    $a_headers = iil_SortHeaders($a_msg_headers, $sort_field, $sort_order);
326   
327    // write headers list to cache
328    if (!$headers_cached)
329      $this->update_cache($mailbox.'.msg', $a_msg_headers);
330
331    if (is_array($a_headers))
332      foreach ($a_headers as $header)
333        if (!$header->deleted)
334          $a_out[] = $header;
335
336    // return complete list of messages
337    if (strtolower($page)=='all')
338      return $a_out;
339
340    $start_msg = ($this->list_page-1) * $this->page_size;
341    return array_slice($a_out, $start_msg, $this->page_size);
342    }
343
344
345  // return sorted array of message UIDs
346  function message_index($mbox='', $sort_field='date', $sort_order='DESC')
347    {
348    $mailbox = $mbox ? $this->_mod_mailbox($mbox) : $this->mailbox;
349    $a_out = array();
350
351    // get array of message headers
352    $a_headers = $this->_list_headers($mailbox, 'all', $sort_field, $sort_order);
353
354    if (is_array($a_headers))
355      foreach ($a_headers as $header)
356        $a_out[] = $header->uid;
357
358    return $a_out;
359    }
360
361
362  function sync_header_index($mbox=NULL)
363    {
364   
365    }
366
367
368  function search($mbox='', $criteria='ALL')
369    {
370    $mailbox = $mbox ? $this->_mod_mailbox($mbox) : $this->mailbox;
371    $a_messages = iil_C_Search($this->conn, $mailbox, $criteria);
372    return $a_messages;
373    }
374
375
376  function get_headers($uid, $mbox=NULL)
377    {
378    $mailbox = $mbox ? $this->_mod_mailbox($mbox) : $this->mailbox;
379   
380    // get cached headers
381    $a_msg_headers = $this->get_cache($mailbox.'.msg');
382   
383    // return cached header
384    if ($a_msg_headers[$uid])
385      return $a_msg_headers[$uid];
386
387    $msg_id = $this->_uid2id($uid);
388    $header = iil_C_FetchHeader($this->conn, $mailbox, $msg_id);
389
390    // write headers cache
391    $a_msg_headers[$uid] = $header;
392    $this->update_cache($mailbox.'.msg', $a_msg_headers);
393
394    return $header;
395    }
396
397
398  function get_body($uid, $part=1)
399    {
400    if (!($msg_id = $this->_uid2id($uid)))
401      return FALSE;
402
403        $structure_str = iil_C_FetchStructureString($this->conn, $this->mailbox, $msg_id);
404        $structure = iml_GetRawStructureArray($structure_str);
405    $body = iil_C_FetchPartBody($this->conn, $this->mailbox, $msg_id, $part);
406
407    $encoding = iml_GetPartEncodingCode($structure, $part);
408   
409    if ($encoding==3) $body = $this->mime_decode($body, 'base64');
410    else if ($encoding==4) $body = $this->mime_decode($body, 'quoted-printable');
411
412    return $body;
413    }
414
415
416  function get_raw_body($uid)
417    {
418    if (!($msg_id = $this->_uid2id($uid)))
419      return FALSE;
420
421        $body = iil_C_FetchPartHeader($this->conn, $this->mailbox, $msg_id, NULL);
422        $body .= iil_C_HandlePartBody($this->conn, $this->mailbox, $msg_id, NULL, 1);
423
424    return $body;   
425    }
426
427
428  // set message flag to one or several messages
429  // possible flgs are: SEEN, DELETED, RECENT, ANSWERED, DRAFT
430  function set_flag($uids, $flag)
431    {
432    $flag = strtoupper($flag);
433    $msg_ids = array();
434    if (!is_array($uids))
435      $uids = array($uids);
436     
437    foreach ($uids as $uid)
438      $msg_ids[] = $this->_uid2id($uid);
439     
440    if ($flag=='UNSEEN')
441      $result = iil_C_Unseen($this->conn, $this->mailbox, join(',', $msg_ids));
442    else
443      $result = iil_C_Flag($this->conn, $this->mailbox, join(',', $msg_ids), $flag);
444
445    // reload message headers if cached
446    $cache_key = $this->mailbox.'.msg';
447    if ($this->caching_enabled && $result && ($a_cached_headers = $this->get_cache($cache_key)))
448      {
449      // close and re-open connection     
450      $this->reconnect();
451
452      foreach ($uids as $uid)
453        {
454        if (isset($a_cached_headers[$uid]))
455          {
456          unset($this->cache[$cache_key][$uid]);
457          $this->get_headers($uid);
458          }
459        }
460      }
461
462    // set nr of messages that were flaged
463    $count = sizeof($msg_ids);
464
465    // clear message count cache
466    if ($result && $flag=='SEEN')
467      $this->_set_messagecount($this->mailbox, 'UNSEEN', $count*(-1));
468    else if ($result && $flag=='UNSEEN')
469      $this->_set_messagecount($this->mailbox, 'UNSEEN', $count);
470    else if ($result && $flag=='DELETED')
471      $this->_set_messagecount($this->mailbox, 'ALL', $count*(-1));
472
473    return $result;
474    }
475
476
477  // append a mail message (source) to a specific mailbox
478  function save_message($mbox, $message)
479    {
480    $mailbox = $this->_mod_mailbox($mbox);
481
482    // make shure mailbox exists
483    if (in_array($mailbox, $this->_list_mailboxes()))
484      $saved = iil_C_Append($this->conn, $mailbox, $message);
485   
486    if ($saved)
487      {
488      // increase messagecount of the target mailbox
489      $this->_set_messagecount($mailbox, 'ALL', 1);
490      }
491         
492    return $saved;
493    }
494
495
496  // move a message from one mailbox to another
497  function move_message($uids, $to_mbox, $from_mbox='')
498    {
499    $to_mbox = $this->_mod_mailbox($to_mbox);
500    $from_mbox = $from_mbox ? $this->_mod_mailbox($from_mbox) : $this->mailbox;
501
502    // make shure mailbox exists
503    if (!in_array($to_mbox, $this->_list_mailboxes()))
504      return FALSE;
505   
506    // convert the list of uids to array
507    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
508   
509    // exit if no message uids are specified
510    if (!is_array($a_uids))
511      return false;
512
513    // convert uids to message ids
514    $a_mids = array();
515    foreach ($a_uids as $uid)
516      $a_mids[] = $this->_uid2id($uid, $from_mbox);
517
518    $moved = iil_C_Move($this->conn, join(',', $a_mids), $from_mbox, $to_mbox);
519   
520    // send expunge command in order to have the moved message
521    // really deleted from the source mailbox
522    if ($moved)
523      {
524      $this->expunge($from_mbox, FALSE);
525      $this->clear_cache($to_mbox.'.msg');
526      $this->_clear_messagecount($from_mbox);
527      $this->_clear_messagecount($to_mbox);
528      }
529
530    // update cached message headers
531    $cache_key = $from_mbox.'.msg';
532    if ($moved && ($a_cached_headers = $this->get_cache($cache_key)))
533      {
534      foreach ($a_uids as $uid)
535        unset($a_cached_headers[$uid]);
536
537      $this->update_cache($cache_key, $a_cached_headers);
538      }
539
540    return $moved;
541    }
542
543
544  // mark messages as deleted and expunge mailbox
545  function delete_message($uids, $mbox='')
546    {
547    $mailbox = $mbox ? $this->_mod_mailbox($mbox) : $this->mailbox;
548
549    // convert the list of uids to array
550    $a_uids = is_string($uids) ? explode(',', $uids) : (is_array($uids) ? $uids : NULL);
551   
552    // exit if no message uids are specified
553    if (!is_array($a_uids))
554      return false;
555
556
557    // convert uids to message ids
558    $a_mids = array();
559    foreach ($a_uids as $uid)
560      $a_mids[] = $this->_uid2id($uid, $mailbox);
561       
562    $deleted = iil_C_Delete($this->conn, $mailbox, join(',', $a_mids));
563   
564    // send expunge command in order to have the deleted message
565    // really deleted from the mailbox
566    if ($deleted)
567      {
568      $this->expunge($mailbox, FALSE);
569      $this->_clear_messagecount($mailbox);
570      }
571
572    // remove deleted messages from cache
573    if ($deleted && ($a_cached_headers = $this->get_cache($mailbox.'.msg')))
574      {
575      foreach ($a_uids as $uid)
576        unset($a_cached_headers[$uid]);
577
578      $this->update_cache($mailbox.'.msg', $a_cached_headers);
579      }
580
581    return $deleted;
582
583    }
584
585
586  // send IMAP expunge command and clear cache
587  function expunge($mbox='', $clear_cache=TRUE)
588    {
589    $mailbox = $mbox ? $this->_mod_mailbox($mbox) : $this->mailbox;
590   
591    $result = iil_C_Expunge($this->conn, $mailbox);
592
593    if ($result>=0 && $clear_cache)
594      {
595      $this->clear_cache($mailbox.'.msg');
596      $this->_clear_messagecount($mailbox);
597      }
598     
599    return $result;
600    }
601
602
603
604  /* --------------------------------
605   *        folder managment
606   * --------------------------------*/
607
608
609  // return an array with all folders available in IMAP server
610  function list_unsubscribed($root='')
611    {
612    static $sa_unsubscribed;
613   
614    if (is_array($sa_unsubscribed))
615      return $sa_unsubscribed;
616     
617    // retrieve list of folders from IMAP server
618    $a_mboxes = iil_C_ListMailboxes($this->conn, $this->_mod_mailbox($root), '*');
619
620    // modify names with root dir
621    foreach ($a_mboxes as $mbox)
622      {
623      $name = $this->_mod_mailbox($mbox, 'out');
624      if (strlen($name))
625        $a_folders[] = $name;
626      }
627
628    // filter folders and sort them
629    $sa_unsubscribed = $this->_sort_mailbox_list($a_folders);
630    return $sa_unsubscribed;
631    }
632
633
634  // subscribe to a specific mailbox(es)
635  function subscribe($mbox, $mode='subscribe')
636    {
637    if (is_array($mbox))
638      $a_mboxes = $mbox;
639    else if (is_string($mbox) && strlen($mbox))
640      $a_mboxes = explode(',', $mbox);
641   
642    // let this common function do the main work
643    return $this->_change_subscription($a_mboxes, 'subscribe');
644    }
645
646
647  // unsubscribe mailboxes
648  function unsubscribe($mbox)
649    {
650    if (is_array($mbox))
651      $a_mboxes = $mbox;
652    else if (is_string($mbox) && strlen($mbox))
653      $a_mboxes = explode(',', $mbox);
654
655    // let this common function do the main work
656    return $this->_change_subscription($a_mboxes, 'unsubscribe');
657    }
658
659
660  // create a new mailbox on the server and register it in local cache
661  function create_mailbox($name, $subscribe=FALSE)
662    {
663    $result = FALSE;
664    $abs_name = $this->_mod_mailbox($name);
665    $a_mailbox_cache = $this->get_cache('mailboxes');
666   
667    if (strlen($this->root_ns))
668      $abs_name = $this->root_ns.$abs_name;
669
670    if (strlen($abs_name) && (!is_array($a_mailbox_cache) || !in_array($abs_name, $a_mailbox_cache)))
671      $result = iil_C_CreateFolder($this->conn, iil_utf7_encode($abs_name));
672
673    // update mailboxlist cache
674    if ($result && $subscribe)
675      $this->subscribe($this->root_ns.$name);
676
677    return $result ? $this->root_ns.$name : FALSE;
678    }
679
680
681  // set a new name to an existing mailbox
682  function rename_mailbox($mbox, $new_name)
683    {
684    // not implemented yet
685    }
686
687
688  // remove mailboxes from server
689  function delete_mailbox($mbox)
690    {
691    $deleted = FALSE;
692
693    if (is_array($mbox))
694      $a_mboxes = $mbox;
695    else if (is_string($mbox) && strlen($mbox))
696      $a_mboxes = explode(',', $mbox);
697
698    if (is_array($a_mboxes))
699      foreach ($a_mboxes as $mbox)
700        {
701        $mailbox = $this->_mod_mailbox($mbox);
702
703        // unsubscribe mailbox before deleting
704        iil_C_UnSubscribe($this->conn, $mailbox);
705       
706        // send delete command to server
707        $result = iil_C_DeleteFolder($this->conn, $mailbox);
708        if ($result>=0)
709          $deleted = TRUE;
710        }
711
712    // clear mailboxlist cache
713    if ($deleted)
714      $this->clear_cache('mailboxes');
715
716    return $updated;
717    }
718
719
720
721
722  /* --------------------------------
723   *   internal caching functions
724   * --------------------------------*/
725
726
727  function set_caching($set)
728    {
729    if ($set && function_exists('rcube_read_cache'))
730      $this->caching_enabled = TRUE;
731    else
732      $this->caching_enabled = FALSE;
733    }
734
735  function get_cache($key)
736    {
737    // read cache
738    if (!isset($this->cache[$key]) && $this->caching_enabled)
739      {
740      $cache_data = rcube_read_cache('IMAP.'.$key);
741      $this->cache[$key] = strlen($cache_data) ? unserialize($cache_data) : FALSE;
742      }
743   
744    return $this->cache[$key];         
745    }
746
747
748  function update_cache($key, $data)
749    {
750    $this->cache[$key] = $data;
751    $this->cache_changed = TRUE;
752    $this->cache_changes[$key] = TRUE;
753    }
754
755
756  function write_cache()
757    {
758    if ($this->caching_enabled && $this->cache_changed)
759      {
760      foreach ($this->cache as $key => $data)
761        {
762        if ($this->cache_changes[$key])
763          rcube_write_cache('IMAP.'.$key, serialize($data));
764        }
765      }   
766    }
767
768
769  function clear_cache($key=NULL)
770    {
771    if ($key===NULL)
772      {
773      foreach ($this->cache as $key => $data)
774        rcube_clear_cache('IMAP.'.$key);
775
776      $this->cache = array();
777      $this->cache_changed = FALSE;
778      $this->cache_changes = array();
779      }
780    else
781      {
782      rcube_clear_cache('IMAP.'.$key);
783      $this->cache_changes[$key] = FALSE;
784      unset($this->cache[$key]);
785      }
786    }
787
788
789
790  /* --------------------------------
791   *   encoding/decoding functions
792   * --------------------------------*/
793
794 
795  function decode_address_list($input, $max=NULL)
796    {
797    $a = $this->_parse_address_list($input);
798    $out = array();
799
800    if (!is_array($a))
801      return $out;
802
803    $c = count($a);
804    $j = 0;
805
806    foreach ($a as $val)
807      {
808      $j++;
809      $address = $val['address'];
810      $name = preg_replace(array('/^[\'"]/', '/[\'"]$/'), '', trim($val['name']));
811      $string = $name!==$address ? sprintf('%s <%s>', strpos($name, ',')!==FALSE ? '"'.$name.'"' : $name, $address) : $address;
812     
813      $out[$j] = array('name' => $name,
814                       'mailto' => $address,
815                       'string' => $string);
816             
817      if ($max && $j==$max)
818        break;
819      }
820   
821    return $out;
822    }
823
824
825  function decode_header($input)
826    {
827    $out = '';
828
829    $pos = strpos($input, '=?');
830    if ($pos !== false)
831      {
832      $out = substr($input, 0, $pos);
833 
834      $end_cs_pos = strpos($input, "?", $pos+2);
835      $end_en_pos = strpos($input, "?", $end_cs_pos+1);
836      $end_pos = strpos($input, "?=", $end_en_pos+1);
837 
838      $encstr = substr($input, $pos+2, ($end_pos-$pos-2));
839      $rest = substr($input, $end_pos+2);
840
841      $out .= $this->decode_mime_string($encstr);
842      $out .= $this->decode_header($rest);
843
844      return $out;
845      }
846    else
847      return $input;
848    }
849
850
851  function decode_mime_string($str)
852    {
853    $a = explode('?', $str);
854    $count = count($a);
855
856    // should be in format "charset?encoding?base64_string"
857    if ($count >= 3)
858      {
859      for ($i=2; $i<$count; $i++)
860        $rest.=$a[$i];
861
862      if (($a[1]=="B")||($a[1]=="b"))
863        $rest = base64_decode($rest);
864      else if (($a[1]=="Q")||($a[1]=="q"))
865        {
866        $rest = str_replace("_", " ", $rest);
867        $rest = quoted_printable_decode($rest);
868        }
869
870      return decode_specialchars($rest, $a[0]);
871      }
872    else
873      return $str;    //we dont' know what to do with this 
874    }
875
876
877  function mime_decode($input, $encoding='7bit')
878    {
879    switch (strtolower($encoding))
880      {
881      case '7bit':
882        return $input;
883        break;
884     
885      case 'quoted-printable':
886        return quoted_printable_decode($input);
887        break;
888     
889      case 'base64':
890        return base64_decode($input);
891        break;
892     
893      default:
894        return $input;
895      }
896    }
897
898
899  function mime_encode($input, $encoding='7bit')
900    {
901    switch ($encoding)
902      {
903      case 'quoted-printable':
904        return quoted_printable_encode($input);
905        break;
906
907      case 'base64':
908        return base64_encode($input);
909        break;
910
911      default:
912        return $input;
913      }
914    }
915
916
917  // convert body chars according to the ctype_parameters
918  function charset_decode($body, $ctype_param)
919    {
920    if (is_array($ctype_param) && strlen($ctype_param['charset']))
921      return decode_specialchars($body, $ctype_param['charset']);
922
923    return $body;
924    }
925
926
927  /* --------------------------------
928   *         private methods
929   * --------------------------------*/
930
931
932  function _mod_mailbox($mbox, $mode='in')
933    {
934    if (!empty($this->root_dir) && $mode=='in')
935      $mbox = $this->root_dir.$this->delimiter.$mbox;
936    else if (strlen($this->root_dir) && $mode=='out')
937      $mbox = substr($mbox, strlen($this->root_dir)+1);
938
939    return $mbox;
940    }
941
942
943  // sort mailboxes first by default folders and then in alphabethical order
944  function _sort_mailbox_list($a_folders)
945    {
946    $a_out = $a_defaults = array();
947
948    // find default folders and skip folders starting with '.'
949    foreach($a_folders as $i => $folder)
950      {
951      if ($folder{0}=='.')
952        continue;
953       
954      if (($p = array_search(strtolower($folder), $this->default_folders))!==FALSE)
955        $a_defaults[$p] = $folder;
956      else
957        $a_out[] = $folder;
958      }
959
960    sort($a_out);
961    ksort($a_defaults);
962   
963    return array_merge($a_defaults, $a_out);
964    }
965
966
967  function _uid2id($uid, $mbox=NULL)
968    {
969    if (!$mbox)
970      $mbox = $this->mailbox;
971     
972    if (!isset($this->uid_id_map[$mbox][$uid]))
973      $this->uid_id_map[$mbox][$uid] = iil_C_UID2ID($this->conn, $mbox, $uid);
974
975    return $this->uid_id_map[$mbox][$uid];
976    }
977
978
979  // subscribe/unsubscribe a list of mailboxes and update local cache
980  function _change_subscription($a_mboxes, $mode)
981    {
982    $updated = FALSE;
983   
984    if (is_array($a_mboxes))
985      foreach ($a_mboxes as $i => $mbox)
986        {
987        $mailbox = $this->_mod_mailbox($mbox);
988        $a_mboxes[$i] = $mailbox;
989
990        if ($mode=='subscribe')
991          $result = iil_C_Subscribe($this->conn, $mailbox);
992        else if ($mode=='unsubscribe')
993          $result = iil_C_UnSubscribe($this->conn, $mailbox);
994
995        if ($result>=0)
996          $updated = TRUE;
997        }
998       
999    // get cached mailbox list   
1000    if ($updated)
1001      {
1002      $a_mailbox_cache = $this->get_cache('mailboxes');
1003      if (!is_array($a_mailbox_cache))
1004        return $updated;
1005
1006      // modify cached list
1007      if ($mode=='subscribe')
1008        $a_mailbox_cache = array_merge($a_mailbox_cache, $a_mboxes);
1009      else if ($mode=='unsubscribe')
1010        $a_mailbox_cache = array_diff($a_mailbox_cache, $a_mboxes);
1011       
1012      // write mailboxlist to cache
1013      $this->update_cache('mailboxes', $this->_sort_mailbox_list($a_mailbox_cache));
1014      }
1015
1016    return $updated;
1017    }
1018
1019
1020  // increde/decrese messagecount for a specific mailbox
1021  function _set_messagecount($mbox, $mode, $increment)
1022    {
1023    $a_mailbox_cache = FALSE;
1024    $mailbox = $mbox ? $mbox : $this->mailbox;
1025    $mode = strtoupper($mode);
1026
1027    $a_mailbox_cache = $this->get_cache('messagecount');
1028   
1029    if (!is_array($a_mailbox_cache[$mailbox]) || !isset($a_mailbox_cache[$mailbox][$mode]) || !is_numeric($increment))
1030      return FALSE;
1031   
1032    // add incremental value to messagecount
1033    $a_mailbox_cache[$mailbox][$mode] += $increment;
1034
1035    // write back to cache
1036    $this->update_cache('messagecount', $a_mailbox_cache);
1037   
1038    return TRUE;
1039    }
1040
1041
1042  // remove messagecount of a specific mailbox from cache
1043  function _clear_messagecount($mbox='')
1044    {
1045    $a_mailbox_cache = FALSE;
1046    $mailbox = $mbox ? $mbox : $this->mailbox;
1047
1048    $a_mailbox_cache = $this->get_cache('messagecount');
1049
1050    if (is_array($a_mailbox_cache[$mailbox]))
1051      {
1052      unset($a_mailbox_cache[$mailbox]);
1053      $this->update_cache('messagecount', $a_mailbox_cache);
1054      }
1055    }
1056
1057
1058  function _parse_address_list($str)
1059    {
1060    $a = $this->_explode_quoted_string(',', $str);
1061    $result = array();
1062
1063    foreach ($a as $key => $val)
1064      {
1065      $val = str_replace("\"<", "\" <", $val);
1066      $sub_a = $this->_explode_quoted_string(' ', $val);
1067     
1068      foreach ($sub_a as $k => $v)
1069        {
1070        if ((strpos($v, '@') > 0) && (strpos($v, '.') > 0))
1071          $result[$key]['address'] = str_replace('<', '', str_replace('>', '', $v));
1072        else
1073          $result[$key]['name'] .= (empty($result[$key]['name'])?'':' ').str_replace("\"",'',stripslashes($v));
1074        }
1075       
1076      if (empty($result[$key]['name']))
1077        $result[$key]['name'] = $result[$key]['address'];
1078       
1079      $result[$key]['name'] = $this->decode_header($result[$key]['name']);
1080      }
1081   
1082    return $result;
1083    }
1084
1085
1086  function _explode_quoted_string($delimiter, $string)
1087    {
1088    $quotes = explode("\"", $string);
1089    foreach ($quotes as $key => $val)
1090      if (($key % 2) == 1)
1091        $quotes[$key] = str_replace($delimiter, "_!@!_", $quotes[$key]);
1092       
1093    $string = implode("\"", $quotes);
1094
1095    $result = explode($delimiter, $string);
1096    foreach ($result as $key => $val)
1097      $result[$key] = str_replace("_!@!_", $delimiter, $result[$key]);
1098   
1099    return $result;
1100    }
1101  }
1102
1103
1104
1105
1106
1107function quoted_printable_encode($input="", $line_max=76, $space_conv=false)
1108  {
1109  $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
1110  $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
1111  $eol = "\r\n";
1112  $escape = "=";
1113  $output = "";
1114
1115  while( list(, $line) = each($lines))
1116    {
1117    //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
1118    $linlen = strlen($line);
1119    $newline = "";
1120    for($i = 0; $i < $linlen; $i++)
1121      {
1122      $c = substr( $line, $i, 1 );
1123      $dec = ord( $c );
1124      if ( ( $i == 0 ) && ( $dec == 46 ) ) // convert first point in the line into =2E
1125        {
1126        $c = "=2E";
1127        }
1128      if ( $dec == 32 )
1129        {
1130        if ( $i == ( $linlen - 1 ) ) // convert space at eol only
1131          {
1132          $c = "=20";
1133          }
1134        else if ( $space_conv )
1135          {
1136          $c = "=20";
1137          }
1138        }
1139      else if ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) )  // always encode "\t", which is *not* required
1140        {
1141        $h2 = floor($dec/16);
1142        $h1 = floor($dec%16);
1143        $c = $escape.$hex["$h2"].$hex["$h1"];
1144        }
1145         
1146      if ( (strlen($newline) + strlen($c)) >= $line_max )  // CRLF is not counted
1147        {
1148        $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
1149        $newline = "";
1150        // check if newline first character will be point or not
1151        if ( $dec == 46 )
1152          {
1153          $c = "=2E";
1154          }
1155        }
1156      $newline .= $c;
1157      } // end of for
1158    $output .= $newline.$eol;
1159    } // end of while
1160
1161  return trim($output);
1162  }
1163
1164?>
Note: See TracBrowser for help on using the repository browser.