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