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