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