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