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