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