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