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