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