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