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\Item;
31 use Friendica\Model\Post;
32 use Friendica\Model\User;
33 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Protocol\Email;
38 use Friendica\Protocol\Feed;
39 use Friendica\Util\DateTimeFormat;
40 use Friendica\Util\Strings;
44 public static function execute($contact_id = 0, $command = '')
46 Logger::notice('Start polling/probing contact', ['id' => $contact_id]);
48 $force = ($command == "force");
50 if (empty($contact_id)) {
51 Logger::notice('no contact provided');
55 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
56 if (!DBA::isResult($contact)) {
57 Logger::warning('Contact not found', ['id' => $contact_id]);
61 // We never probe mail contacts since their probing demands a mail from the contact in the inbox.
62 // We don't probe feed accounts by default since they are polled in a higher frequency, but forced probes are okay.
63 if ($force && ($contact['network'] == Protocol::FEED)) {
64 $success = Contact::updateFromProbe($contact_id);
69 $importer_uid = $contact['uid'];
71 $updated = DateTimeFormat::utcNow();
73 // Possibly switch the remote contact to AP
74 if ($success && ($contact['network'] === Protocol::OSTATUS)) {
75 ActivityPub\Receiver::switchContact($contact['id'], $importer_uid, $contact['url']);
78 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
80 if ($success && ($importer_uid != 0) && in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])
81 && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
82 $importer = User::getOwnerDataById($importer_uid);
83 if (empty($importer)) {
84 Logger::warning('No self contact for user', ['uid' => $importer_uid]);
86 // set the last-update so we don't keep polling
87 Contact::update(['last-update' => $updated], ['id' => $contact['id']]);
91 Logger::info('Start polling/subscribing', ['protocol' => $contact['network'], 'id' => $contact['id']]);
92 if ($contact['network'] === Protocol::FEED) {
93 $success = self::pollFeed($contact, $importer);
94 } elseif ($contact['network'] === Protocol::MAIL) {
95 $success = self::pollMail($contact, $importer_uid, $updated);
97 $success = self::subscribeToHub($contact['url'], $importer, $contact, $contact['blocked'] ? 'unsubscribe' : 'subscribe');
100 Logger::notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]);
105 self::updateContact($contact, ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
106 Contact::unmarkForArchival($contact);
108 self::updateContact($contact, ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
109 Contact::markForArchival($contact);
112 Logger::notice('End');
117 * Updates a personal contact entry and the public contact entry
119 * @param array $contact The personal contact entry
120 * @param array $fields The fields that are updated
123 private static function updateContact(array $contact, array $fields)
125 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL, Protocol::OSTATUS])) {
126 // Update the user's contact
127 Contact::update($fields, ['id' => $contact['id']]);
129 // Update the public contact
130 Contact::update($fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
132 // Update the rest of the contacts that aren't polled
133 Contact::update($fields, ['rel' => Contact::FOLLOWER, 'nurl' => $contact['nurl']]);
135 // Update all contacts
136 Contact::update($fields, ['nurl' => $contact['nurl']]);
143 * @param array $contact The personal contact entry
144 * @param array $importer
146 * @return bool Success
149 private static function pollFeed(array $contact, $importer)
151 // Are we allowed to import from this person?
152 if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) {
153 Logger::notice('Contact is blocked or only a follower');
157 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-onepoll-');
158 $curlResult = DI::httpClient()->get($contact['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::COOKIEJAR => $cookiejar]);
161 if ($curlResult->isTimeout()) {
162 Logger::notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]);
166 $xml = $curlResult->getBody();
168 Logger::notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]);
172 if (!strstr($xml, '<')) {
173 Logger::notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]);
177 Logger::notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]);
179 return !empty(Feed::import($xml, $importer, $contact));
185 * @param array $contact The personal contact entry
186 * @param integer $importer_uid The UID of the importer
187 * @param string $updated The updated date
190 private static function pollMail(array $contact, $importer_uid, $updated)
192 Logger::info('Fetching mails', ['addr' => $contact['addr']]);
194 $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1);
195 if ($mail_disabled) {
196 Logger::notice('Mail is disabled');
200 Logger::info('Mail is enabled');
203 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
205 $condition = ["`server` != '' AND `uid` = ?", $importer_uid];
206 $mailconf = DBA::selectFirst('mailacct', [], $condition);
207 if (DBA::isResult($user) && DBA::isResult($mailconf)) {
208 $mailbox = Email::constructMailboxName($mailconf);
210 openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
211 $mbox = Email::connect($mailbox, $mailconf['user'], $password);
213 Logger::notice('Connect', ['user' => $mailconf['user']]);
215 $fields = ['last_check' => $updated];
216 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
217 Logger::notice('Connected', ['user' => $mailconf['user']]);
219 Logger::notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]);
228 $msgs = Email::poll($mbox, $contact['addr']);
231 Logger::info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]);
233 $metas = Email::messageMeta($mbox, implode(',', $msgs));
235 if (count($metas) != count($msgs)) {
236 Logger::info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas");
238 $msgs = array_combine($msgs, $metas);
240 foreach ($msgs as $msg_uid => $meta) {
241 Logger::info('Parsing mail', ['message-uid' => $msg_uid]);
244 $datarray['uid'] = $importer_uid;
245 $datarray['contact-id'] = $contact['id'];
246 $datarray['verb'] = Activity::POST;
247 $datarray['object-type'] = Activity\ObjectType::NOTE;
248 $datarray['network'] = Protocol::MAIL;
249 // $meta = Email::messageMeta($mbox, $msg_uid);
251 $datarray['thr-parent'] = $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
253 // Have we seen it before?
254 $fields = ['deleted', 'id'];
255 $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']];
256 $item = Post::selectFirst($fields, $condition);
257 if (DBA::isResult($item)) {
258 Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user']." UID: ".$importer_uid." URI: ".$datarray['uri']);
260 // Only delete when mails aren't automatically moved or deleted
261 if (($mailconf['action'] != 1) && ($mailconf['action'] != 3))
262 if ($meta->deleted && ! $item['deleted']) {
263 $fields = ['deleted' => true, 'changed' => $updated];
264 Item::update($fields, ['id' => $item['id']]);
267 switch ($mailconf['action']) {
269 Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.");
272 Logger::notice("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
273 imap_delete($mbox, $msg_uid, FT_UID);
276 Logger::notice("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
277 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
280 Logger::notice("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
281 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
282 if ($mailconf['movetofolder'] != "") {
283 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
290 // look for a 'references' or an 'in-reply-to' header and try to match with a parent item we have locally.
291 $raw_refs = (property_exists($meta, 'references') ? str_replace("\t", '', $meta->references) : '');
292 if (!trim($raw_refs)) {
293 $raw_refs = (property_exists($meta, 'in_reply_to') ? str_replace("\t", '', $meta->in_reply_to) : '');
295 $raw_refs = trim($raw_refs); // Don't allow a blank reference in $refs_arr
298 $refs_arr = explode(' ', $raw_refs);
299 if (count($refs_arr)) {
300 for ($x = 0; $x < count($refs_arr); $x ++) {
301 $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x]));
304 $condition = ['uri' => $refs_arr, 'uid' => $importer_uid];
305 $parent = Post::selectFirst(['uri'], $condition);
306 if (DBA::isResult($parent)) {
307 $datarray['thr-parent'] = $parent['uri'];
311 // Decoding the header
312 $subject = imap_mime_header_decode($meta->subject ?? '');
313 $datarray['title'] = "";
314 foreach ($subject as $subpart) {
315 if ($subpart->charset != "default") {
316 $datarray['title'] .= iconv($subpart->charset, 'UTF-8//IGNORE', $subpart->text);
318 $datarray['title'] .= $subpart->text;
321 $datarray['title'] = trim($datarray['title']);
323 //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
324 $datarray['created'] = DateTimeFormat::utc($meta->date);
327 $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
328 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
331 // Remove Reply-signs in the subject
332 $datarray['title'] = self::RemoveReply($datarray['title']);
334 // If it seems to be a reply but a header couldn't be found take the last message with matching subject
335 if (empty($datarray['thr-parent']) && $reply) {
336 $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL];
337 $params = ['order' => ['created' => true]];
338 $parent = Post::selectFirst(['uri'], $condition, $params);
339 if (DBA::isResult($parent)) {
340 $datarray['thr-parent'] = $parent['uri'];
344 $headers = imap_headerinfo($mbox, $meta->msgno);
348 if (!empty($headers->from)) {
349 $object['from'] = $headers->from;
352 if (!empty($headers->to)) {
353 $object['to'] = $headers->to;
356 if (!empty($headers->reply_to)) {
357 $object['reply_to'] = $headers->reply_to;
360 if (!empty($headers->sender)) {
361 $object['sender'] = $headers->sender;
364 if (!empty($object)) {
365 $datarray['object'] = json_encode($object);
368 $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
369 if (!empty($headers->from[0]->personal)) {
370 $fromname = $headers->from[0]->personal;
373 $datarray['author-name'] = $fromname;
374 $datarray['author-link'] = "mailto:".$frommail;
375 $datarray['author-avatar'] = $contact['photo'];
377 $datarray['owner-name'] = $contact['name'];
378 $datarray['owner-link'] = "mailto:".$contact['addr'];
379 $datarray['owner-avatar'] = $contact['photo'];
381 if (empty($datarray['thr-parent']) || ($datarray['thr-parent'] === $datarray['uri'])) {
382 $datarray['private'] = Item::PRIVATE;
385 if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
386 $datarray['private'] = Item::PRIVATE;
387 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
390 $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray);
391 if (empty($datarray['body'])) {
392 Logger::notice("Mail: can't fetch msg ".$msg_uid." for ".$mailconf['user']);
396 Logger::notice("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
398 Item::insert($datarray);
400 switch ($mailconf['action']) {
402 Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.");
405 Logger::notice("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
406 imap_delete($mbox, $msg_uid, FT_UID);
409 Logger::notice("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
410 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
413 Logger::notice("Mail: Moving ".$msg_uid." to ".$mailconf['movetofolder']." for ".$mailconf['user']);
414 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
415 if ($mailconf['movetofolder'] != "") {
416 imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID);
423 Logger::notice('No mails', ['user' => $mailconf['user']]);
427 Logger::info('Closing connection', ['user' => $mailconf['user']]);
433 private static function RemoveReply($subject)
435 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
436 $subject = trim(substr($subject, 4));
444 * @param array $importer
445 * @param array $contact
446 * @param string $hubmode
447 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
449 private static function subscribeToHub(string $url, array $importer, array $contact, string $hubmode = 'subscribe')
451 $push_url = DI::baseUrl() . '/pubsub/' . $importer['nick'] . '/' . $contact['id'];
453 // Use a single verify token, even if multiple hubs
454 $verify_token = $contact['hub-verify'] ?: Strings::getRandomHex();
456 $params = 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
458 Logger::info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]);
460 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
461 Contact::update(['hub-verify' => $verify_token], ['id' => $contact['id']]);
464 $postResult = DI::httpClient()->post($url, $params);
466 Logger::info('Hub subscription done', ['result' => $postResult->getReturnCode()]);
468 return $postResult->isSuccess();