]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
Use direct logic
[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          * @throws Exception
246          */
247         public static function countCommonFriends($uid, $cid)
248         {
249                 $r = q(
250                         "SELECT count(*) as `total`
251                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
252                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
253                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
254                         (`gcontact`.`updated` >= `gcontact`.`last_failure`))
255                         AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
256                         intval($cid),
257                         intval($uid),
258                         intval($uid),
259                         intval($cid)
260                 );
261
262                 // Logger::log("countCommonFriends: $uid $cid {$r[0]['total']}");
263                 if (DBA::isResult($r)) {
264                         return $r[0]['total'];
265                 }
266                 return 0;
267         }
268
269         /**
270          * @param integer $uid  id
271          * @param integer $zcid zcid
272          * @return integer
273          * @throws Exception
274          */
275         public static function countCommonFriendsZcid($uid, $zcid)
276         {
277                 $r = q(
278                         "SELECT count(*) as `total`
279                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
280                         where `glink`.`zcid` = %d
281                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
282                         intval($zcid),
283                         intval($uid)
284                 );
285
286                 if (DBA::isResult($r)) {
287                         return $r[0]['total'];
288                 }
289
290                 return 0;
291         }
292
293         /**
294          * @param integer $uid     user
295          * @param integer $cid     cid
296          * @param integer $start   optional, default 0
297          * @param integer $limit   optional, default 9999
298          * @param boolean $shuffle optional, default false
299          * @return object
300          * @throws Exception
301          */
302         public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
303         {
304                 if ($shuffle) {
305                         $sql_extra = " order by rand() ";
306                 } else {
307                         $sql_extra = " order by `gcontact`.`name` asc ";
308                 }
309
310                 $r = q(
311                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
312                         FROM `glink`
313                         INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
314                         INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
315                         WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
316                                 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
317                                 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
318                                 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
319                                 $sql_extra LIMIT %d, %d",
320                         intval($cid),
321                         intval($uid),
322                         intval($uid),
323                         intval($cid),
324                         intval($start),
325                         intval($limit)
326                 );
327
328                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
329                 return $r;
330         }
331
332         /**
333          * @param integer $uid     user
334          * @param integer $zcid    zcid
335          * @param integer $start   optional, default 0
336          * @param integer $limit   optional, default 9999
337          * @param boolean $shuffle optional, default false
338          * @return object
339          * @throws Exception
340          */
341         public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
342         {
343                 if ($shuffle) {
344                         $sql_extra = " order by rand() ";
345                 } else {
346                         $sql_extra = " order by `gcontact`.`name` asc ";
347                 }
348
349                 $r = q(
350                         "SELECT `gcontact`.*
351                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
352                         where `glink`.`zcid` = %d
353                         and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
354                         $sql_extra limit %d, %d",
355                         intval($zcid),
356                         intval($uid),
357                         intval($start),
358                         intval($limit)
359                 );
360
361                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
362                 return $r;
363         }
364
365         /**
366          * @param integer $uid user
367          * @param integer $cid cid
368          * @return integer
369          * @throws Exception
370          */
371         public static function countAllFriends($uid, $cid)
372         {
373                 $r = q(
374                         "SELECT count(*) as `total`
375                         FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
376                         where `glink`.`cid` = %d and `glink`.`uid` = %d AND
377                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
378                         intval($cid),
379                         intval($uid)
380                 );
381
382                 if (DBA::isResult($r)) {
383                         return $r[0]['total'];
384                 }
385
386                 return 0;
387         }
388
389         /**
390          * @param integer $uid   user
391          * @param integer $cid   cid
392          * @param integer $start optional, default 0
393          * @param integer $limit optional, default 80
394          * @return array
395          * @throws Exception
396          */
397         public static function allFriends($uid, $cid, $start = 0, $limit = 80)
398         {
399                 $r = q(
400                         "SELECT `gcontact`.*, `contact`.`id` AS `cid`
401                         FROM `glink`
402                         INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
403                         LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
404                         WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
405                         ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
406                         ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
407                         intval($uid),
408                         intval($cid),
409                         intval($uid),
410                         intval($start),
411                         intval($limit)
412                 );
413
414                 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
415                 return $r;
416         }
417
418         /**
419          * @param int     $uid   user
420          * @param integer $start optional, default 0
421          * @param integer $limit optional, default 80
422          * @return array
423          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
424          */
425         public static function suggestionQuery($uid, $start = 0, $limit = 80)
426         {
427                 if (!$uid) {
428                         return [];
429                 }
430
431                 /*
432                 * Uncommented because the result of the queries are to big to store it in the cache.
433                 * We need to decide if we want to change the db column type or if we want to delete it.
434                 */
435                 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
436                 //if (!is_null($list)) {
437                 //      return $list;
438                 //}
439
440                 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
441
442                 if (Config::get('system', 'diaspora_enabled')) {
443                         $network[] = Protocol::DIASPORA;
444                 }
445
446                 if (!Config::get('system', 'ostatus_disabled')) {
447                         $network[] = Protocol::OSTATUS;
448                 }
449
450                 $sql_network = implode("', '", $network);
451                 $sql_network = "'".$sql_network."'";
452
453                 /// @todo This query is really slow
454                 // By now we cache the data for five minutes
455                 $r = q(
456                         "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
457                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
458                         where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
459                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
460                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
461                         AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
462                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
463                         AND `gcontact`.`network` IN (%s)
464                         GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
465                         intval($uid),
466                         intval($uid),
467                         intval($uid),
468                         intval($uid),
469                         DBA::NULL_DATETIME,
470                         $sql_network,
471                         intval($start),
472                         intval($limit)
473                 );
474
475                 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
476                         /*
477                         * Uncommented because the result of the queries are to big to store it in the cache.
478                         * We need to decide if we want to change the db column type or if we want to delete it.
479                         */
480                         //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, Cache::FIVE_MINUTES);
481
482                         return $r;
483                 }
484
485                 $r2 = q(
486                         "SELECT gcontact.* FROM gcontact
487                         INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
488                         WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
489                         AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
490                         AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
491                         AND `gcontact`.`updated` >= '%s'
492                         AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
493                         AND `gcontact`.`network` IN (%s)
494                         ORDER BY rand() LIMIT %d, %d",
495                         intval($uid),
496                         intval($uid),
497                         intval($uid),
498                         DBA::NULL_DATETIME,
499                         $sql_network,
500                         intval($start),
501                         intval($limit)
502                 );
503
504                 $list = [];
505                 foreach ($r2 as $suggestion) {
506                         $list[$suggestion["nurl"]] = $suggestion;
507                 }
508
509                 foreach ($r as $suggestion) {
510                         $list[$suggestion["nurl"]] = $suggestion;
511                 }
512
513                 while (sizeof($list) > ($limit)) {
514                         array_pop($list);
515                 }
516
517                 /*
518                 * Uncommented because the result of the queries are to big to store it in the cache.
519                 * We need to decide if we want to change the db column type or if we want to delete it.
520                 */
521                 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, Cache::FIVE_MINUTES);
522                 return $list;
523         }
524
525         /**
526          * @return void
527          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
528          */
529         public static function updateSuggestions()
530         {
531                 $done = [];
532
533                 /// @TODO Check if it is really neccessary to poll the own server
534                 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
535
536                 $done[] = System::baseUrl() . '/poco';
537
538                 if (strlen(Config::get('system', 'directory'))) {
539                         $x = Network::fetchUrl(get_server()."/pubsites");
540                         if (!empty($x)) {
541                                 $j = json_decode($x);
542                                 if (!empty($j->entries)) {
543                                         foreach ($j->entries as $entry) {
544                                                 PortableContact::checkServer($entry->url);
545
546                                                 $url = $entry->url . '/poco';
547                                                 if (!in_array($url, $done)) {
548                                                         PortableContact::loadWorker(0, 0, 0, $url);
549                                                         $done[] = $url;
550                                                 }
551                                         }
552                                 }
553                         }
554                 }
555
556                 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
557                 $r = q(
558                         "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
559                         DBA::escape(Protocol::DFRN),
560                         DBA::escape(Protocol::DIASPORA)
561                 );
562
563                 if (DBA::isResult($r)) {
564                         foreach ($r as $rr) {
565                                 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
566                                 if (! in_array($base, $done)) {
567                                         PortableContact::loadWorker(0, 0, 0, $base);
568                                 }
569                         }
570                 }
571         }
572
573         /**
574          * @brief Removes unwanted parts from a contact url
575          *
576          * @param string $url Contact url
577          *
578          * @return string Contact url with the wanted parts
579          * @throws Exception
580          */
581         public static function cleanContactUrl($url)
582         {
583                 $parts = parse_url($url);
584
585                 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
586                         return $url;
587                 }
588
589                 $new_url = $parts["scheme"]."://".$parts["host"];
590
591                 if (isset($parts["port"])) {
592                         $new_url .= ":".$parts["port"];
593                 }
594
595                 if (isset($parts["path"])) {
596                         $new_url .= $parts["path"];
597                 }
598
599                 if ($new_url != $url) {
600                         Logger::log("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), Logger::DEBUG);
601                 }
602
603                 return $new_url;
604         }
605
606         /**
607          * @brief Replace alternate OStatus user format with the primary one
608          *
609          * @param array $contact contact array (called by reference)
610          * @return void
611          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
612          * @throws \ImagickException
613          */
614         public static function fixAlternateContactAddress(&$contact)
615         {
616                 if (($contact["network"] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
617                         $data = Probe::uri($contact["url"]);
618                         if ($contact["network"] == Protocol::OSTATUS) {
619                                 Logger::log("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
620                                 $contact["url"] = $data["url"];
621                                 $contact["addr"] = $data["addr"];
622                                 $contact["alias"] = $data["alias"];
623                                 $contact["server_url"] = $data["baseurl"];
624                         }
625                 }
626         }
627
628         /**
629          * @brief Fetch the gcontact id, add an entry if not existed
630          *
631          * @param array $contact contact array
632          *
633          * @return bool|int Returns false if not found, integer if contact was found
634          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635          * @throws \ImagickException
636          */
637         public static function getId($contact)
638         {
639                 $gcontact_id = 0;
640                 $doprobing = false;
641                 $last_failure_str = '';
642                 $last_contact_str = '';
643
644                 if (empty($contact["network"])) {
645                         Logger::log("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
646                         return false;
647                 }
648
649                 if (in_array($contact["network"], [Protocol::PHANTOM])) {
650                         Logger::log("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
651                         return false;
652                 }
653
654                 if ($contact["network"] == Protocol::STATUSNET) {
655                         $contact["network"] = Protocol::OSTATUS;
656                 }
657
658                 // All new contacts are hidden by default
659                 if (!isset($contact["hide"])) {
660                         $contact["hide"] = true;
661                 }
662
663                 // Replace alternate OStatus user format with the primary one
664                 self::fixAlternateContactAddress($contact);
665
666                 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
667                 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
668                         $contact["url"] = self::cleanContactUrl($contact["url"]);
669                 }
670
671                 DBA::lock('gcontact');
672                 $fields = ['id', 'last_contact', 'last_failure', 'network'];
673                 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact["url"])]);
674                 if (DBA::isResult($gcnt)) {
675                         $gcontact_id = $gcnt["id"];
676
677                         // Update every 90 days
678                         if (in_array($gcnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
679                                 $last_failure_str = $gcnt["last_failure"];
680                                 $last_failure = strtotime($gcnt["last_failure"]);
681                                 $last_contact_str = $gcnt["last_contact"];
682                                 $last_contact = strtotime($gcnt["last_contact"]);
683                                 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
684                         }
685                 } else {
686                         $contact['location'] = defaults($contact, 'location', '');
687                         $contact['about'] = defaults($contact, 'about', '');
688                         $contact['generation'] = defaults($contact, 'generation', 0);
689
690                         q(
691                                 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
692                                 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
693                                 DBA::escape($contact["name"]),
694                                 DBA::escape($contact["nick"]),
695                                 DBA::escape($contact["addr"]),
696                                 DBA::escape($contact["network"]),
697                                 DBA::escape($contact["url"]),
698                                 DBA::escape(Strings::normaliseLink($contact["url"])),
699                                 DBA::escape($contact["photo"]),
700                                 DBA::escape(DateTimeFormat::utcNow()),
701                                 DBA::escape(DateTimeFormat::utcNow()),
702                                 DBA::escape($contact["location"]),
703                                 DBA::escape($contact["about"]),
704                                 intval($contact["hide"]),
705                                 intval($contact["generation"])
706                         );
707
708                         $condition = ['nurl' => Strings::normaliseLink($contact["url"])];
709                         $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
710                         if (DBA::isResult($cnt)) {
711                                 $gcontact_id = $cnt["id"];
712                                 $doprobing = in_array($cnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""]);
713                         }
714                 }
715                 DBA::unlock();
716
717                 if ($doprobing) {
718                         Logger::log("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], Logger::DEBUG);
719                         Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
720                 }
721
722                 return $gcontact_id;
723         }
724
725         /**
726          * @brief Updates the gcontact table from a given array
727          *
728          * @param array $contact contact array
729          *
730          * @return bool|int Returns false if not found, integer if contact was found
731          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
732          * @throws \ImagickException
733          */
734         public static function update($contact)
735         {
736                 // Check for invalid "contact-type" value
737                 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
738                         $contact['contact-type'] = 0;
739                 }
740
741                 /// @todo update contact table as well
742
743                 $gcontact_id = self::getId($contact);
744
745                 if (!$gcontact_id) {
746                         return false;
747                 }
748
749                 $public_contact = q(
750                         "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
751                                 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
752                         FROM `gcontact` WHERE `id` = %d LIMIT 1",
753                         intval($gcontact_id)
754                 );
755
756                 // Get all field names
757                 $fields = [];
758                 foreach ($public_contact[0] as $field => $data) {
759                         $fields[$field] = $data;
760                 }
761
762                 unset($fields["url"]);
763                 unset($fields["updated"]);
764                 unset($fields["hide"]);
765
766                 // Bugfix: We had an error in the storing of keywords which lead to the "0"
767                 // This value is still transmitted via poco.
768                 if (!empty($contact["keywords"]) && ($contact["keywords"] == "0")) {
769                         unset($contact["keywords"]);
770                 }
771
772                 if (!empty($public_contact[0]["keywords"]) && ($public_contact[0]["keywords"] == "0")) {
773                         $public_contact[0]["keywords"] = "";
774                 }
775
776                 // assign all unassigned fields from the database entry
777                 foreach ($fields as $field => $data) {
778                         if (!isset($contact[$field]) || ($contact[$field] == "")) {
779                                 $contact[$field] = $public_contact[0][$field];
780                         }
781                 }
782
783                 if (!isset($contact["hide"])) {
784                         $contact["hide"] = $public_contact[0]["hide"];
785                 }
786
787                 $fields["hide"] = $public_contact[0]["hide"];
788
789                 if ($contact["network"] == Protocol::STATUSNET) {
790                         $contact["network"] = Protocol::OSTATUS;
791                 }
792
793                 // Replace alternate OStatus user format with the primary one
794                 self::fixAlternateContactAddress($contact);
795
796                 if (!isset($contact["updated"])) {
797                         $contact["updated"] = DateTimeFormat::utcNow();
798                 }
799
800                 if ($contact["network"] == Protocol::TWITTER) {
801                         $contact["server_url"] = 'http://twitter.com';
802                 }
803
804                 if ($contact["server_url"] == "") {
805                         $data = Probe::uri($contact["url"]);
806                         if ($data["network"] != Protocol::PHANTOM) {
807                                 $contact["server_url"] = $data['baseurl'];
808                         }
809                 } else {
810                         $contact["server_url"] = Strings::normaliseLink($contact["server_url"]);
811                 }
812
813                 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
814                         $hostname = str_replace("http://", "", $contact["server_url"]);
815                         $contact["addr"] = $contact["nick"]."@".$hostname;
816                 }
817
818                 // Check if any field changed
819                 $update = false;
820                 unset($fields["generation"]);
821
822                 if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
823                         foreach ($fields as $field => $data) {
824                                 if ($contact[$field] != $public_contact[0][$field]) {
825                                         Logger::log("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", Logger::DEBUG);
826                                         $update = true;
827                                 }
828                         }
829
830                         if ($contact["generation"] < $public_contact[0]["generation"]) {
831                                 Logger::log("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", Logger::DEBUG);
832                                 $update = true;
833                         }
834                 }
835
836                 if ($update) {
837                         Logger::log("Update gcontact for ".$contact["url"], Logger::DEBUG);
838                         $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
839                                         Strings::normaliseLink($contact["url"]), $contact["generation"]];
840                         $contact["updated"] = DateTimeFormat::utc($contact["updated"]);
841
842                         $updated = ['photo' => $contact['photo'], 'name' => $contact['name'],
843                                         'nick' => $contact['nick'], 'addr' => $contact['addr'],
844                                         'network' => $contact['network'], 'birthday' => $contact['birthday'],
845                                         'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
846                                         'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
847                                         'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
848                                         'notify' => $contact['notify'], 'url' => $contact['url'],
849                                         'location' => $contact['location'], 'about' => $contact['about'],
850                                         'generation' => $contact['generation'], 'updated' => $contact['updated'],
851                                         'server_url' => $contact['server_url'], 'connect' => $contact['connect']];
852
853                         DBA::update('gcontact', $updated, $condition, $fields);
854
855                         // Now update the contact entry with the user id "0" as well.
856                         // This is used for the shadow copies of public items.
857                         /// @todo Check if we really should do this.
858                         // The quality of the gcontact table is mostly lower than the public contact
859                         $public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => Strings::normaliseLink($contact["url"]), 'uid' => 0]);
860                         if (DBA::isResult($public_contact)) {
861                                 Logger::log("Update public contact ".$public_contact["id"], Logger::DEBUG);
862
863                                 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
864
865                                 $fields = ['name', 'nick', 'addr',
866                                                 'network', 'bd', 'gender',
867                                                 'keywords', 'alias', 'contact-type',
868                                                 'url', 'location', 'about'];
869                                 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
870
871                                 // Update it with the current values
872                                 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
873                                                 'addr' => $contact['addr'], 'network' => $contact['network'],
874                                                 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
875                                                 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
876                                                 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
877                                                 'location' => $contact['location'], 'about' => $contact['about']];
878
879                                 // Don't update the birthday field if not set or invalid
880                                 if (empty($contact['birthday']) || ($contact['birthday'] <= DBA::NULL_DATE)) {
881                                         unset($fields['bd']);
882                                 }
883
884
885                                 DBA::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
886                         }
887                 }
888
889                 return $gcontact_id;
890         }
891
892         /**
893          * @brief Updates the gcontact entry from probe
894          *
895          * @param string $url profile link
896          * @return void
897          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
898          * @throws \ImagickException
899          */
900         public static function updateFromProbe($url)
901         {
902                 $data = Probe::uri($url);
903
904                 if (in_array($data["network"], [Protocol::PHANTOM])) {
905                         Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
906                         return;
907                 }
908
909                 $data["server_url"] = $data["baseurl"];
910
911                 self::update($data);
912         }
913
914         /**
915          * @brief Update the gcontact entry for a given user id
916          *
917          * @param int $uid User ID
918          * @return bool
919          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
920          * @throws \ImagickException
921          */
922         public static function updateForUser($uid)
923         {
924                 $r = q(
925                         "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
926                                 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
927                                 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
928                                 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
929                                 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
930                         FROM `profile`
931                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
932                                 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
933                         WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
934                         intval($uid)
935                 );
936
937                 if (!DBA::isResult($r)) {
938                         Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
939                         return false;
940                 }
941
942                 $location = Profile::formatLocation(
943                         ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
944                 );
945
946                 // The "addr" field was added in 3.4.3 so it can be empty for older users
947                 if ($r[0]["addr"] != "") {
948                         $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
949                 } else {
950                         $addr = $r[0]["addr"];
951                 }
952
953                 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
954                                 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
955                                 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
956                                 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
957                                 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
958                                 "nick" => $r[0]["nickname"], "addr" => $addr,
959                                 "connect" => $addr, "server_url" => System::baseUrl(),
960                                 "generation" => 1, "network" => Protocol::DFRN];
961
962                 self::update($gcontact);
963         }
964
965         /**
966          * @brief Fetches users of given GNU Social server
967          *
968          * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
969          *
970          * @param string $server Server address
971          * @return bool
972          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
973          * @throws \ImagickException
974          */
975         public static function fetchGsUsers($server)
976         {
977                 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
978
979                 $url = $server."/main/statistics";
980
981                 $curlResult = Network::curl($url);
982                 if (!$curlResult->isSuccess()) {
983                         return false;
984                 }
985
986                 $statistics = json_decode($curlResult->getBody());
987
988                 if (!empty($statistics->config->instance_address)) {
989                         if (!empty($statistics->config->instance_with_ssl)) {
990                                 $server = "https://";
991                         } else {
992                                 $server = "http://";
993                         }
994
995                         $server .= $statistics->config->instance_address;
996
997                         $hostname = $statistics->config->instance_address;
998                 } elseif (!empty($statistics->instance_address)) {
999                         if (!empty($statistics->instance_with_ssl)) {
1000                                 $server = "https://";
1001                         } else {
1002                                 $server = "http://";
1003                         }
1004
1005                         $server .= $statistics->instance_address;
1006
1007                         $hostname = $statistics->instance_address;
1008                 }
1009
1010                 if (!empty($statistics->users)) {
1011                         foreach ($statistics->users as $nick => $user) {
1012                                 $profile_url = $server."/".$user->nickname;
1013
1014                                 $contact = ["url" => $profile_url,
1015                                                 "name" => $user->fullname,
1016                                                 "addr" => $user->nickname."@".$hostname,
1017                                                 "nick" => $user->nickname,
1018                                                 "network" => Protocol::OSTATUS,
1019                                                 "photo" => System::baseUrl()."/images/person-300.jpg"];
1020
1021                                 if (isset($user->bio)) {
1022                                         $contact["about"] = $user->bio;
1023                                 }
1024
1025                                 self::getId($contact);
1026                         }
1027                 }
1028         }
1029
1030         /**
1031          * @brief Asking GNU Social server on a regular base for their user data
1032          * @return void
1033          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1034          * @throws \ImagickException
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                         DBA::escape(Protocol::OSTATUS),
1045                         DBA::escape($last_update)
1046                 );
1047
1048                 if (!DBA::isResult($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'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1055                 }
1056         }
1057
1058         /**
1059          * @return string
1060          * @throws Exception
1061          */
1062         public static function getRandomUrl()
1063         {
1064                 $r = q(
1065                         "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1066                                         AND `last_contact` >= `last_failure`
1067                                         AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1068                                 ORDER BY rand() LIMIT 1",
1069                         DBA::escape(Protocol::DFRN)
1070                 );
1071
1072                 if (DBA::isResult($r)) {
1073                         return dirname($r[0]['url']);
1074                 }
1075
1076                 return '';
1077         }
1078 }