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