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