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