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