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