]> git.mxchange.org Git - friendica.git/blob - src/Worker/OnePoll.php
cb892d332628685dc39f273e75fc733e3aca69cd
[friendica.git] / src / Worker / OnePoll.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
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\Core\System;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Model\Contact;
30 use Friendica\Model\Conversation;
31 use Friendica\Model\Item;
32 use Friendica\Model\Post;
33 use Friendica\Model\User;
34 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
35 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
36 use Friendica\Protocol\Activity;
37 use Friendica\Protocol\ActivityPub;
38 use Friendica\Protocol\Email;
39 use Friendica\Protocol\Feed;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Strings;
42
43 class OnePoll
44 {
45         public static function execute(int $contact_id = 0, string $command = '')
46         {
47                 Logger::notice('Start polling/probing contact', ['id' => $contact_id, 'command' => $command]);
48
49                 $force = ($command == 'force');
50
51                 if (empty($contact_id)) {
52                         Logger::notice('no contact provided');
53                         return;
54                 }
55
56                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
57                 if (!DBA::isResult($contact)) {
58                         Logger::warning('Contact not found', ['id' => $contact_id]);
59                         return;
60                 }
61
62                 // We never probe mail contacts since their probing demands a mail from the contact in the inbox.
63                 // We don't probe feed accounts by default since they are polled in a higher frequency, but forced probes are okay.
64                 if ($force && ($contact['network'] == Protocol::FEED)) {
65                         $success = Contact::updateFromProbe($contact_id);
66                 } else {
67                         $success = true;
68                 }
69
70                 $importer_uid = $contact['uid'];
71
72                 $updated = DateTimeFormat::utcNow();
73
74                 // Possibly switch the remote contact to AP
75                 if ($success && ($contact['network'] === Protocol::OSTATUS)) {
76                         ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
77                 }
78
79                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
80
81                 if ($success && ($importer_uid != 0) && in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])
82                         && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
83                         $importer = User::getOwnerDataById($importer_uid);
84                         if (empty($importer)) {
85                                 Logger::warning('No self contact for user', ['uid' => $importer_uid]);
86
87                                 // set the last-update so we don't keep polling
88                                 Contact::update(['last-update' => $updated], ['id' => $contact['id']]);
89                                 return;
90                         }
91
92                         Logger::info('Start polling/subscribing', ['protocol' => $contact['network'], 'id' => $contact['id']]);
93                         if ($contact['network'] === Protocol::FEED) {
94                                 $success = self::pollFeed($contact, $importer);
95                         } elseif ($contact['network'] === Protocol::MAIL) {
96                                 $success = self::pollMail($contact, $importer_uid, $updated);
97                         } else {
98                                 $success = self::subscribeToHub($contact['url'], $importer, $contact, $contact['blocked'] ? 'unsubscribe' : 'subscribe');
99                         }
100                         if (!$success) {
101                                 Logger::notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]);
102                         }
103                 }
104
105                 if ($success) {
106                         self::updateContact($contact, ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
107                         Contact::unmarkForArchival($contact);
108                 } else {
109                         self::updateContact($contact, ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
110                         Contact::markForArchival($contact);
111                 }
112
113                 Logger::notice('End');
114                 return;
115         }
116
117         /**
118          * Updates a personal contact entry and the public contact entry
119          *
120          * @param array $contact The personal contact entry
121          * @param array $fields  The fields that are updated
122          *
123          * @return void
124          * @throws \Exception
125          */
126         private static function updateContact(array $contact, array $fields)
127         {
128                 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
129                         // Update the user's contact
130                         Contact::update($fields, ['id' => $contact['id']]);
131
132                         // Update the public contact
133                         Contact::update($fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
134
135                         // Update the rest of the contacts that aren't polled
136                         Contact::update($fields, ['rel' => Contact::FOLLOWER, 'nurl' => $contact['nurl']]);
137                 } else {
138                         // Update all contacts
139                         Contact::update($fields, ['nurl' => $contact['nurl']]);
140                 }
141         }
142
143         /**
144          * Poll Feed contacts
145          *
146          * @param  array $contact The personal contact entry
147          * @param  array $importer
148          *
149          * @return bool   Success
150          * @throws \Exception
151          */
152         private static function pollFeed(array $contact, array $importer): bool
153         {
154                 // Are we allowed to import from this person?
155                 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
156                         Logger::notice('Contact is blocked or only a follower');
157                         return false;
158                 }
159
160                 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-onepoll-');
161                 $curlResult = DI::httpClient()->get($contact['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::COOKIEJAR => $cookiejar]);
162                 unlink($cookiejar);
163
164                 if ($curlResult->isTimeout()) {
165                         Logger::notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]);
166                         return false;
167                 }
168
169                 $xml = $curlResult->getBody();
170                 if (empty($xml)) {
171                         Logger::notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]);
172                         return false;
173                 }
174
175                 if (!strstr($xml, '<')) {
176                         Logger::notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]);
177                         return false;
178                 }
179
180                 Logger::notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]);
181
182                 return !empty(Feed::import($xml, $importer, $contact));
183         }
184
185         /**
186          * Poll Mail contacts
187          *
188          * @param  array   $contact      The personal contact entry
189          * @param  integer $importer_uid The UID of the importer
190          * @param  string  $updated      The updated date
191          *
192          * @return bool Success
193          * @throws \Exception
194          */
195         private static function pollMail(array $contact, int $importer_uid, string $updated): bool
196         {
197                 Logger::info('Fetching mails', ['addr' => $contact['addr']]);
198
199                 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
200                 if ($mail_disabled) {
201                         Logger::notice('Mail is disabled');
202                         return false;
203                 }
204
205                 Logger::info('Mail is enabled');
206
207                 $mbox = null;
208                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
209
210                 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
211                 $mailconf = DBA::selectFirst('mailacct', [], $condition);
212                 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
213                         $mailbox = Email::constructMailboxName($mailconf);
214                         $password = '';
215                         openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
216                         $mbox = Email::connect($mailbox, $mailconf['user'], $password);
217                         unset($password);
218                         Logger::notice('Connect', ['user' => $mailconf['user']]);
219                         if ($mbox) {
220                                 $fields = ['last_check' => $updated];
221                                 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
222                                 Logger::notice('Connected', ['user' => $mailconf['user']]);
223                         } else {
224                                 Logger::notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]);
225                                 return false;
226                         }
227                 }
228
229                 if (empty($mbox)) {
230                         return false;
231                 }
232
233                 $msgs = Email::poll($mbox, $contact['addr']);
234
235                 if (count($msgs)) {
236                         Logger::info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]);
237
238                         $metas = Email::messageMeta($mbox, implode(',', $msgs));
239
240                         if (count($metas) != count($msgs)) {
241                                 Logger::info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas");
242                         } else {
243                                 $msgs = array_combine($msgs, $metas);
244
245                                 foreach ($msgs as $msg_uid => $meta) {
246                                         Logger::info('Parsing mail', ['message-uid' => $msg_uid]);
247
248                                         $datarray = [
249                                                 'uid'         => $importer_uid,
250                                                 'contact-id'  => $contact['id'],
251                                                 'verb'        => Activity::POST,
252                                                 'object-type' => Activity\ObjectType::NOTE,
253                                                 'network'     => Protocol::MAIL,
254                                                 'protocol'    => Conversation::PARCEL_IMAP,
255                                                 'direction'   => Conversation::PULL,
256                                         ];
257                                         $datarray['thr-parent'] = $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
258
259                                         // $meta = Email::messageMeta($mbox, $msg_uid);
260
261                                         // Have we seen it before?
262                                         $fields = ['deleted', 'id'];
263                                         $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
264                                         $item = Post::selectFirst($fields, $condition);
265                                         if (DBA::isResult($item)) {
266                                                 Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . ' UID: ' . $importer_uid . ' URI: ' . $datarray['uri']);
267
268                                                 // Only delete when mails aren't automatically moved or deleted
269                                                 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
270                                                         if ($meta->deleted && ! $item['deleted']) {
271                                                                 $fields = ['deleted' => true, 'changed' => $updated];
272                                                                 Item::update($fields, ['id' => $item['id']]);
273                                                         }
274
275                                                 switch ($mailconf['action']) {
276                                                         case 0:
277                                                                 Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.');
278                                                                 break;
279
280                                                         case 1:
281                                                                 Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']);
282                                                                 imap_delete($mbox, $msg_uid, FT_UID);
283                                                                 break;
284
285                                                         case 2:
286                                                                 Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']);
287                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
288                                                                 break;
289
290                                                         case 3:
291                                                                 Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']);
292                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
293                                                                 if ($mailconf['movetofolder'] != '') {
294                                                                         imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
295                                                                 }
296                                                                 break;
297                                                 }
298                                                 continue;
299                                         }
300
301                                         // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
302                                         $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
303                                         if (!trim($raw_refs)) {
304                                                 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
305                                         }
306                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
307
308                                         if ($raw_refs) {
309                                                 $refs_arr = explode(' ', $raw_refs);
310                                                 if (count($refs_arr)) {
311                                                         for ($x = 0; $x < count($refs_arr); $x ++) {
312                                                                 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
313                                                         }
314                                                 }
315                                                 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
316                                                 $parent = Post::selectFirst(['uri'], $condition);
317                                                 if (DBA::isResult($parent)) {
318                                                         $datarray['thr-parent'] = $parent['uri'];
319                                                 }
320                                         }
321
322                                         // Decoding the header
323                                         $subject = imap_mime_header_decode($meta->subject ?? '');
324                                         $datarray['title'] = "";
325                                         foreach ($subject as $subpart) {
326                                                 if ($subpart->charset != "default") {
327                                                         $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
328                                                 } else {
329                                                         $datarray['title'] .= $subpart->text;
330                                                 }
331                                         }
332                                         $datarray['title'] = trim($datarray['title']);
333
334                                         //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
335                                         $datarray['created'] = DateTimeFormat::utc($meta->date);
336
337                                         // Is it a reply?
338                                         $reply = ((substr(strtolower($datarray['title']), 0, 3) == 're:') ||
339                                                 (substr(strtolower($datarray['title']), 0, 3) == 're-') ||
340                                                 ($raw_refs != ''));
341
342                                         // Remove Reply-signs in the subject
343                                         $datarray['title'] = self::removeReply($datarray['title']);
344
345                                         // If it seems to be a reply but a header couldn't be found take the last message with matching subject
346                                         if (empty($datarray['thr-parent']) && $reply) {
347                                                 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
348                                                 $params = ['order' => ['created' => true]];
349                                                 $parent = Post::selectFirst(['uri'], $condition, $params);
350                                                 if (DBA::isResult($parent)) {
351                                                         $datarray['thr-parent'] = $parent['uri'];
352                                                 }
353                                         }
354
355                                         $headers = imap_headerinfo($mbox, $meta->msgno);
356
357                                         $object = [];
358
359                                         if (!empty($headers->from)) {
360                                                 $object['from'] = $headers->from;
361                                         }
362
363                                         if (!empty($headers->to)) {
364                                                 $object['to'] = $headers->to;
365                                         }
366
367                                         if (!empty($headers->reply_to)) {
368                                                 $object['reply_to'] = $headers->reply_to;
369                                         }
370
371                                         if (!empty($headers->sender)) {
372                                                 $object['sender'] = $headers->sender;
373                                         }
374
375                                         if (!empty($object)) {
376                                                 $datarray['object'] = json_encode($object);
377                                         }
378
379                                         $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
380                                         if (!empty($headers->from[0]->personal)) {
381                                                 $fromname = $headers->from[0]->personal;
382                                         }
383
384                                         $datarray['author-name'] = $fromname;
385                                         $datarray['author-link'] = 'mailto:' . $frommail;
386                                         $datarray['author-avatar'] = $contact['photo'];
387
388                                         $datarray['owner-name'] = $contact['name'];
389                                         $datarray['owner-link'] = 'mailto:' . $contact['addr'];
390                                         $datarray['owner-avatar'] = $contact['photo'];
391
392                                         if (empty($datarray['thr-parent']) || ($datarray['thr-parent'] === $datarray['uri'])) {
393                                                 $datarray['private'] = Item::PRIVATE;
394                                         }
395
396                                         if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
397                                                 $datarray['private'] = Item::PRIVATE;
398                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
399                                         }
400
401                                         $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
402                                         if (empty($datarray['body'])) {
403                                                 Logger::warning('Cannot fetch mail', ['msg-id' => $msg_uid, 'uid' => $mailconf['user']]);
404                                                 continue;
405                                         }
406
407                                         Logger::notice('Mail: Importing ' . $msg_uid . ' for ' . $mailconf['user']);
408
409                                         Item::insert($datarray);
410
411                                         switch ($mailconf['action']) {
412                                                 case 0:
413                                                         Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.');
414                                                         break;
415
416                                                 case 1:
417                                                         Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']);
418                                                         imap_delete($mbox, $msg_uid, FT_UID);
419                                                         break;
420
421                                                 case 2:
422                                                         Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']);
423                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
424                                                         break;
425
426                                                 case 3:
427                                                         Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']);
428                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
429                                                         if ($mailconf['movetofolder'] != '') {
430                                                                 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
431                                                         }
432                                                         break;
433                                         }
434                                 }
435                         }
436                 } else {
437                         Logger::notice('No mails', ['user' => $mailconf['user']]);
438                 }
439
440
441                 Logger::info('Closing connection', ['user' => $mailconf['user']]);
442                 imap_close($mbox);
443
444                 return true;
445         }
446
447         private static function removeReply(string $subject): string
448         {
449                 while (in_array(strtolower(substr($subject, 0, 3)), ['re:', 'aw:'])) {
450                         $subject = trim(substr($subject, 4));
451                 }
452
453                 return $subject;
454         }
455
456         /**
457          * @param string $url
458          * @param array  $importer
459          * @param array  $contact
460          * @param string $hubmode
461          *
462          * @return bool Success
463          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
464          */
465         private static function subscribeToHub(string $url, array $importer, array $contact, string $hubmode = 'subscribe'): bool
466         {
467                 $push_url = DI::baseUrl() . '/pubsub/' . $importer['nick'] . '/' . $contact['id'];
468
469                 // Use a single verify token, even if multiple hubs
470                 $verify_token = $contact['hub-verify'] ?: Strings::getRandomHex();
471
472                 $params = 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
473
474                 Logger::info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]);
475
476                 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
477                         Contact::update(['hub-verify' => $verify_token], ['id' => $contact['id']]);
478                 }
479
480                 $postResult = DI::httpClient()->post($url, $params);
481
482                 Logger::info('Hub subscription done', ['result' => $postResult->getReturnCode()]);
483
484                 return $postResult->isSuccess();
485         }
486 }