3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Worker;
24 use Friendica\Core\Logger;
25 use Friendica\Core\Protocol;
26 use Friendica\Core\System;
27 use Friendica\Database\DBA;
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\Network;
42 use Friendica\Util\Strings;
46 public static function execute(int $contact_id = 0, string $command = '')
48 Logger::notice('Start polling/probing contact', ['id' => $contact_id, 'command' => $command]);
50 $force = ($command == 'force');
52 if (empty($contact_id)) {
53 Logger::notice('no contact provided');
57 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
58 if (!DBA::isResult($contact)) {
59 Logger::warning('Contact not found', ['id' => $contact_id]);
63 // We never probe mail contacts since their probing demands a mail from the contact in the inbox.
64 // We don't probe feed accounts by default since they are polled in a higher frequency, but forced probes are okay.
65 if ($force && ($contact['network'] == Protocol::FEED)) {
66 $success = Contact::updateFromProbe($contact_id);
71 $importer_uid = $contact['uid'];
73 $updated = DateTimeFormat::utcNow();
75 // Possibly switch the remote contact to AP
76 if ($success && ($contact['network'] === Protocol::OSTATUS)) {
77 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
80 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
82 if ($success && ($importer_uid != 0) && in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])
83 && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
84 $importer = User::getOwnerDataById($importer_uid);
85 if (empty($importer)) {
86 Logger::warning('No self contact for user', ['uid' => $importer_uid]);
88 // set the last-update so we don't keep polling
89 Contact::update(['last-update' => $updated], ['id' => $contact['id']]);
93 Logger::info('Start polling/subscribing', ['protocol' => $contact['network'], 'id' => $contact['id']]);
94 if ($contact['network'] === Protocol::FEED) {
95 $success = self::pollFeed($contact, $importer);
96 } elseif ($contact['network'] === Protocol::MAIL) {
97 $success = self::pollMail($contact, $importer_uid, $updated);
99 $success = self::subscribeToHub($contact['url'], $importer, $contact, $contact['blocked'] ? 'unsubscribe' : 'subscribe');
102 Logger::notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]);
107 self::updateContact($contact, ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
108 Contact::unmarkForArchival($contact);
110 self::updateContact($contact, ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
111 Contact::markForArchival($contact);
114 Logger::notice('End');
119 * Updates a personal contact entry and the public contact entry
121 * @param array $contact The personal contact entry
122 * @param array $fields The fields that are updated
127 private static function updateContact(array $contact, array $fields)
129 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
130 // Update the user's contact
131 Contact::update($fields, ['id' => $contact['id']]);
133 // Update the public contact
134 Contact::update($fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
136 // Update the rest of the contacts that aren't polled
137 Contact::update($fields, ['rel' => Contact::FOLLOWER, 'nurl' => $contact['nurl']]);
139 // Update all contacts
140 Contact::update($fields, ['nurl' => $contact['nurl']]);
147 * @param array $contact The personal contact entry
148 * @param array $importer
150 * @return bool Success
153 private static function pollFeed(array $contact, array $importer): bool
155 // Are we allowed to import from this person?
156 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
157 Logger::notice('Contact is blocked or only a follower');
161 if (!Network::isValidHttpUrl($contact['poll'])) {
162 Logger::warning('Poll address is not valid', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'poll' => $contact['poll']]);
166 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-onepoll-');
167 $curlResult = DI::httpClient()->get($contact['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::COOKIEJAR => $cookiejar]);
170 if ($curlResult->isTimeout()) {
171 Logger::notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]);
175 $xml = $curlResult->getBody();
177 Logger::notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]);
181 if (!strstr($xml, '<')) {
182 Logger::notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]);
186 Logger::notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]);
188 return !empty(Feed::import($xml, $importer, $contact));
194 * @param array $contact The personal contact entry
195 * @param integer $importer_uid The UID of the importer
196 * @param string $updated The updated date
198 * @return bool Success
201 private static function pollMail(array $contact, int $importer_uid, string $updated): bool
203 Logger::info('Fetching mails', ['addr' => $contact['addr']]);
205 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
206 if ($mail_disabled) {
207 Logger::notice('Mail is disabled');
211 Logger::info('Mail is enabled');
214 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
216 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
217 $mailconf = DBA::selectFirst('mailacct', [], $condition);
218 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
219 $mailbox = Email::constructMailboxName($mailconf);
221 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
222 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
224 Logger::notice('Connect', ['user' => $mailconf['user']]);
226 $fields = ['last_check' => $updated];
227 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
228 Logger::notice('Connected', ['user' => $mailconf['user']]);
230 Logger::notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]);
239 $msgs = Email::poll($mbox, $contact['addr']);
242 Logger::info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]);
244 $metas = Email::messageMeta($mbox, implode(',', $msgs));
246 if (count($metas) != count($msgs)) {
247 Logger::info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas");
249 $msgs = array_combine($msgs, $metas);
251 foreach ($msgs as $msg_uid => $meta) {
252 Logger::info('Parsing mail', ['message-uid' => $msg_uid]);
255 'uid' => $importer_uid,
256 'contact-id' => $contact['id'],
257 'verb' => Activity::POST,
258 'object-type' => Activity\ObjectType::NOTE,
259 'network' => Protocol::MAIL,
260 'protocol' => Conversation::PARCEL_IMAP,
261 'direction' => Conversation::PULL,
263 $datarray['thr-parent'] = $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
265 // $meta = Email::messageMeta($mbox, $msg_uid);
267 // Have we seen it before?
268 $fields = ['deleted', 'id'];
269 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
270 $item = Post::selectFirst($fields, $condition);
271 if (DBA::isResult($item)) {
272 Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . ' UID: ' . $importer_uid . ' URI: ' . $datarray['uri']);
274 // Only delete when mails aren't automatically moved or deleted
275 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
276 if ($meta->deleted && ! $item['deleted']) {
277 $fields = ['deleted' => true, 'changed' => $updated];
278 Item::update($fields, ['id' => $item['id']]);
281 switch ($mailconf['action']) {
283 Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.');
287 Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']);
288 imap_delete($mbox, $msg_uid, FT_UID);
292 Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']);
293 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
297 Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']);
298 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
299 if ($mailconf['movetofolder'] != '') {
300 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
307 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
308 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
309 if (!trim($raw_refs)) {
310 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
312 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
315 $refs_arr = explode(' ', $raw_refs);
316 if (count($refs_arr)) {
317 for ($x = 0; $x < count($refs_arr); $x ++) {
318 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
321 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
322 $parent = Post::selectFirst(['uri'], $condition);
323 if (DBA::isResult($parent)) {
324 $datarray['thr-parent'] = $parent['uri'];
328 // Decoding the header
329 $subject = imap_mime_header_decode($meta->subject ?? '');
330 $datarray['title'] = "";
331 foreach ($subject as $subpart) {
332 if ($subpart->charset != "default") {
333 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
335 $datarray['title'] .= $subpart->text;
338 $datarray['title'] = trim($datarray['title']);
340 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
341 $datarray['created'] = DateTimeFormat::utc($meta->date);
344 $reply = ((substr(strtolower($datarray['title']), 0, 3) == 're:') ||
345 (substr(strtolower($datarray['title']), 0, 3) == 're-') ||
348 // Remove Reply-signs in the subject
349 $datarray['title'] = self::removeReply($datarray['title']);
351 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
352 if (empty($datarray['thr-parent']) && $reply) {
353 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
354 $params = ['order' => ['created' => true]];
355 $parent = Post::selectFirst(['uri'], $condition, $params);
356 if (DBA::isResult($parent)) {
357 $datarray['thr-parent'] = $parent['uri'];
361 $headers = imap_headerinfo($mbox, $meta->msgno);
365 if (!empty($headers->from)) {
366 $object['from'] = $headers->from;
369 if (!empty($headers->to)) {
370 $object['to'] = $headers->to;
373 if (!empty($headers->reply_to)) {
374 $object['reply_to'] = $headers->reply_to;
377 if (!empty($headers->sender)) {
378 $object['sender'] = $headers->sender;
381 if (!empty($object)) {
382 $datarray['object'] = json_encode($object);
385 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
386 if (!empty($headers->from[0]->personal)) {
387 $fromname = $headers->from[0]->personal;
390 $datarray['author-name'] = $fromname;
391 $datarray['author-link'] = 'mailto:' . $frommail;
392 $datarray['author-avatar'] = $contact['photo'];
394 $datarray['owner-name'] = $contact['name'];
395 $datarray['owner-link'] = 'mailto:' . $contact['addr'];
396 $datarray['owner-avatar'] = $contact['photo'];
398 if (empty($datarray['thr-parent']) || ($datarray['thr-parent'] === $datarray['uri'])) {
399 $datarray['private'] = Item::PRIVATE;
402 if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
403 $datarray['private'] = Item::PRIVATE;
404 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
407 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
408 if (empty($datarray['body'])) {
409 Logger::warning('Cannot fetch mail', ['msg-id' => $msg_uid, 'uid' => $mailconf['user']]);
413 Logger::notice('Mail: Importing ' . $msg_uid . ' for ' . $mailconf['user']);
415 Item::insert($datarray);
417 switch ($mailconf['action']) {
419 Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.');
423 Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']);
424 imap_delete($mbox, $msg_uid, FT_UID);
428 Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']);
429 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
433 Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']);
434 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
435 if ($mailconf['movetofolder'] != '') {
436 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
443 Logger::notice('No mails', ['user' => $mailconf['user']]);
447 Logger::info('Closing connection', ['user' => $mailconf['user']]);
453 private static function removeReply(string $subject): string
455 while (in_array(strtolower(substr($subject, 0, 3)), ['re:', 'aw:'])) {
456 $subject = trim(substr($subject, 4));
464 * @param array $importer
465 * @param array $contact
466 * @param string $hubmode
468 * @return bool Success
469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
471 private static function subscribeToHub(string $url, array $importer, array $contact, string $hubmode = 'subscribe'): bool
473 $push_url = DI::baseUrl() . '/pubsub/' . $importer['nick'] . '/' . $contact['id'];
475 // Use a single verify token, even if multiple hubs
476 $verify_token = $contact['hub-verify'] ?: Strings::getRandomHex();
478 $params = 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
480 Logger::info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]);
482 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
483 Contact::update(['hub-verify' => $verify_token], ['id' => $contact['id']]);
486 $postResult = DI::httpClient()->post($url, $params);
488 Logger::info('Hub subscription done', ['result' => $postResult->getReturnCode()]);
490 return $postResult->isSuccess();