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