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