4 * @file src/Model/GlobalContact.php
5 * @brief This file includes the GlobalContact class with directory related functions
7 namespace Friendica\Model;
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;
21 require_once 'include/dba.php';
24 * @brief This class handles GlobalContact related functions
29 * @brief Search global contact table by nick or name
31 * @param string $search Name or nick
32 * @param string $mode Search mode (e.g. "community")
34 * @return array with search results
36 public static function searchByName($search, $mode = '')
42 // check supported networks
43 if (Config::get('system', 'diaspora_enabled')) {
44 $diaspora = Protocol::DIASPORA;
46 $diaspora = Protocol::DFRN;
49 if (!Config::get('system', 'ostatus_disabled')) {
50 $ostatus = Protocol::OSTATUS;
52 $ostatus = Protocol::DFRN;
55 // check if we search only communities or every contact
56 if ($mode === "community") {
57 $extra_sql = " AND `community`";
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
73 while ($result = DBA::fetch($results)) {
74 $urlparts = parse_url($result["nurl"]);
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'])) {
82 $gcontacts[] = Contact::getDetailsByURL($result["nurl"], local_user());
88 * @brief Link the gcontact entry with user, contact and global contact
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
96 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
102 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
103 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
107 * @brief Sanitize the given gcontact data
109 * @param array $gcontact array with gcontact data
114 * 1: Profiles on this server
115 * 2: Contacts of profiles on this server
116 * 3: Contacts of contacts of profiles on this server
118 * @return array $gcontact
120 public static function sanitize($gcontact)
122 if ($gcontact['url'] == "") {
123 throw new Exception('URL is empty');
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.");
131 if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
132 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
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'] = "";
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']);
146 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
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'] = "";
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"];
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"];
171 $gcontact['server_url'] = '';
172 $gcontact['network'] = '';
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"];
180 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
181 $gcontact['updated'] = $gcnt["updated"];
183 if (!isset($gcontact['server_url']) && (normalise_link($gcnt["server_url"]) != normalise_link($gcnt["url"]))) {
184 $gcontact['server_url'] = $gcnt["server_url"];
186 if (!isset($gcontact['addr'])) {
187 $gcontact['addr'] = $gcnt["addr"];
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)
194 $data = Probe::uri($gcontact['url']);
196 if ($data["network"] == Protocol::PHANTOM) {
197 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
200 $orig_profile = $gcontact['url'];
202 $gcontact["server_url"] = $data["baseurl"];
204 $gcontact = array_merge($gcontact, $data);
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)]);
214 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
215 throw new Exception('No name and photo for URL '.$gcontact['url']);
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']);
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']);
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;
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'] = "";
241 * @param integer $uid id
242 * @param integer $cid id
245 public static function countCommonFriends($uid, $cid)
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 ) ",
260 // Logger::log("countCommonFriends: $uid $cid {$r[0]['total']}");
261 if (DBA::isResult($r)) {
262 return $r[0]['total'];
268 * @param integer $uid id
269 * @param integer $zcid zcid
272 public static function countCommonFriendsZcid($uid, $zcid)
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 ) ",
283 if (DBA::isResult($r)) {
284 return $r[0]['total'];
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
298 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
301 $sql_extra = " order by rand() ";
303 $sql_extra = " order by `gcontact`.`name` asc ";
307 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
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",
324 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
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
336 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
339 $sql_extra = " order by rand() ";
341 $sql_extra = " order by `gcontact`.`name` asc ";
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",
356 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
361 * @param integer $uid user
362 * @param integer $cid cid
365 public static function countAllFriends($uid, $cid)
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`))",
376 if (DBA::isResult($r)) {
377 return $r[0]['total'];
384 * @param integer $uid user
385 * @param integer $cid cid
386 * @param integer $start optional, default 0
387 * @param integer $limit optional, default 80
390 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
393 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
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 ",
407 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
412 * @param object $uid user
413 * @param integer $start optional, default 0
414 * @param integer $limit optional, default 80
417 public static function suggestionQuery($uid, $start = 0, $limit = 80)
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.
427 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
428 //if (!is_null($list)) {
432 $network = [Protocol::DFRN];
434 if (Config::get('system', 'diaspora_enabled')) {
435 $network[] = Protocol::DIASPORA;
438 if (!Config::get('system', 'ostatus_disabled')) {
439 $network[] = Protocol::OSTATUS;
442 $sql_network = implode("', '", $network);
443 $sql_network = "'".$sql_network."'";
445 /// @todo This query is really slow
446 // By now we cache the data for five minutes
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",
467 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
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.
472 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, Cache::FIVE_MINUTES);
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",
497 foreach ($r2 as $suggestion) {
498 $list[$suggestion["nurl"]] = $suggestion;
501 foreach ($r as $suggestion) {
502 $list[$suggestion["nurl"]] = $suggestion;
505 while (sizeof($list) > ($limit)) {
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.
513 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, Cache::FIVE_MINUTES);
520 public static function updateSuggestions()
526 /// @TODO Check if it is really neccessary to poll the own server
527 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
529 $done[] = System::baseUrl() . '/poco';
531 if (strlen(Config::get('system', 'directory'))) {
532 $x = Network::fetchUrl(get_server()."/pubsites");
534 $j = json_decode($x);
535 if (!empty($j->entries)) {
536 foreach ($j->entries as $entry) {
537 PortableContact::checkServer($entry->url);
539 $url = $entry->url . '/poco';
540 if (!in_array($url, $done)) {
541 PortableContact::loadWorker(0, 0, 0, $url);
549 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
551 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
552 DBA::escape(Protocol::DFRN),
553 DBA::escape(Protocol::DIASPORA)
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);
567 * @brief Removes unwanted parts from a contact url
569 * @param string $url Contact url
571 * @return string Contact url with the wanted parts
573 public static function cleanContactUrl($url)
575 $parts = parse_url($url);
577 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
581 $new_url = $parts["scheme"]."://".$parts["host"];
583 if (isset($parts["port"])) {
584 $new_url .= ":".$parts["port"];
587 if (isset($parts["path"])) {
588 $new_url .= $parts["path"];
591 if ($new_url != $url) {
592 Logger::log("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), Logger::DEBUG);
599 * @brief Replace alternate OStatus user format with the primary one
601 * @param array $contact contact array (called by reference)
604 public static function fixAlternateContactAddress(&$contact)
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"];
619 * @brief Fetch the gcontact id, add an entry if not existed
621 * @param array $contact contact array
623 * @return bool|int Returns false if not found, integer if contact was found
625 public static function getId($contact)
629 $last_failure_str = '';
630 $last_contact_str = '';
632 if (empty($contact["network"])) {
633 Logger::log("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
637 if (in_array($contact["network"], [Protocol::PHANTOM])) {
638 Logger::log("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
642 if ($contact["network"] == Protocol::STATUSNET) {
643 $contact["network"] = Protocol::OSTATUS;
646 // All new contacts are hidden by default
647 if (!isset($contact["hide"])) {
648 $contact["hide"] = true;
651 // Replace alternate OStatus user format with the primary one
652 self::fixAlternateContactAddress($contact);
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"]);
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"];
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)));
674 $contact['location'] = defaults($contact, 'location', '');
675 $contact['about'] = defaults($contact, 'about', '');
676 $contact['generation'] = defaults($contact, 'generation', 0);
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"])
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, ""]);
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"]);
714 * @brief Updates the gcontact table from a given array
716 * @param array $contact contact array
718 * @return bool|int Returns false if not found, integer if contact was found
720 public static function update($contact)
722 // Check for invalid "contact-type" value
723 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
724 $contact['contact-type'] = 0;
727 /// @todo update contact table as well
729 $gcontact_id = self::getId($contact);
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",
742 // Get all field names
744 foreach ($public_contact[0] as $field => $data) {
745 $fields[$field] = $data;
748 unset($fields["url"]);
749 unset($fields["updated"]);
750 unset($fields["hide"]);
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"]);
758 if (!empty($public_contact[0]["keywords"]) && ($public_contact[0]["keywords"] == "0")) {
759 $public_contact[0]["keywords"] = "";
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];
769 if (!isset($contact["hide"])) {
770 $contact["hide"] = $public_contact[0]["hide"];
773 $fields["hide"] = $public_contact[0]["hide"];
775 if ($contact["network"] == Protocol::STATUSNET) {
776 $contact["network"] = Protocol::OSTATUS;
779 // Replace alternate OStatus user format with the primary one
780 self::fixAlternateContactAddress($contact);
782 if (!isset($contact["updated"])) {
783 $contact["updated"] = DateTimeFormat::utcNow();
786 if ($contact["network"] == Protocol::TWITTER) {
787 $contact["server_url"] = 'http://twitter.com';
790 if ($contact["server_url"] == "") {
791 $data = Probe::uri($contact["url"]);
792 if ($data["network"] != Protocol::PHANTOM) {
793 $contact["server_url"] = $data['baseurl'];
796 $contact["server_url"] = normalise_link($contact["server_url"]);
799 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
800 $hostname = str_replace("http://", "", $contact["server_url"]);
801 $contact["addr"] = $contact["nick"]."@".$hostname;
804 // Check if any field changed
806 unset($fields["generation"]);
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);
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);
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"]);
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']];
839 DBA::update('gcontact', $updated, $condition, $fields);
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);
849 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
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"]]);
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']];
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']);
871 DBA::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
879 * @brief Updates the gcontact entry from probe
881 * @param string $url profile link
884 public static function updateFromProbe($url)
886 $data = Probe::uri($url);
888 if (in_array($data["network"], [Protocol::PHANTOM])) {
889 Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
893 $data["server_url"] = $data["baseurl"];
899 * @brief Update the gcontact entry for a given user id
901 * @param int $uid User ID
904 public static function updateForUser($uid)
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`
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`",
919 if (!DBA::isResult($r)) {
920 Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
924 $location = Profile::formatLocation(
925 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
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());
932 $addr = $r[0]["addr"];
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];
944 self::update($gcontact);
948 * @brief Fetches users of given GNU Social server
950 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
952 * @param string $server Server address
955 public static function fetchGsUsers($server)
957 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
959 $url = $server."/main/statistics";
961 $curlResult = Network::curl($url);
962 if (!$curlResult->isSuccess()) {
966 $statistics = json_decode($curlResult->getBody());
968 if (!empty($statistics->config)) {
969 if ($statistics->config->instance_with_ssl) {
970 $server = "https://";
975 $server .= $statistics->config->instance_address;
977 $hostname = $statistics->config->instance_address;
978 } elseif (!empty($statistics)) {
979 if ($statistics->instance_with_ssl) {
980 $server = "https://";
985 $server .= $statistics->instance_address;
987 $hostname = $statistics->instance_address;
990 if (!empty($statistics->users)) {
991 foreach ($statistics->users as $nick => $user) {
992 $profile_url = $server."/".$user->nickname;
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"];
1001 if (isset($user->bio)) {
1002 $contact["about"] = $user->bio;
1005 self::getId($contact);
1011 * @brief Asking GNU Social server on a regular base for their user data
1014 public static function discoverGsUsers()
1016 $requery_days = intval(Config::get("system", "poco_requery_days"));
1018 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
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)
1026 if (!DBA::isResult($r)) {
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"]));
1039 public static function getRandomUrl()
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)
1049 if (DBA::isResult($r)) {
1050 return dirname($r[0]['url']);