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