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