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