]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
Merge pull request #8948 from annando/remove-gcontact
[friendica.git] / src / Model / GContact.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\Model;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Exception;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Search;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Network\Probe;
34 use Friendica\Protocol\ActivityPub;
35 use Friendica\Protocol\PortableContact;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Strings;
38
39 /**
40  * This class handles GlobalContact related functions
41  */
42 class GContact
43 {
44         /**
45          * Link the gcontact entry with user, contact and global contact
46          *
47          * @param integer $gcid Global contact ID
48          * @param integer $uid  User ID
49          * @param integer $cid  Contact ID
50          * @param integer $zcid Global Contact ID
51          * @return void
52          * @throws Exception
53          */
54         public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
55         {
56                 if ($gcid <= 0) {
57                         return;
58                 }
59
60                 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
61                 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
62         }
63
64         /**
65          * Sanitize the given gcontact data
66          *
67          * Generation:
68          *  0: No definition
69          *  1: Profiles on this server
70          *  2: Contacts of profiles on this server
71          *  3: Contacts of contacts of profiles on this server
72          *  4: ...
73          *
74          * @param array $gcontact array with gcontact data
75          * @return array $gcontact
76          * @throws Exception
77          */
78         public static function sanitize($gcontact)
79         {
80                 if (empty($gcontact['url'])) {
81                         throw new Exception('URL is empty');
82                 }
83
84                 $gcontact['server_url'] = $gcontact['server_url'] ?? '';
85
86                 $urlparts = parse_url($gcontact['url']);
87                 if (empty($urlparts['scheme'])) {
88                         throw new Exception('This (' . $gcontact['url'] . ") doesn't seem to be an url.");
89                 }
90
91                 if (in_array($urlparts['host'], ['twitter.com', 'identi.ca'])) {
92                         throw new Exception('Contact from a non federated network ignored. (' . $gcontact['url'] . ')');
93                 }
94
95                 // Don't store the statusnet connector as network
96                 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
97                 if ($gcontact['network'] == Protocol::STATUSNET) {
98                         $gcontact['network'] = '';
99                 }
100
101                 // Assure that there are no parameter fragments in the profile url
102                 if (empty($gcontact['*network']) || in_array($gcontact['network'], Protocol::FEDERATED)) {
103                         $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
104                 }
105
106                 // The global contacts should contain the original picture, not the cached one
107                 if (($gcontact['generation'] != 1) && stristr(Strings::normaliseLink($gcontact['photo']), Strings::normaliseLink(DI::baseUrl() . '/photo/'))) {
108                         $gcontact['photo'] = '';
109                 }
110
111                 if (empty($gcontact['network'])) {
112                         $gcontact['network'] = '';
113
114                         $condition = ["`uid` = 0 AND `nurl` = ? AND `network` != '' AND `network` != ?",
115                                 Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
116                         $contact = DBA::selectFirst('contact', ['network'], $condition);
117                         if (DBA::isResult($contact)) {
118                                 $gcontact['network'] = $contact['network'];
119                         }
120
121                         if (($gcontact['network'] == '') || ($gcontact['network'] == Protocol::OSTATUS)) {
122                                 $condition = ["`uid` = 0 AND `alias` IN (?, ?) AND `network` != '' AND `network` != ?",
123                                         $gcontact['url'], Strings::normaliseLink($gcontact['url']), Protocol::STATUSNET];
124                                 $contact = DBA::selectFirst('contact', ['network'], $condition);
125                                 if (DBA::isResult($contact)) {
126                                         $gcontact['network'] = $contact['network'];
127                                 }
128                         }
129                 }
130
131                 $fields = ['network', 'updated', 'server_url', 'url', 'addr'];
132                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($gcontact['url'])]);
133                 if (DBA::isResult($gcnt)) {
134                         if (!isset($gcontact['network']) && ($gcnt['network'] != Protocol::STATUSNET)) {
135                                 $gcontact['network'] = $gcnt['network'];
136                         }
137                         if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
138                                 $gcontact['updated'] = $gcnt['updated'];
139                         }
140                         if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt['server_url']) != Strings::normaliseLink($gcnt['url']))) {
141                                 $gcontact['server_url'] = $gcnt['server_url'];
142                         }
143                         if (!isset($gcontact['addr'])) {
144                                 $gcontact['addr'] = $gcnt['addr'];
145                         }
146                 }
147
148                 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']))
149                         && GServer::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
150                 ) {
151                         $data = Probe::uri($gcontact['url']);
152
153                         if ($data['network'] == Protocol::PHANTOM) {
154                                 throw new Exception('Probing for URL ' . $gcontact['url'] . ' failed');
155                         }
156
157                         $gcontact['server_url'] = $data['baseurl'];
158                         $gcontact['failed'] = false;
159
160                         $gcontact = array_merge($gcontact, $data);
161                 }
162
163                 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
164                         throw new Exception('No name and photo for URL '.$gcontact['url']);
165                 }
166
167                 if (!in_array($gcontact['network'], Protocol::FEDERATED)) {
168                         throw new Exception('No federated network (' . $gcontact['network'] . ') detected for URL ' . $gcontact['url']);
169                 }
170
171                 if (empty($gcontact['server_url'])) {
172                         // We check the server url to be sure that it is a real one
173                         $server_url = self::getBasepath($gcontact['url']);
174
175                         // We are now sure that it is a correct URL. So we use it in the future
176                         if ($server_url != '') {
177                                 $gcontact['server_url'] = $server_url;
178                         }
179                 }
180
181                 // The server URL doesn't seem to be valid, so we don't store it.
182                 if (!GServer::check($gcontact['server_url'], $gcontact['network'])) {
183                         $gcontact['server_url'] = '';
184                 }
185
186                 return $gcontact;
187         }
188
189         /**
190          * @param integer $uid id
191          * @param integer $cid id
192          * @return integer
193          * @throws Exception
194          */
195         public static function countCommonFriends($uid, $cid)
196         {
197                 $r = q(
198                         "SELECT count(*) as `total`
199                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
200                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
201                         NOT `gcontact`.`failed`
202                         AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d) ",
203                         intval($cid),
204                         intval($uid),
205                         intval($uid),
206                         intval($cid)
207                 );
208
209                 if (DBA::isResult($r)) {
210                         return $r[0]['total'];
211                 }
212                 return 0;
213         }
214
215         /**
216          * @param integer $uid  id
217          * @param integer $zcid zcid
218          * @return integer
219          * @throws Exception
220          */
221         public static function countCommonFriendsZcid($uid, $zcid)
222         {
223                 $r = q(
224                         "SELECT count(*) as `total`
225                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
226                         where `glink`.`zcid` = %d
227                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0) ",
228                         intval($zcid),
229                         intval($uid)
230                 );
231
232                 if (DBA::isResult($r)) {
233                         return $r[0]['total'];
234                 }
235
236                 return 0;
237         }
238
239         /**
240          * @param integer $uid     user
241          * @param integer $cid     cid
242          * @param integer $start   optional, default 0
243          * @param integer $limit   optional, default 9999
244          * @param boolean $shuffle optional, default false
245          * @return object
246          * @throws Exception
247          */
248         public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
249         {
250                 if ($shuffle) {
251                         $sql_extra = " order by rand() ";
252                 } else {
253                         $sql_extra = " order by `gcontact`.`name` asc ";
254                 }
255
256                 $r = q(
257                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
258                         FROM `glink`
259                         INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
260                         INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
261                         WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
262                                 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
263                                 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
264                                 AND NOT `gcontact`.`failed`
265                                 $sql_extra LIMIT %d, %d",
266                         intval($cid),
267                         intval($uid),
268                         intval($uid),
269                         intval($cid),
270                         intval($start),
271                         intval($limit)
272                 );
273
274                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
275                 return $r;
276         }
277
278         /**
279          * @param integer $uid     user
280          * @param integer $zcid    zcid
281          * @param integer $start   optional, default 0
282          * @param integer $limit   optional, default 9999
283          * @param boolean $shuffle optional, default false
284          * @return object
285          * @throws Exception
286          */
287         public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
288         {
289                 if ($shuffle) {
290                         $sql_extra = " order by rand() ";
291                 } else {
292                         $sql_extra = " order by `gcontact`.`name` asc ";
293                 }
294
295                 $r = q(
296                         "SELECT `gcontact`.*
297                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
298                         where `glink`.`zcid` = %d
299                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0)
300                         $sql_extra limit %d, %d",
301                         intval($zcid),
302                         intval($uid),
303                         intval($start),
304                         intval($limit)
305                 );
306
307                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
308                 return $r;
309         }
310
311         /**
312          * @param integer $uid user
313          * @param integer $cid cid
314          * @return integer
315          * @throws Exception
316          */
317         public static function countAllFriends($uid, $cid)
318         {
319                 $r = q(
320                         "SELECT count(*) as `total`
321                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
322                         where `glink`.`cid` = %d and `glink`.`uid` = %d AND
323                         NOT `gcontact`.`failed`",
324                         intval($cid),
325                         intval($uid)
326                 );
327
328                 if (DBA::isResult($r)) {
329                         return $r[0]['total'];
330                 }
331
332                 return 0;
333         }
334
335         /**
336          * @param integer $uid   user
337          * @param integer $cid   cid
338          * @param integer $start optional, default 0
339          * @param integer $limit optional, default 80
340          * @return array
341          * @throws Exception
342          */
343         public static function allFriends($uid, $cid, $start = 0, $limit = 80)
344         {
345                 $r = q(
346                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
347                         FROM `glink`
348                         INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
349                         LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
350                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
351                         NOT `gcontact`.`failed`
352                         ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
353                         intval($uid),
354                         intval($cid),
355                         intval($uid),
356                         intval($start),
357                         intval($limit)
358                 );
359
360                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
361                 return $r;
362         }
363
364         /**
365          * @return void
366          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
367          */
368         public static function updateSuggestions()
369         {
370                 $done = [];
371
372                 /// @TODO Check if it is really neccessary to poll the own server
373                 PortableContact::loadWorker(0, 0, 0, DI::baseUrl() . '/poco');
374
375                 $done[] = DI::baseUrl() . '/poco';
376
377                 if (strlen(DI::config()->get('system', 'directory'))) {
378                         $x = DI::httpRequest()->fetch(Search::getGlobalDirectory() . '/pubsites');
379                         if (!empty($x)) {
380                                 $j = json_decode($x);
381                                 if (!empty($j->entries)) {
382                                         foreach ($j->entries as $entry) {
383                                                 GServer::check($entry->url);
384
385                                                 $url = $entry->url . '/poco';
386                                                 if (!in_array($url, $done)) {
387                                                         PortableContact::loadWorker(0, 0, 0, $url);
388                                                         $done[] = $url;
389                                                 }
390                                         }
391                                 }
392                         }
393                 }
394
395                 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
396                 $contacts = DBA::p("SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN (?, ?)", Protocol::DFRN, Protocol::DIASPORA);
397                 while ($contact = DBA::fetch($contacts)) {
398                         $base = substr($contact['poco'], 0, strrpos($contact['poco'], '/'));
399                         if (!in_array($base, $done)) {
400                                 PortableContact::loadWorker(0, 0, 0, $base);
401                         }
402                 }
403                 DBA::close($contacts);
404         }
405
406         /**
407          * Removes unwanted parts from a contact url
408          *
409          * @param string $url Contact url
410          *
411          * @return string Contact url with the wanted parts
412          * @throws Exception
413          */
414         public static function cleanContactUrl($url)
415         {
416                 $parts = parse_url($url);
417
418                 if (empty($parts['scheme']) || empty($parts['host'])) {
419                         return $url;
420                 }
421
422                 $new_url = $parts['scheme'] . '://' . $parts['host'];
423
424                 if (!empty($parts['port'])) {
425                         $new_url .= ':' . $parts['port'];
426                 }
427
428                 if (!empty($parts['path'])) {
429                         $new_url .= $parts['path'];
430                 }
431
432                 if ($new_url != $url) {
433                         Logger::info('Cleaned contact url', ['url' => $url, 'new_url' => $new_url, 'callstack' => System::callstack()]);
434                 }
435
436                 return $new_url;
437         }
438
439         /**
440          * Fetch the gcontact id, add an entry if not existed
441          *
442          * @param array $contact contact array
443          *
444          * @return bool|int Returns false if not found, integer if contact was found
445          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
446          * @throws \ImagickException
447          */
448         public static function getId($contact)
449         {
450                 if (empty($contact['network'])) {
451                         Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
452                         return false;
453                 }
454
455                 if (in_array($contact['network'], [Protocol::PHANTOM])) {
456                         Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
457                         return false;
458                 }
459
460                 if ($contact['network'] == Protocol::STATUSNET) {
461                         $contact['network'] = Protocol::OSTATUS;
462                 }
463
464                 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
465                 if (in_array($contact['network'], Protocol::FEDERATED)) {
466                         $contact['url'] = self::cleanContactUrl($contact['url']);
467                 }
468
469                 $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
470                 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
471                 if (DBA::isResult($gcontact)) {
472                         return $gcontact['id'];
473                 }
474
475                 $contact['location'] = $contact['location'] ?? '';
476                 $contact['about'] = $contact['about'] ?? '';
477                 $contact['generation'] = $contact['generation'] ?? 0;
478                 $contact['hide'] = $contact['hide'] ?? true;
479
480                 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
481                         'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
482                         'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
483                         'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation'], 'failed' => false];
484
485                 DBA::insert('gcontact', $fields);
486
487                 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
488                 $gcontact = DBA::selectFirst('gcontact', ['id'], $condition, ['order' => ['id']]);
489                 if (!DBA::isResult($gcontact)) {
490                         Logger::info('GContact creation failed', $fields);
491                         // Shouldn't happen
492                         return 0;
493                 }
494                 return $gcontact['id'];
495         }
496
497         /**
498          * Updates the gcontact table from a given array
499          *
500          * @param array $contact contact array
501          *
502          * @return bool|int Returns false if not found, integer if contact was found
503          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504          * @throws \ImagickException
505          */
506         public static function update($contact)
507         {
508                 // Check for invalid "contact-type" value
509                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
510                         $contact['contact-type'] = 0;
511                 }
512
513                 /// @todo update contact table as well
514
515                 $gcontact_id = self::getId($contact);
516
517                 if (!$gcontact_id) {
518                         return false;
519                 }
520
521                 $public_contact = DBA::selectFirst('gcontact', [
522                         'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'keywords', 'gsid', 'failed',
523                         'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
524                 ], ['id' => $gcontact_id]);
525
526                 if (!DBA::isResult($public_contact)) {
527                         return false;
528                 }
529
530                 // Get all field names
531                 $fields = [];
532                 foreach ($public_contact as $field => $data) {
533                         $fields[$field] = $data;
534                 }
535
536                 unset($fields['url']);
537                 unset($fields['updated']);
538                 unset($fields['hide']);
539
540                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
541                 // This value is still transmitted via poco.
542                 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
543                         unset($contact['keywords']);
544                 }
545
546                 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
547                         $public_contact['keywords'] = '';
548                 }
549
550                 // assign all unassigned fields from the database entry
551                 foreach ($fields as $field => $data) {
552                         if (empty($contact[$field])) {
553                                 $contact[$field] = $public_contact[$field];
554                         }
555                 }
556
557                 if (!isset($contact['hide'])) {
558                         $contact['hide'] = $public_contact['hide'];
559                 }
560
561                 $fields['hide'] = $public_contact['hide'];
562
563                 if ($contact['network'] == Protocol::STATUSNET) {
564                         $contact['network'] = Protocol::OSTATUS;
565                 }
566
567                 if (!isset($contact['updated'])) {
568                         $contact['updated'] = DateTimeFormat::utcNow();
569                 }
570
571                 if ($contact['network'] == Protocol::TWITTER) {
572                         $contact['server_url'] = 'http://twitter.com';
573                 }
574
575                 if (empty($contact['server_url'])) {
576                         $data = Probe::uri($contact['url']);
577                         if ($data['network'] != Protocol::PHANTOM) {
578                                 $contact['server_url'] = $data['baseurl'];
579                         }
580                 } else {
581                         $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
582                 }
583
584                 if (!empty($contact['server_url']) && empty($contact['gsid'])) {
585                         $contact['gsid'] = GServer::getID($contact['server_url']);
586                 }
587
588                 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
589                         $hostname = str_replace('http://', '', $contact['server_url']);
590                         $contact['addr'] = $contact['nick'] . '@' . $hostname;
591                 }
592
593                 // Check if any field changed
594                 $update = false;
595                 unset($fields['generation']);
596
597                 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
598                         foreach ($fields as $field => $data) {
599                                 if ($contact[$field] != $public_contact[$field]) {
600                                         Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
601                                         $update = true;
602                                 }
603                         }
604
605                         if ($contact['generation'] < $public_contact['generation']) {
606                                 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
607                                 $update = true;
608                         }
609                 }
610
611                 if ($update) {
612                         Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
613                         $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
614                                         Strings::normaliseLink($contact['url']), $contact['generation']];
615                         $contact['updated'] = DateTimeFormat::utc($contact['updated']);
616
617                         $updated = [
618                                 'photo' => $contact['photo'], 'name' => $contact['name'],
619                                 'nick' => $contact['nick'], 'addr' => $contact['addr'],
620                                 'network' => $contact['network'], 'birthday' => $contact['birthday'],
621                                 'keywords' => $contact['keywords'],
622                                 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
623                                 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
624                                 'notify' => $contact['notify'], 'url' => $contact['url'],
625                                 'location' => $contact['location'], 'about' => $contact['about'],
626                                 'generation' => $contact['generation'], 'updated' => $contact['updated'],
627                                 'server_url' => $contact['server_url'], 'connect' => $contact['connect'],
628                                 'failed' => $contact['failed'], 'gsid' => $contact['gsid']
629                         ];
630
631                         DBA::update('gcontact', $updated, $condition, $fields);
632                 }
633
634                 return $gcontact_id;
635         }
636
637         /**
638          * Set the last date that the contact had posted something
639          *
640          * @param string $data  Probing result
641          * @param bool   $force force updating
642          */
643         public static function setLastUpdate(array $data, bool $force = false)
644         {
645                 // Fetch the global contact
646                 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
647                         ['nurl' => Strings::normaliseLink($data['url'])]);
648                 if (!DBA::isResult($gcontact)) {
649                         return;
650                 }
651
652                 if (!$force && !GServer::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
653                         Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
654                         return;
655                 }
656
657                 if (self::updateFromNoScrape($data)) {
658                         return;
659                 }
660
661                 if (!empty($data['outbox'])) {
662                         self::updateFromOutbox($data['outbox'], $data);
663                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
664                         self::updateFromOutbox($data['poll'], $data);
665                 } elseif (!empty($data['poll'])) {
666                         self::updateFromFeed($data);
667                 }
668         }
669
670         /**
671          * Update a global contact via the "noscrape" endpoint
672          *
673          * @param string $data Probing result
674          *
675          * @return bool 'true' if update was successful or the server was unreachable
676          */
677         private static function updateFromNoScrape(array $data)
678         {
679                 // Check the 'noscrape' endpoint when it is a Friendica server
680                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
681                 Strings::normaliseLink($data['baseurl'])]);
682                 if (!DBA::isResult($gserver)) {
683                         return false;
684                 }
685
686                 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
687
688                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
689                         $noscrape = json_decode($curlResult->getBody(), true);
690                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
691                                 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
692                                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
693                                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
694                                 return true;
695                         }
696                 } elseif ($curlResult->isTimeout()) {
697                         // On a timeout return the existing value, but mark the contact as failure
698                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
699                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
700                         return true;
701                 }
702                 return false;
703         }
704
705         /**
706          * Update a global contact via an ActivityPub Outbox
707          *
708          * @param string $feed
709          * @param array  $data Probing result
710          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
711          */
712         private static function updateFromOutbox(string $feed, array $data)
713         {
714                 $outbox = ActivityPub::fetchContent($feed);
715                 if (empty($outbox)) {
716                         return;
717                 }
718
719                 if (!empty($outbox['orderedItems'])) {
720                         $items = $outbox['orderedItems'];
721                 } elseif (!empty($outbox['first']['orderedItems'])) {
722                         $items = $outbox['first']['orderedItems'];
723                 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
724                         self::updateFromOutbox($outbox['first']['href'], $data);
725                         return;
726                 } elseif (!empty($outbox['first'])) {
727                         if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
728                                 self::updateFromOutbox($outbox['first'], $data);
729                         } else {
730                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
731                         }
732                         return;
733                 } else {
734                         $items = [];
735                 }
736
737                 $last_updated = '';
738                 foreach ($items as $activity) {
739                         if (!empty($activity['published'])) {
740                                 $published =  DateTimeFormat::utc($activity['published']);
741                         } elseif (!empty($activity['object']['published'])) {
742                                 $published =  DateTimeFormat::utc($activity['object']['published']);
743                         } else {
744                                 continue;
745                         }
746
747                         if ($last_updated < $published) {
748                                 $last_updated = $published;
749                         }
750                 }
751
752                 if (empty($last_updated)) {
753                         return;
754                 }
755
756                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
757                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
758         }
759
760         /**
761          * Update a global contact via an XML feed
762          *
763          * @param string $data Probing result
764          */
765         private static function updateFromFeed(array $data)
766         {
767                 // Search for the newest entry in the feed
768                 $curlResult = DI::httpRequest()->get($data['poll']);
769                 if (!$curlResult->isSuccess()) {
770                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
771                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
772
773                         Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
774                         return;
775                 }
776
777                 $doc = new DOMDocument();
778                 @$doc->loadXML($curlResult->getBody());
779
780                 $xpath = new DOMXPath($doc);
781                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
782
783                 $entries = $xpath->query('/atom:feed/atom:entry');
784
785                 $last_updated = '';
786
787                 foreach ($entries as $entry) {
788                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
789                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
790                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
791                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
792
793                         if (empty($published) || empty($updated)) {
794                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
795                                 continue;
796                         }
797
798                         if ($last_updated < $published) {
799                                 $last_updated = $published;
800                         }
801
802                         if ($last_updated < $updated) {
803                                 $last_updated = $updated;
804                         }
805                 }
806
807                 if (empty($last_updated)) {
808                         return;
809                 }
810
811                 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
812                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
813         }
814         /**
815          * Updates the gcontact entry from a given public contact id
816          *
817          * @param integer $cid contact id
818          * @return void
819          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
820          * @throws \ImagickException
821          */
822         public static function updateFromPublicContactID($cid)
823         {
824                 self::updateFromPublicContact(['id' => $cid]);
825         }
826
827         /**
828          * Updates the gcontact entry from a given public contact url
829          *
830          * @param string $url contact url
831          * @return integer gcontact id
832          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833          * @throws \ImagickException
834          */
835         public static function updateFromPublicContactURL($url)
836         {
837                 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
838         }
839
840         /**
841          * Helper function for updateFromPublicContactID and updateFromPublicContactURL
842          *
843          * @param array $condition contact condition
844          * @return integer gcontact id
845          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
846          * @throws \ImagickException
847          */
848         private static function updateFromPublicContact($condition)
849         {
850                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords',
851                         'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
852                         'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
853                         'baseurl', 'gsid', 'sensitive', 'unsearchable', 'failed'];
854
855                 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
856                 if (!DBA::isResult($contact)) {
857                         return 0;
858                 }
859
860                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'generation',
861                         'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
862                         'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
863                         'server_url', 'gsid', 'nsfw', 'hide', 'id', 'failed'];
864
865                 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
866                 $do_insert = !DBA::isResult($old_gcontact);
867                 if ($do_insert) {
868                         $old_gcontact = [];
869                 }
870
871                 $gcontact = [];
872
873                 // These fields are identical in both contact and gcontact
874                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gsid',
875                         'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated', 'failed'];
876
877                 foreach ($fields as $field) {
878                         $gcontact[$field] = $contact[$field];
879                 }
880
881                 // These fields are having different names but the same content
882                 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
883                 $gcontact['nsfw'] = $contact['sensitive'];
884                 $gcontact['hide'] = $contact['unsearchable'];
885                 $gcontact['archived'] = $contact['archive'];
886                 $gcontact['archive_date'] = $contact['term-date'];
887                 $gcontact['birthday'] = $contact['bd'];
888                 $gcontact['photo'] = $contact['avatar'];
889                 $gcontact['last_contact'] = $contact['success_update'];
890                 $gcontact['last_failure'] = $contact['failure_update'];
891                 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
892
893                 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
894                         if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
895                                 unset($gcontact[$field]);
896                         }
897                 }
898
899                 if (!$gcontact['archived']) {
900                         $gcontact['archive_date'] = DBA::NULL_DATETIME;
901                 }
902
903                 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
904                         && ($old_gcontact['created'] <= $gcontact['created'])) {
905                         unset($gcontact['created']);
906                 }
907
908                 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
909                         unset($gcontact['birthday']);
910                 }
911
912                 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
913                         $gcontact['generation'] = 2; // We fetched the data directly from the other server
914                 }
915
916                 if (!$do_insert) {
917                         DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
918                         return $old_gcontact['id'];
919                 } elseif (!$gcontact['archived']) {
920                         DBA::insert('gcontact', $gcontact);
921                         return DBA::lastInsertId();
922                 }
923         }
924
925         /**
926          * Updates the gcontact entry from probe
927          *
928          * @param string  $url   profile link
929          * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
930          *
931          * @return boolean 'true' when contact had been updated
932          *
933          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
934          * @throws \ImagickException
935          */
936         public static function updateFromProbe($url, $force = false)
937         {
938                 $data = Probe::uri($url, $force);
939
940                 if (in_array($data['network'], [Protocol::PHANTOM])) {
941                         $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
942                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
943                         Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
944                         return false;
945                 }
946
947                 $data['server_url'] = $data['baseurl'];
948                 $data['failed'] = false;
949
950                 self::update($data);
951
952                 // Set the date of the latest post
953                 self::setLastUpdate($data, $force);
954
955                 return true;
956         }
957
958         /**
959          * Update the gcontact entry for a given user id
960          *
961          * @param int $uid User ID
962          * @return bool
963          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
964          * @throws \ImagickException
965          */
966         public static function updateForUser($uid)
967         {
968                 $profile = Profile::getByUID($uid);
969                 if (empty($profile)) {
970                         Logger::error('Cannot find profile', ['uid' => $uid]);
971                         return false;
972                 }
973
974                 $user = User::getOwnerDataById($uid);
975                 if (empty($user)) {
976                         Logger::error('Cannot find user', ['uid' => $uid]);
977                         return false;
978                 }
979
980                 $userdata = array_merge($profile, $user);
981
982                 $location = Profile::formatLocation(
983                         ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
984                 );
985
986                 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
987                                 'keywords' => $userdata['pub_keywords'],
988                                 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
989                                 "notify" => $userdata['notify'], 'url' => $userdata['url'],
990                                 "hide" => !$userdata['net-publish'],
991                                 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
992                                 "connect" => $userdata['addr'], "server_url" => DI::baseUrl(),
993                                 "generation" => 1, 'network' => Protocol::DFRN];
994
995                 self::update($gcontact);
996         }
997
998         /**
999          * Get the basepath for a given contact link
1000          *
1001          * @param string $url The gcontact link
1002          * @param boolean $dont_update Don't update the contact
1003          *
1004          * @return string basepath
1005          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1006          * @throws \ImagickException
1007          */
1008         public static function getBasepath($url, $dont_update = false)
1009         {
1010                 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1011                 if (!empty($gcontact['server_url'])) {
1012                         return $gcontact['server_url'];
1013                 } elseif ($dont_update) {
1014                         return '';
1015                 }
1016
1017                 self::updateFromProbe($url, true);
1018
1019                 // Fetch the result
1020                 $gcontact = DBA::selectFirst('gcontact', ['server_url'], ['nurl' => Strings::normaliseLink($url)]);
1021                 if (empty($gcontact['server_url'])) {
1022                         Logger::info('No baseurl for gcontact', ['url' => $url]);
1023                         return '';
1024                 }
1025
1026                 Logger::info('Found baseurl for gcontact', ['url' => $url, 'baseurl' => $gcontact['server_url']]);
1027                 return $gcontact['server_url'];
1028         }
1029
1030         /**
1031          * Fetches users of given GNU Social server
1032          *
1033          * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1034          *
1035          * @param string $server Server address
1036          * @return bool
1037          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1038          * @throws \ImagickException
1039          */
1040         public static function fetchGsUsers($server)
1041         {
1042                 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1043
1044                 $url = $server . '/main/statistics';
1045
1046                 $curlResult = DI::httpRequest()->get($url);
1047                 if (!$curlResult->isSuccess()) {
1048                         return false;
1049                 }
1050
1051                 $statistics = json_decode($curlResult->getBody());
1052
1053                 if (!empty($statistics->config->instance_address)) {
1054                         if (!empty($statistics->config->instance_with_ssl)) {
1055                                 $server = 'https://';
1056                         } else {
1057                                 $server = 'http://';
1058                         }
1059
1060                         $server .= $statistics->config->instance_address;
1061
1062                         $hostname = $statistics->config->instance_address;
1063                 } elseif (!empty($statistics->instance_address)) {
1064                         if (!empty($statistics->instance_with_ssl)) {
1065                                 $server = 'https://';
1066                         } else {
1067                                 $server = 'http://';
1068                         }
1069
1070                         $server .= $statistics->instance_address;
1071
1072                         $hostname = $statistics->instance_address;
1073                 }
1074
1075                 if (!empty($statistics->users)) {
1076                         foreach ($statistics->users as $nick => $user) {
1077                                 $profile_url = $server . '/' . $user->nickname;
1078
1079                                 $contact = ['url' => $profile_url,
1080                                                 'name' => $user->fullname,
1081                                                 'addr' => $user->nickname . '@' . $hostname,
1082                                                 'nick' => $user->nickname,
1083                                                 "network" => Protocol::OSTATUS,
1084                                                 'photo' => DI::baseUrl() . '/images/person-300.jpg'];
1085
1086                                 if (isset($user->bio)) {
1087                                         $contact['about'] = $user->bio;
1088                                 }
1089
1090                                 self::getId($contact);
1091                         }
1092                 }
1093         }
1094
1095         /**
1096          * Asking GNU Social server on a regular base for their user data
1097          *
1098          * @return void
1099          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100          * @throws \ImagickException
1101          */
1102         public static function discoverGsUsers()
1103         {
1104                 $requery_days = intval(DI::config()->get('system', 'poco_requery_days'));
1105
1106                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1107
1108                 $r = DBA::select('gserver', ['nurl', 'url'], [
1109                         '`network` = ?
1110                         AND NOT `failed`
1111                         AND `last_poco_query` < ?',
1112                         Protocol::OSTATUS,
1113                         $last_update
1114                 ], [
1115                         'limit' => 5,
1116                         'order' => ['RAND()']
1117                 ]);
1118
1119                 if (!DBA::isResult($r)) {
1120                         return;
1121                 }
1122
1123                 foreach ($r as $server) {
1124                         self::fetchGsUsers($server['url']);
1125                         DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1126                 }
1127         }
1128
1129         /**
1130          * Returns a random, global contact of the current node
1131          *
1132          * @return string The profile URL
1133          * @throws Exception
1134          */
1135         public static function getRandomUrl()
1136         {
1137                 $r = DBA::selectFirst('gcontact', ['url'], [
1138                         '`network` = ?
1139                         AND NOT `failed`
1140                         AND `updated` > ?',
1141                         Protocol::DFRN,
1142                         DateTimeFormat::utc('now - 1 month'),
1143                 ], ['order' => ['RAND()']]);
1144
1145                 if (DBA::isResult($r)) {
1146                         return $r['url'];
1147                 }
1148
1149                 return '';
1150         }
1151 }