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