1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace rdx\imap; |
4
|
|
|
|
5
|
|
|
class IMAPMailbox { |
6
|
|
|
|
7
|
|
|
public $server = ''; |
8
|
|
|
public $username = ''; |
9
|
|
|
public $password = ''; |
10
|
|
|
public $mailbox = ''; |
11
|
|
|
|
12
|
|
|
protected $imap; // IMAP resource |
13
|
|
|
|
14
|
|
|
public function __construct( $server, $username, $password, $mailbox = 'INBOX', $flags = array() ) { |
15
|
|
|
$this->server = $server; |
16
|
|
|
$this->username = $username; |
17
|
|
|
$this->password = $password; |
18
|
|
|
$this->mailbox = $mailbox; |
19
|
|
|
$this->flags = $flags; |
|
|
|
|
20
|
|
|
|
21
|
|
|
// $this->connect(); |
|
|
|
|
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function connect() { |
25
|
|
|
if ( !$this->imap ) { |
26
|
|
|
$server = $this->server; |
27
|
|
|
if ( $this->flags ) { |
28
|
|
|
$server .= '/' . implode('/', $this->flags); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
$mailbox = '{'.$server.'}'.$this->mailbox; |
32
|
|
|
$this->imap = imap_open($mailbox, $this->username, $this->password); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return $this->imap; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function imap() { |
39
|
|
|
return $this->imap; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function headers( $newestFirst = true ) { |
43
|
|
|
$this->connect(); |
44
|
|
|
|
45
|
|
|
$headers = imap_headers($this->imap()); |
46
|
|
|
|
47
|
|
|
if ( $newestFirst ) { |
48
|
|
|
$headers = array_reverse($headers); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $headers; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function messages( array $options = [] ) { |
55
|
|
|
$options += array( |
56
|
|
|
'offset' => 0, |
57
|
|
|
'limit' => 0, |
58
|
|
|
'seen' => null, |
59
|
|
|
'newestFirst' => true, |
60
|
|
|
); |
61
|
|
|
|
62
|
|
|
$headers = $this->headers($options['newestFirst']); |
63
|
|
|
|
64
|
|
|
$messages = array(); |
65
|
|
|
$eligibles = 0; |
66
|
|
|
foreach ( $headers AS $n => $header ) { |
67
|
|
|
if ( preg_match('/(U?)\s+(\d+)\)/', $header, $match) ) { |
68
|
|
|
$unseen = (bool)trim($match[1]); |
69
|
|
|
$msgNum = (int)$match[2]; |
70
|
|
|
|
71
|
|
|
$eligible = $options['seen'] === null || $unseen != $options['seen']; |
72
|
|
|
if ( $eligible ) { |
73
|
|
|
$eligibles++; |
74
|
|
|
|
75
|
|
|
if ( $eligibles > $options['offset'] ) { |
76
|
|
|
$messages[] = new IMAPMessage($this, $msgNum, $header, $unseen); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
if ( $options['limit'] && isset($messages[$options['limit']-1]) ) { |
81
|
|
|
break; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return $messages; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
} |
90
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: