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