]> git.mxchange.org Git - friendica.git/blob - src/Core/Protocol.php
Merge pull request #11015 from MrPetovan/task/10979-frio-time-tooltip
[friendica.git] / src / Core / Protocol.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\Core;
23
24 use Friendica\Database\DBA;
25 use Friendica\DI;
26 use Friendica\Model\User;
27 use Friendica\Network\HTTPException;
28 use Friendica\Protocol\Activity;
29 use Friendica\Protocol\ActivityPub;
30 use Friendica\Protocol\Diaspora;
31 use Friendica\Protocol\OStatus;
32 use Friendica\Protocol\Salmon;
33
34 /**
35  * Manage compatibility with federated networks
36  */
37 class Protocol
38 {
39         // Native support
40         const ACTIVITYPUB = 'apub';    // ActivityPub (Pleroma, Mastodon, Osada, ...)
41         const DFRN        = 'dfrn';    // Friendica, Mistpark, other DFRN implementations
42         const DIASPORA    = 'dspr';    // Diaspora, Hubzilla, Socialhome, Ganggo
43         const FEED        = 'feed';    // RSS/Atom feeds with no known "post/notify" protocol
44         const MAIL        = 'mail';    // IMAP/POP
45         const OSTATUS     = 'stat';    // GNU Social and other OStatus implementations
46
47         const NATIVE_SUPPORT = [self::DFRN, self::DIASPORA, self::OSTATUS, self::FEED, self::MAIL, self::ACTIVITYPUB];
48
49         const FEDERATED = [self::DFRN, self::DIASPORA, self::OSTATUS, self::ACTIVITYPUB];
50
51         const SUPPORT_PRIVATE = [self::DFRN, self::DIASPORA, self::MAIL, self::ACTIVITYPUB, self::PUMPIO];
52
53         // Supported through a connector
54         const DIASPORA2 = 'dspc';    // Diaspora connector
55         const LINKEDIN  = 'lnkd';    // LinkedIn
56         const PUMPIO    = 'pump';    // pump.io
57         const STATUSNET = 'stac';    // Statusnet connector
58         const TWITTER   = 'twit';    // Twitter
59         const DISCOURSE = 'dscs';    // Discourse
60
61         // Dead protocols
62         const APPNET    = 'apdn';    // app.net - Dead protocol
63         const FACEBOOK  = 'face';    // Facebook API - Not working anymore, API is closed
64         const GPLUS     = 'goog';    // Google+ - Dead in 2019
65
66         // Currently unsupported
67         const ICALENDAR = 'ical';    // iCalendar
68         const MYSPACE   = 'mysp';    // MySpace
69         const NEWS      = 'nntp';    // Network News Transfer Protocol
70         const PNUT      = 'pnut';    // pnut.io
71         const XMPP      = 'xmpp';    // XMPP
72         const ZOT       = 'zot!';    // Zot!
73
74         const PHANTOM   = 'unkn';    // Place holder
75
76         /**
77          * Returns whether the provided protocol supports following
78          *
79          * @param $protocol
80          * @return bool
81          * @throws HTTPException\InternalServerErrorException
82          */
83         public static function supportsFollow($protocol): bool
84         {
85                 if (in_array($protocol, self::NATIVE_SUPPORT)) {
86                         return true;
87                 }
88
89                 $hook_data = [
90                         'protocol' => $protocol,
91                         'result' => null
92                 ];
93                 Hook::callAll('support_follow', $hook_data);
94
95                 return $hook_data['result'] === true;
96         }
97
98         /**
99          * Returns whether the provided protocol supports revoking inbound follows
100          *
101          * @param $protocol
102          * @return bool
103          * @throws HTTPException\InternalServerErrorException
104          */
105         public static function supportsRevokeFollow($protocol): bool
106         {
107                 if (in_array($protocol, self::NATIVE_SUPPORT)) {
108                         return true;
109                 }
110
111                 $hook_data = [
112                         'protocol' => $protocol,
113                         'result' => null
114                 ];
115                 Hook::callAll('support_revoke_follow', $hook_data);
116
117                 return $hook_data['result'] === true;
118         }
119
120         /**
121          * Returns the address string for the provided profile URL
122          *
123          * @param string $profile_url
124          * @return string
125          * @throws \Exception
126          */
127         public static function getAddrFromProfileUrl($profile_url)
128         {
129                 $network = self::matchByProfileUrl($profile_url, $matches);
130
131                 if ($network === self::PHANTOM) {
132                         return "";
133                 }
134
135                 $addr = $matches[2] . '@' . $matches[1];
136
137                 return $addr;
138         }
139
140         /**
141          * Guesses the network from a profile URL
142          *
143          * @param string $profile_url
144          * @param array  $matches preg_match return array: [0] => Full match [1] => hostname [2] => username
145          * @return string
146          */
147         public static function matchByProfileUrl($profile_url, &$matches = [])
148         {
149                 if (preg_match('=https?://(twitter\.com)/(.*)=ism', $profile_url, $matches)) {
150                         return self::TWITTER;
151                 }
152
153                 if (preg_match('=https?://(alpha\.app\.net)/(.*)=ism', $profile_url, $matches)) {
154                         return self::APPNET;
155                 }
156
157                 if (preg_match('=https?://(plus\.google\.com)/(.*)=ism', $profile_url, $matches)) {
158                         return self::GPLUS;
159                 }
160
161                 if (preg_match('=https?://(.*)/profile/(.*)=ism', $profile_url, $matches)) {
162                         return self::DFRN;
163                 }
164
165                 if (preg_match('=https?://(.*)/u/(.*)=ism', $profile_url, $matches)) {
166                         return self::DIASPORA;
167                 }
168
169                 if (preg_match('=https?://(.*)/channel/(.*)=ism', $profile_url, $matches)) {
170                         // RedMatrix/Hubzilla is identified as Diaspora - friendica can't connect directly to it
171                         return self::DIASPORA;
172                 }
173
174                 if (preg_match('=https?://(.*)/user/(.*)=ism', $profile_url, $matches)) {
175                         $statusnet_host = $matches[1];
176                         $statusnet_user = $matches[2];
177                         $UserData = DI::httpClient()->fetch('http://' . $statusnet_host . '/api/users/show.json?user_id=' . $statusnet_user);
178                         $user = json_decode($UserData);
179                         if ($user) {
180                                 $matches[2] = $user->screen_name;
181                                 return self::STATUSNET;
182                         }
183                 }
184
185                 // Mastodon, Pleroma
186                 if (preg_match('=https?://(.+?)/users/(.+)=ism', $profile_url, $matches)
187                         || preg_match('=https?://(.+?)/@(.+)=ism', $profile_url, $matches)
188                 ) {
189                         return self::ACTIVITYPUB;
190                 }
191
192                 // pumpio (http://host.name/user)
193                 if (preg_match('=https?://([\.\w]+)/([\.\w]+)$=ism', $profile_url, $matches)) {
194                         return self::PUMPIO;
195                 }
196
197                 return self::PHANTOM;
198         }
199
200         /**
201          * Returns a formatted mention from a profile URL and a display name
202          *
203          * @param string $profile_url
204          * @param string $display_name
205          * @return string
206          * @throws \Exception
207          */
208         public static function formatMention($profile_url, $display_name)
209         {
210                 return $display_name . ' (' . self::getAddrFromProfileUrl($profile_url) . ')';
211         }
212
213         /**
214          * Send a follow message to a remote server.
215          *
216          * @param int     $uid      User Id
217          * @param array   $contact  Contact being followed
218          * @param ?string $protocol Expected protocol
219          * @return bool Only returns false in the unlikely case an ActivityPub contact ID doesn't exist (???)
220          * @throws HTTPException\InternalServerErrorException
221          * @throws \ImagickException
222          */
223         public static function follow(int $uid, array $contact, ?string $protocol = null): bool
224         {
225                 $owner = User::getOwnerDataById($uid);
226                 if (!DBA::isResult($owner)) {
227                         return true;
228                 }
229
230                 $protocol = $protocol ?? $contact['protocol'];
231
232                 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
233                         // create a follow slap
234                         $item = [
235                                 'verb'    => Activity::FOLLOW,
236                                 'gravity' => GRAVITY_ACTIVITY,
237                                 'follow'  => $contact['url'],
238                                 'body'    => '',
239                                 'title'   => '',
240                                 'guid'    => '',
241                                 'uri-id'  => 0,
242                         ];
243
244                         $slap = OStatus::salmon($item, $owner);
245
246                         if (!empty($contact['notify'])) {
247                                 Salmon::slapper($owner, $contact['notify'], $slap);
248                         }
249                 } elseif ($protocol == Protocol::DIASPORA) {
250                         $contact = Diaspora::sendShare($owner, $contact);
251                         Logger::notice('share returns: ' . $contact);
252                 } elseif ($protocol == Protocol::ACTIVITYPUB) {
253                         $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
254                         if (empty($activity_id)) {
255                                 // This really should never happen
256                                 return false;
257                         }
258
259                         $success = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $owner['uid'], $activity_id);
260                         Logger::notice('Follow returns: ' . $success);
261                 }
262
263                 return true;
264         }
265
266         /**
267          * Sends an unfriend message. Does not remove the contact
268          *
269          * @param array   $user    User unfriending
270          * @param array   $contact Contact unfriended
271          * @return bool|null true if successful, false if not, null if no remote action was performed
272          * @throws HTTPException\InternalServerErrorException
273          * @throws \ImagickException
274          */
275         public static function terminateFriendship(array $user, array $contact): ?bool
276         {
277                 if (empty($contact['network'])) {
278                         throw new \InvalidArgumentException('Missing network key in contact array');
279                 }
280
281                 $protocol = $contact['network'];
282                 if (($protocol == Protocol::DFRN) && !empty($contact['protocol'])) {
283                         $protocol = $contact['protocol'];
284                 }
285
286                 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
287                         // create an unfollow slap
288                         $item = [];
289                         $item['verb'] = Activity::O_UNFOLLOW;
290                         $item['gravity'] = GRAVITY_ACTIVITY;
291                         $item['follow'] = $contact['url'];
292                         $item['body'] = '';
293                         $item['title'] = '';
294                         $item['guid'] = '';
295                         $item['uri-id'] = 0;
296                         $slap = OStatus::salmon($item, $user);
297
298                         if (empty($contact['notify'])) {
299                                 throw new \InvalidArgumentException('Missing expected "notify" key in OStatus/DFRN contact');
300                         }
301
302                         return Salmon::slapper($user, $contact['notify'], $slap) === 0;
303                 } elseif ($protocol == Protocol::DIASPORA) {
304                         return Diaspora::sendUnshare($user, $contact) > 0;
305                 } elseif ($protocol == Protocol::ACTIVITYPUB) {
306                         return ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
307                 }
308
309                 // Catch-all hook for connector addons
310                 $hook_data = [
311                         'contact' => $contact,
312                         'result' => null
313                 ];
314                 Hook::callAll('unfollow', $hook_data);
315
316                 return $hook_data['result'];
317         }
318
319         /**
320          * Revoke an incoming follow from the provided contact
321          *
322          * @param array $contact Private contact (uid != 0) array
323          * @return bool|null true if successful, false if not, null if no action was performed
324          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
325          * @throws \ImagickException
326          */
327         public static function revokeFollow(array $contact): ?bool
328         {
329                 if (empty($contact['network'])) {
330                         throw new \InvalidArgumentException('Missing network key in contact array');
331                 }
332
333                 $protocol = $contact['network'];
334                 if ($protocol == Protocol::DFRN && !empty($contact['protocol'])) {
335                         $protocol = $contact['protocol'];
336                 }
337
338                 if ($protocol == Protocol::ACTIVITYPUB) {
339                         return ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $contact['uid']);
340                 }
341
342                 // Catch-all hook for connector addons
343                 $hook_data = [
344                         'contact' => $contact,
345                         'result' => null,
346                 ];
347                 Hook::callAll('revoke_follow', $hook_data);
348
349                 return $hook_data['result'];
350         }
351
352         /**
353          * Send a block message to a remote server. Only useful for connector addons.
354          *
355          * @param array $contact Public contact record to block
356          * @param int   $uid     User issuing the block
357          * @return bool|null true if successful, false if not, null if no action was performed
358          * @throws HTTPException\InternalServerErrorException
359          */
360         public static function block(array $contact, int $uid): ?bool
361         {
362                 // Catch-all hook for connector addons
363                 $hook_data = [
364                         'contact' => $contact,
365                         'uid' => $uid,
366                         'result' => null,
367                 ];
368                 Hook::callAll('block', $hook_data);
369
370                 return $hook_data['result'];
371         }
372
373         /**
374          * Send an unblock message to a remote server. Only useful for connector addons.
375          *
376          * @param array $contact Public contact record to unblock
377          * @param int   $uid     User revoking the block
378          * @return bool|null true if successful, false if not, null if no action was performed
379          * @throws HTTPException\InternalServerErrorException
380          */
381         public static function unblock(array $contact, int $uid): ?bool
382         {
383                 // Catch-all hook for connector addons
384                 $hook_data = [
385                         'contact' => $contact,
386                         'uid' => $uid,
387                         'result' => null,
388                 ];
389                 Hook::callAll('unblock', $hook_data);
390
391                 return $hook_data['result'];
392         }
393 }