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