]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Email.php
d147da1166dd52cd0e5b504a8b4b7b6973858190
[friendica.git] / src / Protocol / Email.php
1 <?php
2 /**
3  * @file src/Protocol/Email.php
4  */
5 namespace Friendica\Protocol;
6
7 require_once 'include/html2plain.php';
8 require_once 'include/msgclean.php';
9 require_once 'include/quoteconvert.php';
10
11 class Email
12 {
13         public static function emailConnect($mailbox, $username, $password)
14         {
15                 if (! function_exists('imap_open')) {
16                         return false;
17                 }
18
19                 $mbox = @imap_open($mailbox, $username, $password);
20
21                 return $mbox;
22         }
23
24         public static function emailPoll($mbox, $email_addr)
25         {
26                 if (! ($mbox && $email_addr))
27                         return array();
28
29                 $search1 = @imap_search($mbox,'FROM "' . $email_addr . '"', SE_UID);
30                 if (!$search1) {
31                         $search1 = array();
32                 } else {
33                         logger("Found mails from ".$email_addr, LOGGER_DEBUG);
34                 }
35
36                 $search2 = @imap_search($mbox,'TO "' . $email_addr . '"', SE_UID);
37                 if (!$search2) {
38                         $search2 = array();
39                 } else {
40                         logger("Found mails to ".$email_addr, LOGGER_DEBUG);
41                 }
42
43                 $search3 = @imap_search($mbox,'CC "' . $email_addr . '"', SE_UID);
44                 if (!$search3) {
45                         $search3 = array();
46                 } else {
47                         logger("Found mails cc ".$email_addr, LOGGER_DEBUG);
48                 }
49
50                 $res = array_unique(array_merge($search1, $search2, $search3));
51
52                 return $res;
53         }
54
55         public static function constructMailboxName($mailacct)
56         {
57                 $ret = '{' . $mailacct['server'] . ((intval($mailacct['port'])) ? ':' . $mailacct['port'] : '');
58                 $ret .= (($mailacct['ssltype']) ?  '/' . $mailacct['ssltype'] . '/novalidate-cert' : '');
59                 $ret .= '}' . $mailacct['mailbox'];
60                 return $ret;
61         }
62
63         public static function emailMsgMeta($mbox, $uid)
64         {
65                 $ret = (($mbox && $uid) ? @imap_fetch_overview($mbox,$uid,FT_UID) : array(array())); // POSSIBLE CLEANUP --> array(array()) is probably redundant now
66                 return ((count($ret)) ? $ret : array());
67         }
68
69         /**
70          * @brief Check addons, not called from main friendica project
71          */
72         function email_msg_headers($mbox, $uid) {
73                 $raw_header = (($mbox && $uid) ? @imap_fetchheader($mbox,$uid,FT_UID) : '');
74                 $raw_header = str_replace("\r",'',$raw_header);
75                 $ret = array();
76                 $h = explode("\n",$raw_header);
77                 if (count($h))
78                 foreach ($h as $line ) {
79                         if (preg_match("/^[a-zA-Z]/", $line)) {
80                                 $key = substr($line,0,strpos($line,':'));
81                                 $value = substr($line,strpos($line,':')+1);
82
83                                 $last_entry = strtolower($key);
84                                 $ret[$last_entry] = trim($value);
85                         }
86                         else {
87                                 $ret[$last_entry] .= ' ' . trim($line);
88                         }
89                 }
90                 return $ret;
91         }
92
93         public static function emailGetMsg($mbox, $uid, $reply)
94         {
95                 $ret = array();
96
97                 $struc = (($mbox && $uid) ? @imap_fetchstructure($mbox,$uid,FT_UID) : null);
98
99                 if (! $struc)
100                         return $ret;
101
102                 if (! $struc->parts) {
103                         $ret['body'] = self::emailGetPart($mbox,$uid,$struc,0, 'html');
104                         $html = $ret['body'];
105
106                         if (trim($ret['body']) == '')
107                                 $ret['body'] = self::emailGetPart($mbox,$uid,$struc,0, 'plain');
108                         else
109                                 $ret['body'] = html2bbcode($ret['body']);
110                 }
111                 else {
112                         $text = '';
113                         $html = '';
114                         foreach ($struc->parts as $ptop => $p) {
115                                 $x = self::emailGetPart($mbox,$uid,$p,$ptop + 1, 'plain');
116                                 if ($x) {
117                                         $text .= $x;
118                                 }
119
120                                 $x = self::emailGetPart($mbox,$uid,$p,$ptop + 1, 'html');
121                                 if ($x) {
122                                         $html .= $x;
123                                 }
124                         }
125                         if (trim($html) != '') {
126                                 $ret['body'] = html2bbcode($html);
127                         } else {
128                                 $ret['body'] = $text;
129                         }
130                 }
131
132                 $ret['body'] = removegpg($ret['body']);
133                 $msg = removesig($ret['body']);
134                 $ret['body'] = $msg['body'];
135                 $ret['body'] = convertquote($ret['body'], $reply);
136
137                 if (trim($html) != '') {
138                         $ret['body'] = removelinebreak($ret['body']);
139                 }
140
141                 $ret['body'] = unifyattributionline($ret['body']);
142
143                 return $ret;
144         }
145
146         // At the moment - only return plain/text.
147         // Later we'll repackage inline images as data url's and make the HTML safe
148
149         private static function emailGetPart($mbox, $uid, $p, $partno, $subtype)
150         {
151                 // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
152                 global $htmlmsg,$plainmsg,$charset,$attachments;
153
154                 //echo $partno."\n";
155
156                 // DECODE DATA
157                 $data = ($partno)
158                         ? @imap_fetchbody($mbox,$uid,$partno, FT_UID|FT_PEEK)
159                 : @imap_body($mbox,$uid,FT_UID|FT_PEEK);
160
161                 // Any part may be encoded, even plain text messages, so check everything.
162                 if ($p->encoding==4)
163                         $data = quoted_printable_decode($data);
164                 elseif ($p->encoding==3)
165                         $data = base64_decode($data);
166
167                 // PARAMETERS
168                 // get all parameters, like charset, filenames of attachments, etc.
169                 $params = array();
170                 if ($p->parameters)
171                         foreach ($p->parameters as $x)
172                                 $params[strtolower($x->attribute)] = $x->value;
173                 if (isset($p->dparameters) && $p->dparameters)
174                         foreach ($p->dparameters as $x)
175                                 $params[strtolower($x->attribute)] = $x->value;
176
177                 // ATTACHMENT
178                 // Any part with a filename is an attachment,
179                 // so an attached text file (type 0) is not mistaken as the message.
180
181                 if ((isset($params['filename']) && $params['filename']) || (isset($params['name']) && $params['name'])) {
182                         // filename may be given as 'Filename' or 'Name' or both
183                         $filename = ($params['filename'])? $params['filename'] : $params['name'];
184                         // filename may be encoded, so see imap_mime_header_decode()
185                         $attachments[$filename] = $data;  // this is a problem if two files have same name
186                 }
187
188                 // TEXT
189                 if ($p->type == 0 && $data) {
190                         // Messages may be split in different parts because of inline attachments,
191                         // so append parts together with blank row.
192                         if (strtolower($p->subtype)==$subtype) {
193                                 $data = iconv($params['charset'], 'UTF-8//IGNORE', $data);
194                                 return (trim($data) ."\n\n");
195                         } else
196                                 $data = '';
197
198                         // $htmlmsg .= $data ."<br><br>";
199                         $charset = $params['charset'];  // assume all parts are same charset
200                 }
201
202                 // EMBEDDED MESSAGE
203                 // Many bounce notifications embed the original message as type 2,
204                 // but AOL uses type 1 (multipart), which is not handled here.
205                 // There are no PHP functions to parse embedded messages,
206                 // so this just appends the raw source to the main message.
207                 //      elseif ($p->type==2 && $data) {
208                 //              $plainmsg .= $data."\n\n";
209                 //      }
210
211                 // SUBPART RECURSION
212                 if (isset($p->parts) && $p->parts) {
213                         $x = "";
214                         foreach ($p->parts as $partno0=>$p2) {
215                                 $x .=  self::emailGetPart($mbox,$uid,$p2,$partno . '.' . ($partno0+1), $subtype);  // 1.2, 1.2.1, etc.
216                                 //if ($x) {
217                                 //      return $x;
218                                 //}
219                         }
220                         return $x;
221                 }
222         }
223
224         public static function emailHeaderEncode($in_str, $charset)
225         {
226                 $out_str = $in_str;
227                 $need_to_convert = false;
228
229                 for ($x = 0; $x < strlen($in_str); $x ++) {
230                         if ((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) {
231                                 $need_to_convert = true;
232                         }
233                 }
234
235                 if (! $need_to_convert)
236                         return $in_str;
237
238                 if ($out_str && $charset) {
239
240                         // define start delimimter, end delimiter and spacer
241                         $end = "?=";
242                         $start = "=?" . $charset . "?B?";
243                         $spacer = $end . "\r\n " . $start;
244
245                         // determine length of encoded text within chunks
246                         // and ensure length is even
247                         $length = 75 - strlen($start) - strlen($end);
248
249                         /*
250                                 [EDIT BY danbrown AT php DOT net: The following
251                                 is a bugfix provided by (gardan AT gmx DOT de)
252                                 on 31-MAR-2005 with the following note:
253                                 "This means: $length should not be even,
254                                 but divisible by 4. The reason is that in
255                                 base64-encoding 3 8-bit-chars are represented
256                                 by 4 6-bit-chars. These 4 chars must not be
257                                 split between two encoded words, according
258                                 to RFC-2047.
259                         */
260                         $length = $length - ($length % 4);
261
262                         // encode the string and split it into chunks
263                         // with spacers after each chunk
264                         $out_str = base64_encode($out_str);
265                         $out_str = chunk_split($out_str, $length, $spacer);
266
267                         // remove trailing spacer and
268                         // add start and end delimiters
269                         $spacer = preg_quote($spacer,'/');
270                         $out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
271                         $out_str = $start . $out_str . $end;
272                 }
273                 return $out_str;
274         }
275
276         /**
277          * emailSend is used by NETWORK_EMAIL and NETWORK_EMAIL2 code
278          * (not to notify the user, but to send items to email contacts)
279          *
280          * @todo This could be changed to use the Emailer class
281          */
282         public static function emailSend($addr, $subject, $headers, $item)
283         {
284                 //$headers .= 'MIME-Version: 1.0' . "\n";
285                 //$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
286                 //$headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
287                 //$headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
288
289                 $part = uniqid("", true);
290
291                 $html    = prepare_body($item);
292
293                 $headers .= "Mime-Version: 1.0\n";
294                 $headers .= 'Content-Type: multipart/alternative; boundary="=_'.$part.'"'."\n\n";
295
296                 $body = "\n--=_".$part."\n";
297                 $body .= "Content-Transfer-Encoding: 8bit\n";
298                 $body .= "Content-Type: text/plain; charset=utf-8; format=flowed\n\n";
299
300                 $body .= html2plain($html)."\n";
301
302                 $body .= "--=_".$part."\n";
303                 $body .= "Content-Transfer-Encoding: 8bit\n";
304                 $body .= "Content-Type: text/html; charset=utf-8\n\n";
305
306                 $body .= '<html><head></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; ">'.$html."</body></html>\n";
307
308                 $body .= "--=_".$part."--";
309
310                 //$message = '<html><body>' . $html . '</body></html>';
311                 //$message = html2plain($html);
312                 logger('notifier: email delivery to ' . $addr);
313                 mail($addr, $subject, $body, $headers);
314         }
315
316         public static function iri2msgid($iri)
317         {
318                 if (!strpos($iri, "@"))
319                         $msgid = preg_replace("/urn:(\S+):(\S+)\.(\S+):(\d+):(\S+)/i", "urn!$1!$4!$5@$2.$3", $iri);
320                 else
321                         $msgid = $iri;
322                 return($msgid);
323         }
324
325         public static function msgid2iri($msgid)
326         {
327                 if (strpos($msgid, "@"))
328                         $iri = preg_replace("/urn!(\S+)!(\d+)!(\S+)@(\S+)\.(\S+)/i", "urn:$1:$4.$5:$2:$3", $msgid);
329                 else
330                         $iri = $msgid;
331                 return($iri);
332         }
333 }