]> git.mxchange.org Git - friendica.git/blob - src/Worker/OnePoll.php
Merge pull request #11503 from annando/bulk-delivery
[friendica.git] / src / Worker / OnePoll.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\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;
41
42 class OnePoll
43 {
44         public static function execute($contact_id = 0, $command = '')
45         {
46                 Logger::notice('Start polling/probing contact', ['id' => $contact_id]);
47
48                 $force = ($command == "force");
49
50                 if (empty($contact_id)) {
51                         Logger::notice('no contact provided');
52                         return;
53                 }
54
55                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
56                 if (!DBA::isResult($contact)) {
57                         Logger::warning('Contact not found', ['id' => $contact_id]);
58                         return;
59                 }
60
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);
65                 } else {
66                         $success = true;
67                 }
68
69                 $importer_uid = $contact['uid'];
70
71                 $updated = DateTimeFormat::utcNow();
72
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']);
76                 }
77
78                 $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]);
79
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]);
85
86                                 // set the last-update so we don't keep polling
87                                 Contact::update(['last-update' => $updated], ['id' => $contact['id']]);
88                                 return;
89                         }
90
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);
96                         } else {
97                                 $success = self::subscribeToHub($contact['url'], $importer, $contact, $contact['blocked'] ? 'unsubscribe' : 'subscribe');
98                         }
99                         if (!$success) {
100                                 Logger::notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]);
101                         }
102                 }
103
104                 if ($success) {
105                         self::updateContact($contact, ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
106                         Contact::unmarkForArchival($contact);
107                 } else {
108                         self::updateContact($contact, ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
109                         Contact::markForArchival($contact);
110                 }
111
112                 Logger::notice('End');
113                 return;
114         }
115
116         /**
117          * Updates a personal contact entry and the public contact entry
118          *
119          * @param array $contact The personal contact entry
120          * @param array $fields  The fields that are updated
121          * @throws \Exception
122          */
123         private static function updateContact(array $contact, array $fields)
124         {
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']]);
128
129                         // Update the public contact
130                         Contact::update($fields, ['uid' => 0, 'nurl' => $contact['nurl']]);
131
132                         // Update the rest of the contacts that aren't polled
133                         Contact::update($fields, ['rel' => Contact::FOLLOWER, 'nurl' => $contact['nurl']]);
134                 } else {
135                         // Update all contacts
136                         Contact::update($fields, ['nurl' => $contact['nurl']]);
137                 }
138         }
139
140         /**
141          * Poll Feed contacts
142          *
143          * @param  array $contact The personal contact entry
144          * @param  array $importer
145          *
146          * @return bool   Success
147          * @throws \Exception
148          */
149         private static function pollFeed(array $contact, $importer)
150         {
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');
154                         return false;
155                 }
156
157                 $cookiejar = tempnam(System::getTempPath(), 'cookiejar-onepoll-');
158                 $curlResult = DI::httpClient()->get($contact['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::COOKIEJAR => $cookiejar]);
159                 unlink($cookiejar);
160
161                 if ($curlResult->isTimeout()) {
162                         Logger::notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]);
163                         return false;
164                 }
165
166                 $xml = $curlResult->getBody();
167                 if (empty($xml)) {
168                         Logger::notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]);
169                         return false;
170                 }
171
172                 if (!strstr($xml, '<')) {
173                         Logger::notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]);
174                         return false;
175                 }
176
177                 Logger::notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]);
178
179                 return !empty(Feed::import($xml, $importer, $contact));
180         }
181
182         /**
183          * Poll Mail contacts
184          *
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
188          * @throws \Exception
189          */
190         private static function pollMail(array $contact, $importer_uid, $updated)
191         {
192                 Logger::info('Fetching mails', ['addr' => $contact['addr']]);
193
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');
197                         return false;
198                 }
199
200                 Logger::info('Mail is enabled');
201
202                 $mbox = null;
203                 $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]);
204
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);
209                         $password = '';
210                         openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']);
211                         $mbox = Email::connect($mailbox, $mailconf['user'], $password);
212                         unset($password);
213                         Logger::notice('Connect', ['user' => $mailconf['user']]);
214                         if ($mbox) {
215                                 $fields = ['last_check' => $updated];
216                                 DBA::update('mailacct', $fields, ['id' => $mailconf['id']]);
217                                 Logger::notice('Connected', ['user' => $mailconf['user']]);
218                         } else {
219                                 Logger::notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]);
220                                 return false;
221                         }
222                 }
223
224                 if (empty($mbox)) {
225                         return false;
226                 }
227
228                 $msgs = Email::poll($mbox, $contact['addr']);
229
230                 if (count($msgs)) {
231                         Logger::info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]);
232
233                         $metas = Email::messageMeta($mbox, implode(',', $msgs));
234
235                         if (count($metas) != count($msgs)) {
236                                 Logger::info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas");
237                         } else {
238                                 $msgs = array_combine($msgs, $metas);
239
240                                 foreach ($msgs as $msg_uid => $meta) {
241                                         Logger::info('Parsing mail', ['message-uid' => $msg_uid]);
242
243                                         $datarray = [];
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);
250
251                                         $datarray['thr-parent'] = $datarray['uri'] = Email::msgid2iri(trim($meta->message_id, '<>'));
252
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']);
259
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']]);
265                                                         }
266
267                                                 switch ($mailconf['action']) {
268                                                         case 0:
269                                                                 Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.");
270                                                                 break;
271                                                         case 1:
272                                                                 Logger::notice("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
273                                                                 imap_delete($mbox, $msg_uid, FT_UID);
274                                                                 break;
275                                                         case 2:
276                                                                 Logger::notice("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
277                                                                 imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
278                                                                 break;
279                                                         case 3:
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);
284                                                                 }
285                                                                 break;
286                                                 }
287                                                 continue;
288                                         }
289
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) : '');
294                                         }
295                                         $raw_refs = trim($raw_refs);  // Don't allow a blank reference in $refs_arr
296
297                                         if ($raw_refs) {
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]));
302                                                         }
303                                                 }
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'];
308                                                 }
309                                         }
310
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);
317                                                 } else {
318                                                         $datarray['title'] .= $subpart->text;
319                                                 }
320                                         }
321                                         $datarray['title'] = trim($datarray['title']);
322
323                                         //$datarray['title'] = Strings::escapeTags(trim($meta->subject));
324                                         $datarray['created'] = DateTimeFormat::utc($meta->date);
325
326                                         // Is it a reply?
327                                         $reply = ((substr(strtolower($datarray['title']), 0, 3) == "re:") ||
328                                                 (substr(strtolower($datarray['title']), 0, 3) == "re-") ||
329                                                 ($raw_refs != ""));
330
331                                         // Remove Reply-signs in the subject
332                                         $datarray['title'] = self::RemoveReply($datarray['title']);
333
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'];
341                                                 }
342                                         }
343
344                                         $headers = imap_headerinfo($mbox, $meta->msgno);
345
346                                         $object = [];
347
348                                         if (!empty($headers->from)) {
349                                                 $object['from'] = $headers->from;
350                                         }
351
352                                         if (!empty($headers->to)) {
353                                                 $object['to'] = $headers->to;
354                                         }
355
356                                         if (!empty($headers->reply_to)) {
357                                                 $object['reply_to'] = $headers->reply_to;
358                                         }
359
360                                         if (!empty($headers->sender)) {
361                                                 $object['sender'] = $headers->sender;
362                                         }
363
364                                         if (!empty($object)) {
365                                                 $datarray['object'] = json_encode($object);
366                                         }
367
368                                         $fromname = $frommail = $headers->from[0]->mailbox . '@' . $headers->from[0]->host;
369                                         if (!empty($headers->from[0]->personal)) {
370                                                 $fromname = $headers->from[0]->personal;
371                                         }
372
373                                         $datarray['author-name'] = $fromname;
374                                         $datarray['author-link'] = "mailto:".$frommail;
375                                         $datarray['author-avatar'] = $contact['photo'];
376
377                                         $datarray['owner-name'] = $contact['name'];
378                                         $datarray['owner-link'] = "mailto:".$contact['addr'];
379                                         $datarray['owner-avatar'] = $contact['photo'];
380
381                                         if (empty($datarray['thr-parent']) || ($datarray['thr-parent'] === $datarray['uri'])) {
382                                                 $datarray['private'] = Item::PRIVATE;
383                                         }
384
385                                         if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) {
386                                                 $datarray['private'] = Item::PRIVATE;
387                                                 $datarray['allow_cid'] = '<' . $contact['id'] . '>';
388                                         }
389
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']);
393                                                 continue;
394                                         }
395
396                                         Logger::notice("Mail: Importing ".$msg_uid." for ".$mailconf['user']);
397
398                                         Item::insert($datarray);
399
400                                         switch ($mailconf['action']) {
401                                                 case 0:
402                                                         Logger::info("Mail: Seen before ".$msg_uid." for ".$mailconf['user'].". Doing nothing.");
403                                                         break;
404                                                 case 1:
405                                                         Logger::notice("Mail: Deleting ".$msg_uid." for ".$mailconf['user']);
406                                                         imap_delete($mbox, $msg_uid, FT_UID);
407                                                         break;
408                                                 case 2:
409                                                         Logger::notice("Mail: Mark as seen ".$msg_uid." for ".$mailconf['user']);
410                                                         imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID);
411                                                         break;
412                                                 case 3:
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);
417                                                         }
418                                                         break;
419                                         }
420                                 }
421                         }
422                 } else {
423                         Logger::notice('No mails', ['user' => $mailconf['user']]);
424                 }
425
426
427                 Logger::info('Closing connection', ['user' => $mailconf['user']]);
428                 imap_close($mbox);
429
430                 return true;
431         }
432
433         private static function RemoveReply($subject)
434         {
435                 while (in_array(strtolower(substr($subject, 0, 3)), ["re:", "aw:"])) {
436                         $subject = trim(substr($subject, 4));
437                 }
438
439                 return $subject;
440         }
441
442         /**
443          * @param string $url
444          * @param array  $importer
445          * @param array  $contact
446          * @param string $hubmode
447          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
448          */
449         private static function subscribeToHub(string $url, array $importer, array $contact, string $hubmode = 'subscribe')
450         {
451                 $push_url = DI::baseUrl() . '/pubsub/' . $importer['nick'] . '/' . $contact['id'];
452
453                 // Use a single verify token, even if multiple hubs
454                 $verify_token = $contact['hub-verify'] ?: Strings::getRandomHex();
455
456                 $params = 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
457
458                 Logger::info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]);
459
460                 if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
461                         Contact::update(['hub-verify' => $verify_token], ['id' => $contact['id']]);
462                 }
463
464                 $postResult = DI::httpClient()->post($url, $params);
465
466                 Logger::info('Hub subscription done', ['result' => $postResult->getReturnCode()]);
467
468                 return $postResult->isSuccess();
469         }
470 }