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