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