]> git.mxchange.org Git - friendica.git/blob - src/Worker/OnePoll.php
c87bfcf25d7cde578c37a5108baa637b3f80748b
[friendica.git] / src / Worker / OnePoll.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Worker;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Model\Contact;
29 use Friendica\Model\Item;
30 use Friendica\Model\User;
31 use Friendica\Protocol\Activity;
32 use Friendica\Protocol\ActivityPub;
33 use Friendica\Protocol\Email;
34 use Friendica\Protocol\PortableContact;
35 use Friendica\Util\DateTimeFormat;
36 use Friendica\Util\Network;
37 use Friendica\Util\Strings;
38 use Friendica\Util\XML;
39
40 class OnePoll
41 {
42         public static function execute($contact_id = 0, $command = '')
43         {
44                 Logger::log('Start for contact ' . $contact_id);
45
46                 $force = false;
47
48                 if ($command == "force") {
49                         $force = true;
50                 }
51
52                 if (!$contact_id) {
53                         Logger::log('no contact');
54                         return;
55                 }
56
57
58                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
59                 if (!DBA::isResult($contact)) {
60                         Logger::log('Contact not found or cannot be used.');
61                         return;
62                 }
63
64                 if (($contact['network'] != Protocol::MAIL) || $force) {
65                         Contact::updateFromProbe($contact_id, '', $force);
66                 }
67
68                 // Special treatment for wrongly detected local contacts
69                 if (!$force && ($contact['network'] != Protocol::DFRN) && Contact::isLocalById($contact_id)) {
70                         Contact::updateFromProbe($contact_id, Protocol::DFRN, true);
71                         $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
72                 }
73
74                 if (($contact['network'] == Protocol::DFRN) && !Contact::isLegacyDFRNContact($contact)) {
75                         $protocol = Protocol::ACTIVITYPUB;
76                 } else {
77                         $protocol = $contact['network'];
78                 }
79
80                 $importer_uid = $contact['uid'];
81
82                 $updated = DateTimeFormat::utcNow();
83
84                 if ($importer_uid == 0) {
85                         Logger::log('Ignore public contacts');
86
87                         // set the last-update so we don't keep polling
88                         DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
89                         return;
90                 }
91
92                 // Possibly switch the remote contact to AP
93                 if ($protocol === Protocol::OSTATUS) {
94                         ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
95                         $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
96                 }
97
98                 // load current friends if possible.
99                 if (!empty($contact['poco']) && ($contact['success_update'] > $contact['failure_update'])) {
100                         if (!DBA::exists('glink', ["`cid` = ? AND updated > UTC_TIMESTAMP() - INTERVAL 1 DAY", $contact['id']])) {
101                                 PortableContact::loadWorker($contact['id'], $importer_uid, 0, $contact['poco']);
102                         }
103                 }
104
105                 // Don't poll if polling is deactivated (But we poll feeds and mails anyway)
106                 if (!in_array($protocol, [Protocol::FEED, Protocol::MAIL]) && DI::config()->get('system', 'disable_polling')) {
107                         Logger::log('Polling is disabled');
108
109                         // set the last-update so we don't keep polling
110                         DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
111                         return;
112                 }
113
114                 // We don't poll AP contacts by now
115                 if ($protocol === Protocol::ACTIVITYPUB) {
116                         Logger::log("Don't poll AP contact");
117
118                         // set the last-update so we don't keep polling
119                         DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
120                         return;
121                 }
122
123                 $importer = User::getOwnerDataById($importer_uid);
124
125                 if (empty($importer)) {
126                         Logger::log('No self contact for user '.$importer_uid);
127
128                         // set the last-update so we don't keep polling
129                         DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
130                         return;
131                 }
132
133                 $url = '';
134                 $xml = false;
135
136                 if ($contact['subhub']) {
137                         $poll_interval = DI::config()->get('system', 'pushpoll_frequency', 3);
138                         $contact['priority'] = intval($poll_interval);
139                         $hub_update = false;
140
141                         if (DateTimeFormat::utcNow() > DateTimeFormat::utc($contact['last-update'] . " + 1 day")) {
142                                 $hub_update = true;
143                         }
144                 } else {
145                         $hub_update = false;
146                 }
147
148                 Logger::log("poll: ({$protocol}-{$contact['id']}) IMPORTER: {$importer['name']}, CONTACT: {$contact['name']}");
149
150                 $xml = '';
151
152                 if ($protocol === Protocol::DFRN) {
153                         $xml = self::pollDFRN($contact, $updated);
154                 } elseif (($protocol === Protocol::OSTATUS)
155                         || ($protocol === Protocol::DIASPORA)
156                         || ($protocol === Protocol::FEED)) {
157                         $xml = self::pollFeed($contact, $protocol, $updated);
158                 } elseif ($protocol === Protocol::MAIL) {
159                         self::pollMail($contact, $importer_uid, $updated);
160                 }
161
162                 if (!empty($xml)) {
163                         Logger::log('received xml : ' . $xml, Logger::DATA);
164                         if (!strstr($xml, '<')) {
165                                 Logger::log('post_handshake: response from ' . $url . ' did not contain XML.');
166
167                                 $fields = ['last-update' => $updated, 'failure_update' => $updated];
168                                 self::updateContact($contact, $fields);
169                                 Contact::markForArchival($contact);
170                                 return;
171                         }
172
173
174                         Logger::log("Consume feed of contact ".$contact['id']);
175
176                         consume_feed($xml, $importer, $contact, $hub);
177
178                         // do it a second time for DFRN so that any children find their parents.
179                         if ($protocol === Protocol::DFRN) {
180                                 consume_feed($xml, $importer, $contact, $hub);
181                         }
182
183                         $hubmode = 'subscribe';
184                         if ($protocol === Protocol::DFRN || $contact['blocked']) {
185                                 $hubmode = 'unsubscribe';
186                         }
187
188                         if (($protocol === Protocol::OSTATUS ||  $protocol == Protocol::FEED) && (! $contact['hub-verify'])) {
189                                 $hub_update = true;
190                         }
191
192                         if ($force) {
193                                 $hub_update = true;
194                         }
195
196                         Logger::log("Contact ".$contact['id']." returned hub: ".$hub." Network: ".$protocol." Relation: ".$contact['rel']." Update: ".$hub_update);
197
198                         if (strlen($hub) && $hub_update && (($contact['rel'] != Contact::FOLLOWER) || $protocol == Protocol::FEED)) {
199                                 Logger::log('hub ' . $hubmode . ' : ' . $hub . ' contact name : ' . $contact['name'] . ' local user : ' . $importer['name']);
200                                 $hubs = explode(',', $hub);
201
202                                 if (count($hubs)) {
203                                         foreach ($hubs as $h) {
204                                                 $h = trim($h);
205
206                                                 if (!strlen($h)) {
207                                                         continue;
208                                                 }
209
210                                                 subscribe_to_hub($h, $importer, $contact, $hubmode);
211                                         }
212                                 }
213                         }
214
215                         self::updateContact($contact, ['last-update' => $updated, 'success_update' => $updated]);
216                         Contact::unmarkForArchival($contact);
217                 } elseif (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED])) {
218                         self::updateContact($contact, ['last-update' => $updated, 'failure_update' => $updated]);
219                         Contact::markForArchival($contact);
220                 } else {
221                         self::updateContact($contact, ['last-update' => $updated]);
222                 }
223
224                 Logger::log('End');
225                 return;
226         }
227
228         private static function RemoveReply($subject)
229         {
230                 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
231                         $subject = trim(substr($subject, 4));
232                 }
233
234                 return $subject;
235         }
236
237         /**
238          * Updates a personal contact entry and the public contact entry
239          *
240          * @param array $contact The personal contact entry
241          * @param array $fields  The fields that are updated
242          * @throws \Exception
243          */
244         private static function updateContact(array $contact, array $fields)
245         {
246                 DBA::update('contact', $fields, ['id' => $contact['id']]);
247                 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
248         }
249
250         /**
251          * Poll DFRN contacts
252          *
253          * @param  array  $contact The personal contact entry
254          * @param  string $updated The updated date
255          * @return string polled XML
256          * @throws \Exception
257          */
258         private static function pollDFRN(array $contact, $updated)
259         {
260                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
261                 if (intval($contact['duplex']) && $contact['dfrn-id']) {
262                         $idtosend = '0:' . $orig_id;
263                 }
264                 if (intval($contact['duplex']) && $contact['issued-id']) {
265                         $idtosend = '1:' . $orig_id;
266                 }
267
268                 // they have permission to write to us. We already filtered this in the contact query.
269                 $perm = 'rw';
270
271                 // But this may be our first communication, so set the writable flag if it isn't set already.
272                 if (!intval($contact['writable'])) {
273                         $fields = ['writable' => true];
274                         DBA::update('contact', $fields, ['id' => $contact['id']]);
275                 }
276
277                 $last_update = (($contact['last-update'] <= DBA::NULL_DATETIME)
278                         ? DateTimeFormat::utc('now - 7 days', DateTimeFormat::ATOM)
279                         : DateTimeFormat::utc($contact['last-update'], DateTimeFormat::ATOM)
280                 );
281
282                 $url = $contact['poll'] . '?dfrn_id=' . $idtosend
283                         . '&dfrn_version=' . DFRN_PROTOCOL_VERSION
284                         . '&type=data&last_update=' . $last_update
285                         . '&perm=' . $perm;
286
287                 $curlResult = Network::curl($url);
288
289                 if (!$curlResult->isSuccess() && ($curlResult->getErrorNumber() == CURLE_OPERATION_TIMEDOUT)) {
290                         // set the last-update so we don't keep polling
291                         self::updateContact($contact, ['last-update' => $updated]);
292                         Contact::markForArchival($contact);
293                         Logger::log('Contact archived');
294                         return false;
295                 }
296
297                 $handshake_xml = $curlResult->getBody();
298                 $html_code = $curlResult->getReturnCode();
299
300                 Logger::log('handshake with url ' . $url . ' returns xml: ' . $handshake_xml, Logger::DATA);
301
302                 if (!strlen($handshake_xml) || ($html_code >= 400) || !$html_code) {
303                         // dead connection - might be a transient event, or this might
304                         // mean the software was uninstalled or the domain expired.
305                         // Will keep trying for one month.
306                         Logger::log("$url appears to be dead - marking for death ");
307
308                         // set the last-update so we don't keep polling
309                         $fields = ['last-update' => $updated, 'failure_update' => $updated];
310                         self::updateContact($contact, $fields);
311                         Contact::markForArchival($contact);
312                         return false;
313                 }
314
315                 if (!strstr($handshake_xml, '<')) {
316                         Logger::log('response from ' . $url . ' did not contain XML.');
317
318                         $fields = ['last-update' => $updated, 'failure_update' => $updated];
319                         self::updateContact($contact, $fields);
320                         Contact::markForArchival($contact);
321                         return false;
322                 }
323
324                 $res = XML::parseString($handshake_xml);
325
326                 if (!is_object($res)) {
327                         Logger::info('Unparseable response', ['url' => $url]);
328
329                         $fields = ['last-update' => $updated, 'failure_update' => $updated];
330                         self::updateContact($contact, $fields);
331                         Contact::markForArchival($contact);
332                         return false;
333                 }
334
335                 if (intval($res->status) == 1) {
336                         // we may not be friends anymore. Will keep trying for one month.
337                         Logger::log("$url replied status 1 - marking for death ");
338
339                         // set the last-update so we don't keep polling
340                         $fields = ['last-update' => $updated, 'failure_update' => $updated];
341                         self::updateContact($contact, $fields);
342                         Contact::markForArchival($contact);
343                 } elseif ($contact['term-date'] > DBA::NULL_DATETIME) {
344                         Contact::unmarkForArchival($contact);
345                 }
346
347                 if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
348                         // set the last-update so we don't keep polling
349                         DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
350                         Logger::log('Contact status is ' . $res->status);
351                         return false;
352                 }
353
354                 if (((float)$res->dfrn_version > 2.21) && ($contact['poco'] == '')) {
355                         $fields = ['poco' => str_replace('/profile/', '/poco/', $contact['url'])];
356                         DBA::update('contact', $fields, ['id' => $contact['id']]);
357                 }
358
359                 $postvars = [];
360
361                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
362                 $challenge    = hex2bin((string) $res->challenge);
363
364                 $final_dfrn_id = '';
365
366                 if ($contact['duplex'] && strlen($contact['prvkey'])) {
367                         openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
368                         openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
369                 } else {
370                         openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
371                         openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
372                 }
373
374                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
375
376                 if (strpos($final_dfrn_id, ':') == 1) {
377                         $final_dfrn_id = substr($final_dfrn_id, 2);
378                 }
379
380                 // There are issues with the legacy DFRN transport layer.
381                 // Since we mostly don't use it anyway, we won't dig into it deeper, but simply ignore it.
382                 if (empty($final_dfrn_id) || empty($orig_id)) {
383                         Logger::log('Contact has got no ID - quitting');
384                         return false;
385                 }
386
387                 if ($final_dfrn_id != $orig_id) {
388                         // did not decode properly - cannot trust this site
389                         Logger::log('ID did not decode: ' . $contact['id'] . ' orig: ' . $orig_id . ' final: ' . $final_dfrn_id);
390
391                         // set the last-update so we don't keep polling
392                         DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
393                         Contact::markForArchival($contact);
394                         return false;
395                 }
396
397                 $postvars['dfrn_id'] = $idtosend;
398                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
399                 $postvars['perm'] = 'rw';
400
401                 return Network::post($contact['poll'], $postvars)->getBody();
402         }
403
404         /**
405          * Poll Feed/OStatus contacts
406          *
407          * @param  array  $contact The personal contact entry
408          * @param  string $protocol The used protocol of the contact
409          * @param  string $updated The updated date
410          * @return string polled XML
411          * @throws \Exception
412          */
413         private static function pollFeed(array $contact, $protocol, $updated)
414         {
415                 // Upgrading DB fields from an older Friendica version
416                 // Will only do this once per notify-enabled OStatus contact
417                 // or if relationship changes
418
419                 $stat_writeable = ((($contact['notify']) && ($contact['rel'] == Contact::FOLLOWER || $contact['rel'] == Contact::FRIEND)) ? 1 : 0);
420
421                 // Contacts from OStatus are always writable
422                 if ($protocol === Protocol::OSTATUS) {
423                         $stat_writeable = 1;
424                 }
425
426                 if ($stat_writeable != $contact['writable']) {
427                         $fields = ['writable' => $stat_writeable];
428                         DBA::update('contact', $fields, ['id' => $contact['id']]);
429                 }
430
431                 // Are we allowed to import from this person?
432                 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
433                         // set the last-update so we don't keep polling
434                         DBA::update('contact', ['last-update' => $updated], ['id' => $contact['id']]);
435                         Logger::log('Contact is blocked or only a follower');
436                         return false;
437                 }
438
439                 $cookiejar = tempnam(get_temppath(), 'cookiejar-onepoll-');
440                 $curlResult = Network::curl($contact['poll'], false, ['cookiejar' => $cookiejar]);
441                 unlink($cookiejar);
442
443                 if ($curlResult->isTimeout()) {
444                         // set the last-update so we don't keep polling
445                         self::updateContact($contact, ['last-update' => $updated]);
446                         Contact::markForArchival($contact);
447                         Logger::log('Contact archived');
448                         return false;
449                 }
450
451                 return $curlResult->getBody();
452         }
453
454         /**
455          * Poll Mail contacts
456          *
457          * @param  array   $contact      The personal contact entry
458          * @param  integer $importer_uid The UID of the importer
459          * @param  string  $updated      The updated date
460          * @throws \Exception
461          */
462         private static function pollMail(array $contact, $importer_uid, $updated)
463         {
464                 Logger::log("Mail: Fetching for ".$contact['addr'], Logger::DEBUG);
465
466                 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
467                 if ($mail_disabled) {
468                         // set the last-update so we don't keep polling
469                         self::updateContact($contact, ['last-update' => $updated]);
470                         Contact::markForArchival($contact);
471                         Logger::log('Contact archived');
472                         return;
473                 }
474
475                 Logger::log("Mail: Enabled", Logger::DEBUG);
476
477                 $mbox = null;
478                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
479
480                 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
481                 $mailconf = DBA::selectFirst('mailacct', [], $condition);
482                 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
483                         $mailbox = Email::constructMailboxName($mailconf);
484                         $password = '';
485                         openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
486                         $mbox = Email::connect($mailbox, $mailconf['user'], $password);
487                         unset($password);
488                         Logger::log("Mail: Connect to " . $mailconf['user']);
489                         if ($mbox) {
490                                 $fields = ['last_check' => $updated];
491                                 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
492                                 Logger::log("Mail: Connected to " . $mailconf['user']);
493                         } else {
494                                 Logger::log("Mail: Connection error ".$mailconf['user']." ".print_r(imap_errors(), true));
495                         }
496                 }
497
498                 if (!$mbox) {
499                         return;
500                 }
501
502                 $msgs = Email::poll($mbox, $contact['addr']);
503
504                 if (count($msgs)) {
505                         Logger::log("Mail: Parsing ".count($msgs)." mails from ".$contact['addr']." for ".$mailconf['user'], Logger::DEBUG);
506
507                         $metas = Email::messageMeta($mbox, implode(',', $msgs));
508
509                         if (count($metas) != count($msgs)) {
510                                 Logger::log("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas", Logger::DEBUG);
511                         } else {
512                                 $msgs = array_combine($msgs, $metas);
513
514                                 foreach ($msgs as $msg_uid => $meta) {
515                                         Logger::log("Mail: Parsing mail ".$msg_uid, Logger::DATA);
516
517                                         $datarray = [];
518                                         $datarray['uid'] = $importer_uid;
519                                         $datarray['contact-id'] = $contact['id'];
520                                         $datarray['verb'] = Activity::POST;
521                                         $datarray['object-type'] = Activity\ObjectType::NOTE;
522                                         $datarray['network'] = Protocol::MAIL;
523                                         // $meta = Email::messageMeta($mbox, $msg_uid);
524
525                                         $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
526
527                                         // Have we seen it before?
528                                         $fields = ['deleted', 'id'];
529                                         $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
530                                         $item = Item::selectFirst($fields, $condition);
531                                         if (DBA::isResult($item)) {
532                                                 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri'],Logger::DEBUG);
533
534                                                 // Only delete when mails aren't automatically moved or deleted
535                                                 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
536                                                         if ($meta->deleted && ! $item['deleted']) {
537                                                                 $fields = ['deleted' => true, 'changed' => $updated];
538                                                                 Item::update($fields, ['id' => $item['id']]);
539                                                         }
540
541                                                 switch ($mailconf['action']) {
542                                                         case 0:
543                                                                 Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
544                                                                 break;
545                                                         case 1:
546                                                                 Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
547                                                                 imap_delete($mbox, $msg_uid, FT_UID);
548                                                                 break;
549                                                         case 2:
550                                                                 Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
551                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
552                                                                 break;
553                                                         case 3:
554                                                                 Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
555                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
556                                                                 if ($mailconf['movetofolder'] != "") {
557                                                                         imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
558                                                                 }
559                                                                 break;
560                                                 }
561                                                 continue;
562                                         }
563
564                                         // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
565                                         $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
566                                         if (!trim($raw_refs)) {
567                                                 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
568                                         }
569                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
570
571                                         if ($raw_refs) {
572                                                 $refs_arr = explode(' ', $raw_refs);
573                                                 if (count($refs_arr)) {
574                                                         for ($x = 0; $x < count($refs_arr); $x ++) {
575                                                                 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
576                                                         }
577                                                 }
578                                                 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
579                                                 $parent = Item::selectFirst(['parent-uri'], $condition);
580                                                 if (DBA::isResult($parent)) {
581                                                         $datarray['parent-uri'] = $parent['parent-uri'];  // Set the parent as the top-level item
582                                                 }
583                                         }
584
585                                         // Decoding the header
586                                         $subject = imap_mime_header_decode($meta->subject ?? '');
587                                         $datarray['title'] = "";
588                                         foreach ($subject as $subpart) {
589                                                 if ($subpart->charset != "default") {
590                                                         $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
591                                                 } else {
592                                                         $datarray['title'] .= $subpart->text;
593                                                 }
594                                         }
595                                         $datarray['title'] = Strings::escapeTags(trim($datarray['title']));
596
597                                         //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
598                                         $datarray['created'] = DateTimeFormat::utc($meta->date);
599
600                                         // Is it a reply?
601                                         $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
602                                                 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
603                                                 ($raw_refs != ""));
604
605                                         // Remove Reply-signs in the subject
606                                         $datarray['title'] = self::RemoveReply($datarray['title']);
607
608                                         // If it seems to be a reply but a header couldn't be found take the last message with matching subject
609                                         if (empty($datarray['parent-uri']) && $reply) {
610                                                 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
611                                                 $params = ['order' => ['created' => true]];
612                                                 $parent = Item::selectFirst(['parent-uri'], $condition, $params);
613                                                 if (DBA::isResult($parent)) {
614                                                         $datarray['parent-uri'] = $parent['parent-uri'];
615                                                 }
616                                         }
617
618                                         if (empty($datarray['parent-uri'])) {
619                                                 $datarray['parent-uri'] = $datarray['uri'];
620                                         }
621
622                                         $headers = imap_headerinfo($mbox, $meta->msgno);
623
624                                         $object = [];
625
626                                         if (!empty($headers->from)) {
627                                                 $object['from'] = $headers->from;
628                                         }
629
630                                         if (!empty($headers->to)) {
631                                                 $object['to'] = $headers->to;
632                                         }
633
634                                         if (!empty($headers->reply_to)) {
635                                                 $object['reply_to'] = $headers->reply_to;
636                                         }
637
638                                         if (!empty($headers->sender)) {
639                                                 $object['sender'] = $headers->sender;
640                                         }
641
642                                         if (!empty($object)) {
643                                                 $datarray['object'] = json_encode($object);
644                                         }
645
646                                         $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
647                                         if (!empty($headers->from[0]->personal)) {
648                                                 $fromname = $headers->from[0]->personal;
649                                         }
650
651                                         $datarray['author-name'] = $fromname;
652                                         $datarray['author-link'] = "mailto:".$frommail;
653                                         $datarray['author-avatar'] = $contact['photo'];
654
655                                         $datarray['owner-name'] = $contact['name'];
656                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
657                                         $datarray['owner-avatar'] = $contact['photo'];
658
659                                         if ($datarray['parent-uri'] === $datarray['uri']) {
660                                                 $datarray['private'] = 1;
661                                         }
662
663                                         if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
664                                                 $datarray['private'] = 1;
665                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
666                                         }
667
668                                         $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
669                                         if (empty($datarray['body'])) {
670                                                 Logger::log("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
671                                                 continue;
672                                         }
673
674                                         Logger::log("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
675
676                                         Item::insert($datarray);
677
678                                         switch ($mailconf['action']) {
679                                                 case 0:
680                                                         Logger::log("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.", Logger::DEBUG);
681                                                         break;
682                                                 case 1:
683                                                         Logger::log("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
684                                                         imap_delete($mbox, $msg_uid, FT_UID);
685                                                         break;
686                                                 case 2:
687                                                         Logger::log("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
688                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
689                                                         break;
690                                                 case 3:
691                                                         Logger::log("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
692                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
693                                                         if ($mailconf['movetofolder'] != "") {
694                                                                 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
695                                                         }
696                                                         break;
697                                         }
698                                 }
699                         }
700                 } else {
701                         Logger::log("Mail: no mails for ".$mailconf['user']);
702                 }
703
704                 Logger::log("Mail: closing connection for ".$mailconf['user']);
705                 imap_close($mbox);
706         }
707 }