]> git.mxchange.org Git - friendica.git/blob - src/Model/GContact.php
4fb766193fb28335ae16cceee444617c92278b59
[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 (empty($gcontact["network"]) || in_array($gcontact["network"], Protocol::FEDERATED)) {
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::FEDERATED)) {
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::FEDERATED)) {
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
856                 return $gcontact_id;
857         }
858
859         /**
860          * @brief Updates the gcontact entry from a given public contact id
861          *
862          * @param integer $cid contact id
863          * @return void
864          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
865          * @throws \ImagickException
866          */
867         public static function updateFromPublicContactID($cid)
868         {
869                 self::updateFromPublicContact(['id' => $cid]);
870         }
871
872         /**
873          * @brief Updates the gcontact entry from a given public contact url
874          *
875          * @param string $url contact url
876          * @return void
877          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
878          * @throws \ImagickException
879          */
880         public static function updateFromPublicContactURL($url)
881         {
882                 self::updateFromPublicContact(['nurl' => Strings::normaliseLink($url)]);
883         }
884
885         /**
886          * @brief Helper function for updateFromPublicContactID and updateFromPublicContactURL
887          *
888          * @param array $condition contact condition
889          * @return void
890          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
891          * @throws \ImagickException
892          */
893         private static function updateFromPublicContact($condition)
894         {
895                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender',
896                         'bd', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archive', 'term-date',
897                         'created', 'updated', 'avatar', 'success_update', 'failure_update', 'forum', 'prv'];
898                 $contact = DBA::selectFirst('contact', $fields, array_merge($condition, ['uid' => 0, 'network' => Protocol::FEDERATED]));
899                 if (!DBA::isResult($contact)) {
900                         return;
901                 }
902
903                 // These fields cannot be updated, since they don't exist in the contact table
904                 // hide, nsfw, server_url
905                 // "connect" does exist, but seems to contain the same as "addr"
906
907                 $fields = ['name', 'nick', 'url', 'nurl', 'location', 'about', 'keywords', 'gender', 'generation',
908                         'birthday', 'contact-type', 'network', 'addr', 'notify', 'alias', 'archived', 'archive_date',
909                         'created', 'updated', 'photo', 'last_contact', 'last_failure', 'community', 'connect'];
910
911                 $old_gcontact = DBA::selectFirst('gcontact', $fields, ['nurl' => $contact['nurl']]);
912                 $do_insert = !DBA::isResult($old_gcontact);
913                 if ($do_insert) {
914                         $old_gcontact = [];
915                 }
916
917                 $gcontact = $contact;
918
919                 // These fields are having different names but the same content
920                 $gcontact['archived'] = $gcontact['archive'];
921                 unset($gcontact['archive']);
922                 $gcontact['archive_date'] = $gcontact['term-date'];
923                 unset($gcontact['term-date']);
924                 $gcontact['birthday'] = $gcontact['bd'];
925                 unset($gcontact['bd']);
926                 $gcontact['photo'] = $gcontact['avatar'];
927                 unset($gcontact['avatar']);
928                 $gcontact['last_contact'] = $gcontact['success_update'];
929                 unset($gcontact['success_update']);
930                 $gcontact['last_failure'] = $gcontact['failure_update'];
931                 unset($gcontact['failure_update']);
932                 $gcontact['community'] = ($gcontact['forum'] || $gcontact['prv']);
933                 unset($gcontact['forum']);
934                 unset($gcontact['prv']);
935
936                 foreach (['last_contact', 'last_failure', 'updated'] as $field) {
937                         if (!empty($old_gcontact[$field]) && ($old_gcontact[$field] >= $gcontact[$field])) {
938                                 unset($gcontact[$field]);
939                         }
940                 }
941
942                 if (!$gcontact['archived']) {
943                         $gcontact['archive_date'] = DBA::NULL_DATETIME;
944                 }
945
946                 if (!empty($old_gcontact['created']) && ($old_gcontact['created'] > DBA::NULL_DATETIME)
947                         && ($old_gcontact['created'] <= $gcontact['created'])) {
948                         unset($gcontact['created']);
949                 }
950
951                 if (empty($gcontact['birthday']) && ($gcontact['birthday'] <= DBA::NULL_DATETIME)) {
952                         unset($gcontact['birthday']);
953                 }
954
955                 if (empty($old_gcontact['generation']) || ($old_gcontact['generation'] > 2)) {
956                         $gcontact['generation'] = 2; // We fetched the data directly from the other server
957                 }
958
959                 if (!$do_insert) {
960                         DBA::update('gcontact', $gcontact, ['nurl' => $contact['nurl']], $old_gcontact);
961                 } elseif (!$gcontact['archived']) {
962                         DBA::insert('gcontact', $gcontact);
963                 }
964         }
965
966         /**
967          * @brief Updates the gcontact entry from probe
968          *
969          * @param string  $url   profile link
970          * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
971          * @return void
972          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
973          * @throws \ImagickException
974          */
975         public static function updateFromProbe($url, $force = false)
976         {
977                 $data = Probe::uri($url, $force);
978
979                 if (in_array($data["network"], [Protocol::PHANTOM])) {
980                         Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
981                         return;
982                 }
983
984                 $data["server_url"] = $data["baseurl"];
985
986                 self::update($data);
987         }
988
989         /**
990          * @brief Update the gcontact entry for a given user id
991          *
992          * @param int $uid User ID
993          * @return bool
994          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995          * @throws \ImagickException
996          */
997         public static function updateForUser($uid)
998         {
999                 $r = q(
1000                         "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
1001                                 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
1002                                 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
1003                                 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
1004                                 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
1005                         FROM `profile`
1006                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
1007                                 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
1008                         WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
1009                         intval($uid)
1010                 );
1011
1012                 if (!DBA::isResult($r)) {
1013                         Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
1014                         return false;
1015                 }
1016
1017                 $location = Profile::formatLocation(
1018                         ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
1019                 );
1020
1021                 // The "addr" field was added in 3.4.3 so it can be empty for older users
1022                 if ($r[0]["addr"] != "") {
1023                         $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
1024                 } else {
1025                         $addr = $r[0]["addr"];
1026                 }
1027
1028                 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
1029                                 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
1030                                 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
1031                                 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
1032                                 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
1033                                 "nick" => $r[0]["nickname"], "addr" => $addr,
1034                                 "connect" => $addr, "server_url" => System::baseUrl(),
1035                                 "generation" => 1, "network" => Protocol::DFRN];
1036
1037                 self::update($gcontact);
1038         }
1039
1040         /**
1041          * @brief Fetches users of given GNU Social server
1042          *
1043          * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
1044          *
1045          * @param string $server Server address
1046          * @return bool
1047          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1048          * @throws \ImagickException
1049          */
1050         public static function fetchGsUsers($server)
1051         {
1052                 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
1053
1054                 $url = $server."/main/statistics";
1055
1056                 $curlResult = Network::curl($url);
1057                 if (!$curlResult->isSuccess()) {
1058                         return false;
1059                 }
1060
1061                 $statistics = json_decode($curlResult->getBody());
1062
1063                 if (!empty($statistics->config->instance_address)) {
1064                         if (!empty($statistics->config->instance_with_ssl)) {
1065                                 $server = "https://";
1066                         } else {
1067                                 $server = "http://";
1068                         }
1069
1070                         $server .= $statistics->config->instance_address;
1071
1072                         $hostname = $statistics->config->instance_address;
1073                 } elseif (!empty($statistics->instance_address)) {
1074                         if (!empty($statistics->instance_with_ssl)) {
1075                                 $server = "https://";
1076                         } else {
1077                                 $server = "http://";
1078                         }
1079
1080                         $server .= $statistics->instance_address;
1081
1082                         $hostname = $statistics->instance_address;
1083                 }
1084
1085                 if (!empty($statistics->users)) {
1086                         foreach ($statistics->users as $nick => $user) {
1087                                 $profile_url = $server."/".$user->nickname;
1088
1089                                 $contact = ["url" => $profile_url,
1090                                                 "name" => $user->fullname,
1091                                                 "addr" => $user->nickname."@".$hostname,
1092                                                 "nick" => $user->nickname,
1093                                                 "network" => Protocol::OSTATUS,
1094                                                 "photo" => System::baseUrl()."/images/person-300.jpg"];
1095
1096                                 if (isset($user->bio)) {
1097                                         $contact["about"] = $user->bio;
1098                                 }
1099
1100                                 self::getId($contact);
1101                         }
1102                 }
1103         }
1104
1105         /**
1106          * @brief Asking GNU Social server on a regular base for their user data
1107          * @return void
1108          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109          * @throws \ImagickException
1110          */
1111         public static function discoverGsUsers()
1112         {
1113                 $requery_days = intval(Config::get("system", "poco_requery_days"));
1114
1115                 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1116
1117                 $r = DBA::select('gserver', ['nurl', 'url'], [
1118                         '`network` = ?
1119                         AND `last_contact` >= `last_failure`
1120                         AND `last_poco_query` < ?',
1121                         Protocol::OSTATUS,
1122                         $last_update
1123                 ], [
1124                         'limit' => 5,
1125                         'order' => ['RAND()']
1126                 ]);
1127
1128                 if (!DBA::isResult($r)) {
1129                         return;
1130                 }
1131
1132                 foreach ($r as $server) {
1133                         self::fetchGsUsers($server["url"]);
1134                         q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1135                 }
1136         }
1137
1138         /**
1139          * Returns a random, global contact of the current node
1140          *
1141          * @return string The profile URL
1142          * @throws Exception
1143          */
1144         public static function getRandomUrl()
1145         {
1146                 $r = DBA::selectFirst('gcontact', ['url'], [
1147                         '`network` = ? 
1148                         AND `last_contact` >= `last_failure`  
1149                         AND `updated` > ?',
1150                         Protocol::DFRN,
1151                         DateTimeFormat::utc('now - 1 month'),
1152                 ], ['order' => ['RAND()']]);
1153
1154                 if (DBA::isResult($r)) {
1155                         return $r['url'];
1156                 }
1157
1158                 return '';
1159         }
1160 }