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