3 * @copyright Copyright (C) 2010-2022, 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\Strings;
45 public static function execute(int $contact_id = 0, string $command = '')
47 Logger::notice('Start polling/probing contact', ['id' => $contact_id]);
49 $force = ($command == 'force');
51 if (empty($contact_id)) {
52 Logger::notice('no contact provided');
56 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
57 if (!DBA::isResult($contact)) {
58 Logger::warning('Contact not found', ['id' => $contact_id]);
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);
70 $importer_uid = $contact['uid'];
72 $updated = DateTimeFormat::utcNow();
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']);
79 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
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]);
87 // set the last-update so we don't keep polling
88 Contact::update(['last-update' => $updated], ['id' => $contact['id']]);
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);
98 $success = self::subscribeToHub($contact['url'], $importer, $contact, $contact['blocked'] ? 'unsubscribe' : 'subscribe');
101 Logger::notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]);
106 self::updateContact($contact, ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
107 Contact::unmarkForArchival($contact);
109 self::updateContact($contact, ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
110 Contact::markForArchival($contact);
113 Logger::notice('End');
118 * Updates a personal contact entry and the public contact entry
120 * @param array $contact The personal contact entry
121 * @param array $fields The fields that are updated
125 private static function updateContact(array $contact, array $fields)
127 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
128 // Update the user's contact
129 Contact::update($fields, ['id' => $contact['id']]);
131 // Update the public contact
132 Contact::update($fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
134 // Update the rest of the contacts that aren't polled
135 Contact::update($fields, ['rel' => Contact::FOLLOWER, 'nurl' => $contact['nurl']]);
137 // Update all contacts
138 Contact::update($fields, ['nurl' => $contact['nurl']]);
145 * @param array $contact The personal contact entry
146 * @param array $importer
148 * @return bool Success
151 private static function pollFeed(array $contact, $importer)
153 // Are we allowed to import from this person?
154 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
155 Logger::notice('Contact is blocked or only a follower');
159 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-onepoll-');
160 $curlResult = DI::httpClient()->get($contact['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::COOKIEJAR => $cookiejar]);
163 if ($curlResult->isTimeout()) {
164 Logger::notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]);
168 $xml = $curlResult->getBody();
170 Logger::notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]);
174 if (!strstr($xml, '<')) {
175 Logger::notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]);
179 Logger::notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]);
181 return !empty(Feed::import($xml, $importer, $contact));
187 * @param array $contact The personal contact entry
188 * @param integer $importer_uid The UID of the importer
189 * @param string $updated The updated date
192 private static function pollMail(array $contact, $importer_uid, $updated)
194 Logger::info('Fetching mails', ['addr' => $contact['addr']]);
196 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
197 if ($mail_disabled) {
198 Logger::notice('Mail is disabled');
202 Logger::info('Mail is enabled');
205 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
207 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
208 $mailconf = DBA::selectFirst('mailacct', [], $condition);
209 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
210 $mailbox = Email::constructMailboxName($mailconf);
212 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
213 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
215 Logger::notice('Connect', ['user' => $mailconf['user']]);
217 $fields = ['last_check' => $updated];
218 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
219 Logger::notice('Connected', ['user' => $mailconf['user']]);
221 Logger::notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]);
230 $msgs = Email::poll($mbox, $contact['addr']);
233 Logger::info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]);
235 $metas = Email::messageMeta($mbox, implode(',', $msgs));
237 if (count($metas) != count($msgs)) {
238 Logger::info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas");
240 $msgs = array_combine($msgs, $metas);
242 foreach ($msgs as $msg_uid => $meta) {
243 Logger::info('Parsing mail', ['message-uid' => $msg_uid]);
246 $datarray['uid'] = $importer_uid;
247 $datarray['contact-id'] = $contact['id'];
248 $datarray['verb'] = Activity::POST;
249 $datarray['object-type'] = Activity\ObjectType::NOTE;
250 $datarray['network'] = Protocol::MAIL;
251 $datarray['protocol'] = Conversation::PARCEL_IMAP;
252 $datarray['direction'] = Conversation::PULL;
254 // $meta = Email::messageMeta($mbox, $msg_uid);
256 $datarray['thr-parent'] = $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
258 // Have we seen it before?
259 $fields = ['deleted', 'id'];
260 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
261 $item = Post::selectFirst($fields, $condition);
262 if (DBA::isResult($item)) {
263 Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri']);
265 // Only delete when mails aren't automatically moved or deleted
266 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
267 if ($meta->deleted && ! $item['deleted']) {
268 $fields = ['deleted' => true, 'changed' => $updated];
269 Item::update($fields, ['id' => $item['id']]);
272 switch ($mailconf['action']) {
274 Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.");
277 Logger::notice("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
278 imap_delete($mbox, $msg_uid, FT_UID);
281 Logger::notice("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
282 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
285 Logger::notice("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
286 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
287 if ($mailconf['movetofolder'] != "") {
288 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
295 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
296 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
297 if (!trim($raw_refs)) {
298 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
300 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
303 $refs_arr = explode(' ', $raw_refs);
304 if (count($refs_arr)) {
305 for ($x = 0; $x < count($refs_arr); $x ++) {
306 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
309 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
310 $parent = Post::selectFirst(['uri'], $condition);
311 if (DBA::isResult($parent)) {
312 $datarray['thr-parent'] = $parent['uri'];
316 // Decoding the header
317 $subject = imap_mime_header_decode($meta->subject ?? '');
318 $datarray['title'] = "";
319 foreach ($subject as $subpart) {
320 if ($subpart->charset != "default") {
321 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
323 $datarray['title'] .= $subpart->text;
326 $datarray['title'] = trim($datarray['title']);
328 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
329 $datarray['created'] = DateTimeFormat::utc($meta->date);
332 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
333 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
336 // Remove Reply-signs in the subject
337 $datarray['title'] = self::RemoveReply($datarray['title']);
339 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
340 if (empty($datarray['thr-parent']) && $reply) {
341 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
342 $params = ['order' => ['created' => true]];
343 $parent = Post::selectFirst(['uri'], $condition, $params);
344 if (DBA::isResult($parent)) {
345 $datarray['thr-parent'] = $parent['uri'];
349 $headers = imap_headerinfo($mbox, $meta->msgno);
353 if (!empty($headers->from)) {
354 $object['from'] = $headers->from;
357 if (!empty($headers->to)) {
358 $object['to'] = $headers->to;
361 if (!empty($headers->reply_to)) {
362 $object['reply_to'] = $headers->reply_to;
365 if (!empty($headers->sender)) {
366 $object['sender'] = $headers->sender;
369 if (!empty($object)) {
370 $datarray['object'] = json_encode($object);
373 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
374 if (!empty($headers->from[0]->personal)) {
375 $fromname = $headers->from[0]->personal;
378 $datarray['author-name'] = $fromname;
379 $datarray['author-link'] = "mailto:".$frommail;
380 $datarray['author-avatar'] = $contact['photo'];
382 $datarray['owner-name'] = $contact['name'];
383 $datarray['owner-link'] = "mailto:".$contact['addr'];
384 $datarray['owner-avatar'] = $contact['photo'];
386 if (empty($datarray['thr-parent']) || ($datarray['thr-parent'] === $datarray['uri'])) {
387 $datarray['private'] = Item::PRIVATE;
390 if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
391 $datarray['private'] = Item::PRIVATE;
392 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
395 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
396 if (empty($datarray['body'])) {
397 Logger::notice("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
401 Logger::notice("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
403 Item::insert($datarray);
405 switch ($mailconf['action']) {
407 Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.");
410 Logger::notice("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
411 imap_delete($mbox, $msg_uid, FT_UID);
414 Logger::notice("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
415 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
418 Logger::notice("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
419 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
420 if ($mailconf['movetofolder'] != "") {
421 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
428 Logger::notice('No mails', ['user' => $mailconf['user']]);
432 Logger::info('Closing connection', ['user' => $mailconf['user']]);
438 private static function RemoveReply($subject)
440 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
441 $subject = trim(substr($subject, 4));
449 * @param array $importer
450 * @param array $contact
451 * @param string $hubmode
452 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
454 private static function subscribeToHub(string $url, array $importer, array $contact, string $hubmode = 'subscribe')
456 $push_url = DI::baseUrl() . '/pubsub/' . $importer['nick'] . '/' . $contact['id'];
458 // Use a single verify token, even if multiple hubs
459 $verify_token = $contact['hub-verify'] ?: Strings::getRandomHex();
461 $params = 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
463 Logger::info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]);
465 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
466 Contact::update(['hub-verify' => $verify_token], ['id' => $contact['id']]);
469 $postResult = DI::httpClient()->post($url, $params);
471 Logger::info('Hub subscription done', ['result' => $postResult->getReturnCode()]);
473 return $postResult->isSuccess();