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