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