]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
2caad945919f04e9fe7d19af279b6c34b0a02517
[friendica.git] / src / Model / GContact.php
1 <?php
2 /**
3  * @file src/Model/GlobalContact.php
4  * @brief 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\Config;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
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  * @brief This class handles GlobalContact related functions
26  */
27 class GContact
28 {
29         /**
30          * @brief 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 (Config::get('system', 'diaspora_enabled')) {
46                         $diaspora = Protocol::DIASPORA;
47                 } else {
48                         $diaspora = Protocol::DFRN;
49                 }
50
51                 if (!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          * @brief 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          * @brief 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(System::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 = Contact::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 (Config::get('system', 'diaspora_enabled')) {
427                         $network[] = Protocol::DIASPORA;
428                 }
429
430                 if (!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, System::baseUrl() . '/poco');
507
508                 $done[] = System::baseUrl() . '/poco';
509
510                 if (strlen(Config::get('system', 'directory'))) {
511                         $x = Network::fetchUrl(get_server() . '/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          * @brief 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          * @brief 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                 $doprobing = false;
584                 $last_failure_str = '';
585                 $last_contact_str = '';
586
587                 if (empty($contact['network'])) {
588                         Logger::notice('Empty network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
589                         return false;
590                 }
591
592                 if (in_array($contact['network'], [Protocol::PHANTOM])) {
593                         Logger::notice('Invalid network', ['url' => $contact['url'], 'callstack' => System::callstack()]);
594                         return false;
595                 }
596
597                 if ($contact['network'] == Protocol::STATUSNET) {
598                         $contact['network'] = Protocol::OSTATUS;
599                 }
600
601                 // All new contacts are hidden by default
602                 if (!isset($contact['hide'])) {
603                         $contact['hide'] = true;
604                 }
605
606                 // Remove unwanted parts from the contact url (e.g. '?zrl=...')
607                 if (in_array($contact['network'], Protocol::FEDERATED)) {
608                         $contact['url'] = self::cleanContactUrl($contact['url']);
609                 }
610
611                 DBA::lock('gcontact');
612                 $fields = ['id', 'last_contact', 'last_failure', 'network'];
613                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
614                 if (DBA::isResult($gcnt)) {
615                         $gcontact_id = $gcnt['id'];
616
617                         // Update every 90 days
618                         if (empty($gcnt['network']) || in_array($gcnt['network'], Protocol::FEDERATED)) {
619                                 $last_failure_str = $gcnt['last_failure'];
620                                 $last_failure = strtotime($gcnt['last_failure']);
621                                 $last_contact_str = $gcnt['last_contact'];
622                                 $last_contact = strtotime($gcnt['last_contact']);
623                                 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
624                         }
625                 } else {
626                         $contact['location'] = $contact['location'] ?? '';
627                         $contact['about'] = $contact['about'] ?? '';
628                         $contact['generation'] = $contact['generation'] ?? 0;
629
630                         $fields = ['name' => $contact['name'], 'nick' => $contact['nick'] ?? '', 'addr' => $contact['addr'] ?? '', 'network' => $contact['network'],
631                                 'url' => $contact['url'], 'nurl' => Strings::normaliseLink($contact['url']), 'photo' => $contact['photo'],
632                                 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), 'location' => $contact['location'],
633                                 'about' => $contact['about'], 'hide' => $contact['hide'], 'generation' => $contact['generation']];
634
635                         DBA::insert('gcontact', $fields);
636
637                         $condition = ['nurl' => Strings::normaliseLink($contact['url'])];
638                         $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
639                         if (DBA::isResult($cnt)) {
640                                 $gcontact_id = $cnt['id'];
641                                 $doprobing = (empty($cnt['network']) || in_array($cnt['network'], Protocol::FEDERATED));
642                         }
643                 }
644                 DBA::unlock();
645
646                 if ($doprobing) {
647                         Logger::notice('Probing', ['contact' => $last_contact_str, "failure" => $last_failure_str, "checking" => $contact['url']]);
648                         Worker::add(PRIORITY_LOW, 'GProbe', $contact['url']);
649                 }
650
651                 return $gcontact_id;
652         }
653
654         /**
655          * @brief Updates the gcontact table from a given array
656          *
657          * @param array $contact contact array
658          *
659          * @return bool|int Returns false if not found, integer if contact was found
660          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
661          * @throws \ImagickException
662          */
663         public static function update($contact)
664         {
665                 // Check for invalid "contact-type" value
666                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
667                         $contact['contact-type'] = 0;
668                 }
669
670                 /// @todo update contact table as well
671
672                 $gcontact_id = self::getId($contact);
673
674                 if (!$gcontact_id) {
675                         return false;
676                 }
677
678                 $public_contact = DBA::selectFirst('gcontact', [
679                         'name', 'nick', 'photo', 'location', 'about', 'addr', 'generation', 'birthday', 'gender', 'keywords',
680                         'contact-type', 'hide', 'nsfw', 'network', 'alias', 'notify', 'server_url', 'connect', 'updated', 'url'
681                 ], ['id' => $gcontact_id]);
682
683                 if (!DBA::isResult($public_contact)) {
684                         return false;
685                 }
686
687                 // Get all field names
688                 $fields = [];
689                 foreach ($public_contact as $field => $data) {
690                         $fields[$field] = $data;
691                 }
692
693                 unset($fields['url']);
694                 unset($fields['updated']);
695                 unset($fields['hide']);
696
697                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
698                 // This value is still transmitted via poco.
699                 if (isset($contact['keywords']) && ($contact['keywords'] == '0')) {
700                         unset($contact['keywords']);
701                 }
702
703                 if (isset($public_contact['keywords']) && ($public_contact['keywords'] == '0')) {
704                         $public_contact['keywords'] = '';
705                 }
706
707                 // assign all unassigned fields from the database entry
708                 foreach ($fields as $field => $data) {
709                         if (empty($contact[$field])) {
710                                 $contact[$field] = $public_contact[$field];
711                         }
712                 }
713
714                 if (!isset($contact['hide'])) {
715                         $contact['hide'] = $public_contact['hide'];
716                 }
717
718                 $fields['hide'] = $public_contact['hide'];
719
720                 if ($contact['network'] == Protocol::STATUSNET) {
721                         $contact['network'] = Protocol::OSTATUS;
722                 }
723
724                 if (!isset($contact['updated'])) {
725                         $contact['updated'] = DateTimeFormat::utcNow();
726                 }
727
728                 if ($contact['network'] == Protocol::TWITTER) {
729                         $contact['server_url'] = 'http://twitter.com';
730                 }
731
732                 if (empty($contact['server_url'])) {
733                         $data = Probe::uri($contact['url']);
734                         if ($data['network'] != Protocol::PHANTOM) {
735                                 $contact['server_url'] = $data['baseurl'];
736                         }
737                 } else {
738                         $contact['server_url'] = Strings::normaliseLink($contact['server_url']);
739                 }
740
741                 if (empty($contact['addr']) && !empty($contact['server_url']) && !empty($contact['nick'])) {
742                         $hostname = str_replace('http://', '', $contact['server_url']);
743                         $contact['addr'] = $contact['nick'] . '@' . $hostname;
744                 }
745
746                 // Check if any field changed
747                 $update = false;
748                 unset($fields['generation']);
749
750                 if ((($contact['generation'] > 0) && ($contact['generation'] <= $public_contact['generation'])) || ($public_contact['generation'] == 0)) {
751                         foreach ($fields as $field => $data) {
752                                 if ($contact[$field] != $public_contact[$field]) {
753                                         Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => $field, 'new' => $contact[$field], 'old' => $public_contact[$field]]);
754                                         $update = true;
755                                 }
756                         }
757
758                         if ($contact['generation'] < $public_contact['generation']) {
759                                 Logger::debug('Difference found.', ['contact' => $contact['url'], 'field' => 'generation', 'new' => $contact['generation'], 'old' => $public_contact['generation']]);
760                                 $update = true;
761                         }
762                 }
763
764                 if ($update) {
765                         Logger::debug('Update gcontact.', ['contact' => $contact['url']]);
766                         $condition = ["`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)",
767                                         Strings::normaliseLink($contact['url']), $contact['generation']];
768                         $contact['updated'] = DateTimeFormat::utc($contact['updated']);
769
770                         $updated = [
771                                 'photo' => $contact['photo'], 'name' => $contact['name'],
772                                 'nick' => $contact['nick'], 'addr' => $contact['addr'],
773                                 'network' => $contact['network'], 'birthday' => $contact['birthday'],
774                                 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
775                                 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
776                                 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
777                                 'notify' => $contact['notify'], 'url' => $contact['url'],
778                                 'location' => $contact['location'], 'about' => $contact['about'],
779                                 'generation' => $contact['generation'], 'updated' => $contact['updated'],
780                                 'server_url' => $contact['server_url'], 'connect' => $contact['connect']
781                         ];
782
783                         DBA::update('gcontact', $updated, $condition, $fields);
784                 }
785
786                 return $gcontact_id;
787         }
788
789         /**
790          * Set the last date that the contact had posted something
791          *
792          * @param string $data  Probing result
793          * @param bool   $force force updating
794          */
795         public static function setLastUpdate(array $data, bool $force = false)
796         {
797                 // Fetch the global contact
798                 $gcontact = DBA::selectFirst('gcontact', ['created', 'updated', 'last_contact', 'last_failure'],
799                         ['nurl' => Strings::normaliseLink($data['url'])]);
800                 if (!DBA::isResult($gcontact)) {
801                         return;
802                 }
803
804                 if (!$force && !PortableContact::updateNeeded($gcontact['created'], $gcontact['updated'], $gcontact['last_failure'], $gcontact['last_contact'])) {
805                         Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $gcontact['updated']]);
806                         return;
807                 }
808
809                 if (self::updateFromNoScrape($data)) {
810                         return;
811                 }
812
813                 if (!empty($data['outbox'])) {
814                         self::updateFromOutbox($data['outbox'], $data);
815                 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
816                         self::updateFromOutbox($data['poll'], $data);
817                 } elseif (!empty($data['poll'])) {
818                         self::updateFromFeed($data);
819                 }
820         }
821
822         /**
823          * Update a global contact via the "noscrape" endpoint
824          *
825          * @param string $data Probing result
826          *
827          * @return bool 'true' if update was successful or the server was unreachable
828          */
829         private static function updateFromNoScrape(array $data)
830         {
831                 // Check the 'noscrape' endpoint when it is a Friendica server
832                 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
833                 Strings::normaliseLink($data['baseurl'])]);
834                 if (!DBA::isResult($gserver)) {
835                         return false;
836                 }
837
838                 $curlResult = Network::curl($gserver['noscrape'] . '/' . $data['nick']);
839
840                 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
841                         $noscrape = json_decode($curlResult->getBody(), true);
842                         if (!empty($noscrape) && !empty($noscrape['updated'])) {
843                                 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
844                                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
845                                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
846                                 return true;
847                         }
848                 } elseif ($curlResult->isTimeout()) {
849                         // On a timeout return the existing value, but mark the contact as failure
850                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
851                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
852                         return true;
853                 }
854                 return false;
855         }
856
857         /**
858          * Update a global contact via an ActivityPub Outbox
859          *
860          * @param string $feed
861          * @param array  $data Probing result
862          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
863          */
864         private static function updateFromOutbox(string $feed, array $data)
865         {
866                 $outbox = ActivityPub::fetchContent($feed);
867                 if (empty($outbox)) {
868                         return;
869                 }
870
871                 if (!empty($outbox['orderedItems'])) {
872                         $items = $outbox['orderedItems'];
873                 } elseif (!empty($outbox['first']['orderedItems'])) {
874                         $items = $outbox['first']['orderedItems'];
875                 } elseif (!empty($outbox['first']['href'])) {
876                         self::updateFromOutbox($outbox['first']['href'], $data);
877                         return;
878                 } elseif (!empty($outbox['first'])) {
879                         if (is_string($outbox['first'])) {
880                                 self::updateFromOutbox($outbox['first'], $data);
881                         } else {
882                                 Logger::warning('Unexpected data', ['outbox' => $outbox]);
883                         }
884                         return;
885                 } else {
886                         $items = [];
887                 }
888
889                 $last_updated = '';
890                 foreach ($items as $activity) {
891                         if (!empty($activity['published'])) {
892                                 $published =  DateTimeFormat::utc($activity['published']);
893                         } elseif (!empty($activity['object']['published'])) {
894                                 $published =  DateTimeFormat::utc($activity['object']['published']);
895                         } else {
896                                 continue;
897                         }
898
899                         if ($last_updated < $published) {
900                                 $last_updated = $published;
901                         }
902                 }
903
904                 if (empty($last_updated)) {
905                         return;
906                 }
907
908                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
909                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
910         }
911
912         /**
913          * Update a global contact via an XML feed
914          *
915          * @param string $data Probing result
916          */
917         private static function updateFromFeed(array $data)
918         {
919                 // Search for the newest entry in the feed
920                 $curlResult = Network::curl($data['poll']);
921                 if (!$curlResult->isSuccess()) {
922                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
923                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($profile)]);
924
925                         Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
926                         return;
927                 }
928
929                 $doc = new DOMDocument();
930                 @$doc->loadXML($curlResult->getBody());
931
932                 $xpath = new DOMXPath($doc);
933                 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
934
935                 $entries = $xpath->query('/atom:feed/atom:entry');
936
937                 $last_updated = '';
938
939                 foreach ($entries as $entry) {
940                         $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
941                         $updated_item   = $xpath->query('atom:updated/text()'  , $entry)->item(0);
942                         $published      = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
943                         $updated        = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
944
945                         if (empty($published) || empty($updated)) {
946                                 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
947                                 continue;
948                         }
949
950                         if ($last_updated < $published) {
951                                 $last_updated = $published;
952                         }
953
954                         if ($last_updated < $updated) {
955                                 $last_updated = $updated;
956                         }
957                 }
958
959                 if (empty($last_updated)) {
960                         return;
961                 }
962
963                 $fields = ['last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
964                 DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
965         }
966         /**
967          * @brief Updates the gcontact entry from a given public contact id
968          *
969          * @param integer $cid contact id
970          * @return void
971          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
972          * @throws \ImagickException
973          */
974         public static function updateFromPublicContactID($cid)
975         {
976                 self::updateFromPublicContact(['id' => $cid]);
977         }
978
979         /**
980          * @brief Updates the gcontact entry from a given public contact url
981          *
982          * @param string $url contact url
983          * @return integer gcontact id
984          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
985          * @throws \ImagickException
986          */
987         public static function updateFromPublicContactURL($url)
988         {
989                 return self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
990         }
991
992         /**
993          * @brief Helper function for updateFromPublicContactID and updateFromPublicContactURL
994          *
995          * @param array $condition contact condition
996          * @return integer gcontact id
997          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
998          * @throws \ImagickException
999          */
1000         private static function updateFromPublicContact($condition)
1001         {
1002                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1003                         'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
1004                         'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv',
1005                         'baseurl', 'sensitive', 'unsearchable'];
1006
1007                 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
1008                 if (!DBA::isResult($contact)) {
1009                         return 0;
1010                 }
1011
1012                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
1013                         'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
1014                         'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect',
1015                         'server_url', 'nsfw', 'hide', 'id'];
1016
1017                 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
1018                 $do_insert = !DBA::isResult($old_gcontact);
1019                 if ($do_insert) {
1020                         $old_gcontact = [];
1021                 }
1022
1023                 $gcontact = [];
1024
1025                 // These fields are identical in both contact and gcontact
1026                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
1027                         'contact-type', 'network', 'addr', 'notify', 'alias', 'created', 'updated'];
1028
1029                 foreach ($fields as $field) {
1030                         $gcontact[$field] = $contact[$field];
1031                 }
1032
1033                 // These fields are having different names but the same content
1034                 $gcontact['server_url'] = $contact['baseurl'] ?? ''; // "baseurl" can be null, "server_url" not
1035                 $gcontact['nsfw'] = $contact['sensitive'];
1036                 $gcontact['hide'] = $contact['unsearchable'];
1037                 $gcontact['archived'] = $contact['archive'];
1038                 $gcontact['archive_date'] = $contact['term-date'];
1039                 $gcontact['birthday'] = $contact['bd'];
1040                 $gcontact['photo'] = $contact['avatar'];
1041                 $gcontact['last_contact'] = $contact['success_update'];
1042                 $gcontact['last_failure'] = $contact['failure_update'];
1043                 $gcontact['community'] = ($contact['forum'] || $contact['prv']);
1044
1045                 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
1046                         if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
1047                                 unset($gcontact[$field]);
1048                         }
1049                 }
1050
1051                 if (!$gcontact['archived']) {
1052                         $gcontact['archive_date'] = DBA::NULL_DATETIME;
1053                 }
1054
1055                 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
1056                         && ($old_gcontact['created'] <= $gcontact['created'])) {
1057                         unset($gcontact['created']);
1058                 }
1059
1060                 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
1061                         unset($gcontact['birthday']);
1062                 }
1063
1064                 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
1065                         $gcontact['generation'] = 2; // We fetched the data directly from the other server
1066                 }
1067
1068                 if (!$do_insert) {
1069                         DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
1070                         return $old_gcontact['id'];
1071                 } elseif (!$gcontact['archived']) {
1072                         DBA::insert('gcontact', $gcontact);
1073                         return DBA::lastInsertId();
1074                 }
1075         }
1076
1077         /**
1078          * @brief Updates the gcontact entry from probe
1079          *
1080          * @param string  $url   profile link
1081          * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1082          *
1083          * @return boolean 'true' when contact had been updated
1084          *
1085          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086          * @throws \ImagickException
1087          */
1088         public static function updateFromProbe($url, $force = false)
1089         {
1090                 $data = Probe::uri($url, $force);
1091
1092                 if (in_array($data['network'], [Protocol::PHANTOM])) {
1093                         $fields = ['last_failure' => DateTimeFormat::utcNow()];
1094                         DBA::update('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1095                         Logger::info('Invalid network for contact', ['url' => $data['url'], 'callstack' => System::callstack()]);
1096                         return false;
1097                 }
1098
1099                 $data['server_url'] = $data['baseurl'];
1100
1101                 self::update($data);
1102
1103                 // Set the date of the latest post
1104                 self::setLastUpdate($data, $force);
1105
1106                 return true;
1107         }
1108
1109         /**
1110          * @brief Update the gcontact entry for a given user id
1111          *
1112          * @param int $uid User ID
1113          * @return bool
1114          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1115          * @throws \ImagickException
1116          */
1117         public static function updateForUser($uid)
1118         {
1119                 $profile = Profile::getByUID($uid);
1120                 if (empty($profile)) {
1121                         Logger::error('Cannot find profile', ['uid' => $uid]);
1122                         return false;
1123                 }
1124
1125                 $user = User::getOwnerDataById($uid);
1126                 if (empty($user)) {
1127                         Logger::error('Cannot find user', ['uid' => $uid]);
1128                         return false;
1129                 }
1130
1131                 $userdata = array_merge($profile, $user);
1132
1133                 $location = Profile::formatLocation(
1134                         ['locality' => $userdata['locality'], 'region' => $userdata['region'], 'country-name' => $userdata['country-name']]
1135                 );
1136
1137                 $gcontact = ['name' => $userdata['name'], 'location' => $location, 'about' => $userdata['about'],
1138                                 'gender' => $userdata['gender'], 'keywords' => $userdata['pub_keywords'],
1139                                 'birthday' => $userdata['dob'], 'photo' => $userdata['photo'],
1140                                 "notify" => $userdata['notify'], 'url' => $userdata['url'],
1141                                 "hide" => ($userdata['hidewall'] || !$userdata['net-publish']),
1142                                 'nick' => $userdata['nickname'], 'addr' => $userdata['addr'],
1143                                 "connect" => $userdata['addr'], "server_url" => System::baseUrl(),
1144                                 "generation" => 1, 'network' => Protocol::DFRN];
1145
1146                 self::update($gcontact);
1147         }
1148
1149         /**
1150          * @brief Fetches users of given GNU Social server
1151          *
1152          * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1153          *
1154          * @param string $server Server address
1155          * @return bool
1156          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1157          * @throws \ImagickException
1158          */
1159         public static function fetchGsUsers($server)
1160         {
1161                 Logger::info('Fetching users from GNU Social server', ['server' => $server]);
1162
1163                 $url = $server . '/main/statistics';
1164
1165                 $curlResult = Network::curl($url);
1166                 if (!$curlResult->isSuccess()) {
1167                         return false;
1168                 }
1169
1170                 $statistics = json_decode($curlResult->getBody());
1171
1172                 if (!empty($statistics->config->instance_address)) {
1173                         if (!empty($statistics->config->instance_with_ssl)) {
1174                                 $server = 'https://';
1175                         } else {
1176                                 $server = 'http://';
1177                         }
1178
1179                         $server .= $statistics->config->instance_address;
1180
1181                         $hostname = $statistics->config->instance_address;
1182                 } elseif (!empty($statistics->instance_address)) {
1183                         if (!empty($statistics->instance_with_ssl)) {
1184                                 $server = 'https://';
1185                         } else {
1186                                 $server = 'http://';
1187                         }
1188
1189                         $server .= $statistics->instance_address;
1190
1191                         $hostname = $statistics->instance_address;
1192                 }
1193
1194                 if (!empty($statistics->users)) {
1195                         foreach ($statistics->users as $nick => $user) {
1196                                 $profile_url = $server . '/' . $user->nickname;
1197
1198                                 $contact = ['url' => $profile_url,
1199                                                 'name' => $user->fullname,
1200                                                 'addr' => $user->nickname . '@' . $hostname,
1201                                                 'nick' => $user->nickname,
1202                                                 "network" => Protocol::OSTATUS,
1203                                                 'photo' => System::baseUrl() . '/images/person-300.jpg'];
1204
1205                                 if (isset($user->bio)) {
1206                                         $contact['about'] = $user->bio;
1207                                 }
1208
1209                                 self::getId($contact);
1210                         }
1211                 }
1212         }
1213
1214         /**
1215          * @brief Asking GNU Social server on a regular base for their user data
1216          * @return void
1217          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1218          * @throws \ImagickException
1219          */
1220         public static function discoverGsUsers()
1221         {
1222                 $requery_days = intval(Config::get('system', 'poco_requery_days'));
1223
1224                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1225
1226                 $r = DBA::select('gserver', ['nurl', 'url'], [
1227                         '`network` = ?
1228                         AND `last_contact` >= `last_failure`
1229                         AND `last_poco_query` < ?',
1230                         Protocol::OSTATUS,
1231                         $last_update
1232                 ], [
1233                         'limit' => 5,
1234                         'order' => ['RAND()']
1235                 ]);
1236
1237                 if (!DBA::isResult($r)) {
1238                         return;
1239                 }
1240
1241                 foreach ($r as $server) {
1242                         self::fetchGsUsers($server['url']);
1243                         DBA::update('gserver', ['last_poco_query' => DateTimeFormat::utcNow()], ['nurl' => $server['nurl']]);
1244                 }
1245         }
1246
1247         /**
1248          * Returns a random, global contact of the current node
1249          *
1250          * @return string The profile URL
1251          * @throws Exception
1252          */
1253         public static function getRandomUrl()
1254         {
1255                 $r = DBA::selectFirst('gcontact', ['url'], [
1256                         '`network` = ? 
1257                         AND `last_contact` >= `last_failure`  
1258                         AND `updated` > ?',
1259                         Protocol::DFRN,
1260                         DateTimeFormat::utc('now - 1 month'),
1261                 ], ['order' => ['RAND()']]);
1262
1263                 if (DBA::isResult($r)) {
1264                         return $r['url'];
1265                 }
1266
1267                 return '';
1268         }
1269 }