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