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;
20 use Friendica\Util\Strings;
23 * @brief This class handles GlobalContact related functions
28 * @brief Search global contact table by nick or name
30 * @param string $search Name or nick
31 * @param string $mode Search mode (e.g. "community")
33 * @return array with search results
34 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
97 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
103 $condition = ['cid' => $cid, 'uid' => $uid, 'gcid' => $gcid, 'zcid' => $zcid];
104 DBA::update('glink', ['updated' => DateTimeFormat::utcNow()], $condition, true);
108 * @brief Sanitize the given gcontact data
112 * 1: Profiles on this server
113 * 2: Contacts of profiles on this server
114 * 3: Contacts of contacts of profiles on this server
117 * @param array $gcontact array with gcontact data
118 * @return array $gcontact
121 public static function sanitize($gcontact)
123 if ($gcontact['url'] == "") {
124 throw new Exception('URL is empty');
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.");
132 if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
133 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
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'] = "";
142 // Assure that there are no parameter fragments in the profile url
143 if (in_array($gcontact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
144 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
147 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
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'] = "";
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"];
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"];
172 $gcontact['server_url'] = '';
173 $gcontact['network'] = '';
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"];
181 if ($gcontact['updated'] <= DBA::NULL_DATETIME) {
182 $gcontact['updated'] = $gcnt["updated"];
184 if (!isset($gcontact['server_url']) && (Strings::normaliseLink($gcnt["server_url"]) != Strings::normaliseLink($gcnt["url"]))) {
185 $gcontact['server_url'] = $gcnt["server_url"];
187 if (!isset($gcontact['addr'])) {
188 $gcontact['addr'] = $gcnt["addr"];
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)
195 $data = Probe::uri($gcontact['url']);
197 if ($data["network"] == Protocol::PHANTOM) {
198 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
201 $orig_profile = $gcontact['url'];
203 $gcontact["server_url"] = $data["baseurl"];
205 $gcontact = array_merge($gcontact, $data);
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)]);
215 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
216 throw new Exception('No name and photo for URL '.$gcontact['url']);
219 if (!in_array($gcontact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
220 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
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']);
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;
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'] = "";
242 * @param integer $uid id
243 * @param integer $cid id
247 public static function countCommonFriends($uid, $cid)
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 ) ",
262 // Logger::log("countCommonFriends: $uid $cid {$r[0]['total']}");
263 if (DBA::isResult($r)) {
264 return $r[0]['total'];
270 * @param integer $uid id
271 * @param integer $zcid zcid
275 public static function countCommonFriendsZcid($uid, $zcid)
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 ) ",
286 if (DBA::isResult($r)) {
287 return $r[0]['total'];
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
302 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
305 $sql_extra = " order by rand() ";
307 $sql_extra = " order by `gcontact`.`name` asc ";
311 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
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",
328 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
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
341 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
344 $sql_extra = " order by rand() ";
346 $sql_extra = " order by `gcontact`.`name` asc ";
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",
361 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
366 * @param integer $uid user
367 * @param integer $cid cid
371 public static function countAllFriends($uid, $cid)
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`))",
382 if (DBA::isResult($r)) {
383 return $r[0]['total'];
390 * @param integer $uid user
391 * @param integer $cid cid
392 * @param integer $start optional, default 0
393 * @param integer $limit optional, default 80
397 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
400 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
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 ",
414 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
419 * @param int $uid user
420 * @param integer $start optional, default 0
421 * @param integer $limit optional, default 80
423 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425 public static function suggestionQuery($uid, $start = 0, $limit = 80)
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.
435 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
436 //if (!is_null($list)) {
440 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
442 if (Config::get('system', 'diaspora_enabled')) {
443 $network[] = Protocol::DIASPORA;
446 if (!Config::get('system', 'ostatus_disabled')) {
447 $network[] = Protocol::OSTATUS;
450 $sql_network = implode("', '", $network);
451 $sql_network = "'".$sql_network."'";
453 /// @todo This query is really slow
454 // By now we cache the data for five minutes
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",
475 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
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.
480 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, Cache::FIVE_MINUTES);
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",
505 foreach ($r2 as $suggestion) {
506 $list[$suggestion["nurl"]] = $suggestion;
509 foreach ($r as $suggestion) {
510 $list[$suggestion["nurl"]] = $suggestion;
513 while (sizeof($list) > ($limit)) {
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.
521 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, Cache::FIVE_MINUTES);
527 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529 public static function updateSuggestions()
533 /// @TODO Check if it is really neccessary to poll the own server
534 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
536 $done[] = System::baseUrl() . '/poco';
538 if (strlen(Config::get('system', 'directory'))) {
539 $x = Network::fetchUrl(get_server()."/pubsites");
541 $j = json_decode($x);
542 if (!empty($j->entries)) {
543 foreach ($j->entries as $entry) {
544 PortableContact::checkServer($entry->url);
546 $url = $entry->url . '/poco';
547 if (!in_array($url, $done)) {
548 PortableContact::loadWorker(0, 0, 0, $url);
556 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
558 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
559 DBA::escape(Protocol::DFRN),
560 DBA::escape(Protocol::DIASPORA)
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);
574 * @brief Removes unwanted parts from a contact url
576 * @param string $url Contact url
578 * @return string Contact url with the wanted parts
581 public static function cleanContactUrl($url)
583 $parts = parse_url($url);
585 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
589 $new_url = $parts["scheme"]."://".$parts["host"];
591 if (isset($parts["port"])) {
592 $new_url .= ":".$parts["port"];
595 if (isset($parts["path"])) {
596 $new_url .= $parts["path"];
599 if ($new_url != $url) {
600 Logger::log("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), Logger::DEBUG);
607 * @brief Replace alternate OStatus user format with the primary one
609 * @param array $contact contact array (called by reference)
611 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
612 * @throws \ImagickException
614 public static function fixAlternateContactAddress(&$contact)
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"];
629 * @brief Fetch the gcontact id, add an entry if not existed
631 * @param array $contact contact array
633 * @return bool|int Returns false if not found, integer if contact was found
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635 * @throws \ImagickException
637 public static function getId($contact)
641 $last_failure_str = '';
642 $last_contact_str = '';
644 if (empty($contact["network"])) {
645 Logger::log("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
649 if (in_array($contact["network"], [Protocol::PHANTOM])) {
650 Logger::log("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
654 if ($contact["network"] == Protocol::STATUSNET) {
655 $contact["network"] = Protocol::OSTATUS;
658 // All new contacts are hidden by default
659 if (!isset($contact["hide"])) {
660 $contact["hide"] = true;
663 // Replace alternate OStatus user format with the primary one
664 self::fixAlternateContactAddress($contact);
666 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
667 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
668 $contact["url"] = self::cleanContactUrl($contact["url"]);
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"];
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)));
686 $contact['location'] = defaults($contact, 'location', '');
687 $contact['about'] = defaults($contact, 'about', '');
688 $contact['generation'] = defaults($contact, 'generation', 0);
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"])
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, ""]);
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"]);
726 * @brief Updates the gcontact table from a given array
728 * @param array $contact contact array
730 * @return bool|int Returns false if not found, integer if contact was found
731 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
732 * @throws \ImagickException
734 public static function update($contact)
736 // Check for invalid "contact-type" value
737 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
738 $contact['contact-type'] = 0;
741 /// @todo update contact table as well
743 $gcontact_id = self::getId($contact);
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",
756 // Get all field names
758 foreach ($public_contact[0] as $field => $data) {
759 $fields[$field] = $data;
762 unset($fields["url"]);
763 unset($fields["updated"]);
764 unset($fields["hide"]);
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"]);
772 if (!empty($public_contact[0]["keywords"]) && ($public_contact[0]["keywords"] == "0")) {
773 $public_contact[0]["keywords"] = "";
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];
783 if (!isset($contact["hide"])) {
784 $contact["hide"] = $public_contact[0]["hide"];
787 $fields["hide"] = $public_contact[0]["hide"];
789 if ($contact["network"] == Protocol::STATUSNET) {
790 $contact["network"] = Protocol::OSTATUS;
793 // Replace alternate OStatus user format with the primary one
794 self::fixAlternateContactAddress($contact);
796 if (!isset($contact["updated"])) {
797 $contact["updated"] = DateTimeFormat::utcNow();
800 if ($contact["network"] == Protocol::TWITTER) {
801 $contact["server_url"] = 'http://twitter.com';
804 if ($contact["server_url"] == "") {
805 $data = Probe::uri($contact["url"]);
806 if ($data["network"] != Protocol::PHANTOM) {
807 $contact["server_url"] = $data['baseurl'];
810 $contact["server_url"] = Strings::normaliseLink($contact["server_url"]);
813 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
814 $hostname = str_replace("http://", "", $contact["server_url"]);
815 $contact["addr"] = $contact["nick"]."@".$hostname;
818 // Check if any field changed
820 unset($fields["generation"]);
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);
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);
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"]);
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']];
853 DBA::update('gcontact', $updated, $condition, $fields);
855 // Now update the contact entry with the user id "0" as well.
856 // This is used for the shadow copies of public items.
857 /// @todo Check if we really should do this.
858 // The quality of the gcontact table is mostly lower than the public contact
859 $public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => Strings::normaliseLink($contact["url"]), 'uid' => 0]);
860 if (DBA::isResult($public_contact)) {
861 Logger::log("Update public contact ".$public_contact["id"], Logger::DEBUG);
863 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
865 $fields = ['name', 'nick', 'addr',
866 'network', 'bd', 'gender',
867 'keywords', 'alias', 'contact-type',
868 'url', 'location', 'about'];
869 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
871 // Update it with the current values
872 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
873 'addr' => $contact['addr'], 'network' => $contact['network'],
874 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
875 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
876 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
877 'location' => $contact['location'], 'about' => $contact['about']];
879 // Don't update the birthday field if not set or invalid
880 if (empty($contact['birthday']) || ($contact['birthday'] <= DBA::NULL_DATE)) {
881 unset($fields['bd']);
885 DBA::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
893 * @brief Updates the gcontact entry from probe
895 * @param string $url profile link
897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
898 * @throws \ImagickException
900 public static function updateFromProbe($url)
902 $data = Probe::uri($url);
904 if (in_array($data["network"], [Protocol::PHANTOM])) {
905 Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
909 $data["server_url"] = $data["baseurl"];
915 * @brief Update the gcontact entry for a given user id
917 * @param int $uid User ID
919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
920 * @throws \ImagickException
922 public static function updateForUser($uid)
925 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
926 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
927 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
928 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
929 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
931 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
932 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
933 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
937 if (!DBA::isResult($r)) {
938 Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
942 $location = Profile::formatLocation(
943 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
946 // The "addr" field was added in 3.4.3 so it can be empty for older users
947 if ($r[0]["addr"] != "") {
948 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
950 $addr = $r[0]["addr"];
953 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
954 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
955 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
956 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
957 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
958 "nick" => $r[0]["nickname"], "addr" => $addr,
959 "connect" => $addr, "server_url" => System::baseUrl(),
960 "generation" => 1, "network" => Protocol::DFRN];
962 self::update($gcontact);
966 * @brief Fetches users of given GNU Social server
968 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
970 * @param string $server Server address
972 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
973 * @throws \ImagickException
975 public static function fetchGsUsers($server)
977 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
979 $url = $server."/main/statistics";
981 $curlResult = Network::curl($url);
982 if (!$curlResult->isSuccess()) {
986 $statistics = json_decode($curlResult->getBody());
988 if (!empty($statistics->config->instance_address)) {
989 if (!empty($statistics->config->instance_with_ssl)) {
990 $server = "https://";
995 $server .= $statistics->config->instance_address;
997 $hostname = $statistics->config->instance_address;
998 } elseif (!empty($statistics->instance_address)) {
999 if (!empty($statistics->instance_with_ssl)) {
1000 $server = "https://";
1002 $server = "http://";
1005 $server .= $statistics->instance_address;
1007 $hostname = $statistics->instance_address;
1010 if (!empty($statistics->users)) {
1011 foreach ($statistics->users as $nick => $user) {
1012 $profile_url = $server."/".$user->nickname;
1014 $contact = ["url" => $profile_url,
1015 "name" => $user->fullname,
1016 "addr" => $user->nickname."@".$hostname,
1017 "nick" => $user->nickname,
1018 "network" => Protocol::OSTATUS,
1019 "photo" => System::baseUrl()."/images/person-300.jpg"];
1021 if (isset($user->bio)) {
1022 $contact["about"] = $user->bio;
1025 self::getId($contact);
1031 * @brief Asking GNU Social server on a regular base for their user data
1033 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1034 * @throws \ImagickException
1036 public static function discoverGsUsers()
1038 $requery_days = intval(Config::get("system", "poco_requery_days"));
1040 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1042 $r = DBA::select('gserver', ['nurl', 'url'], [
1044 AND `last_contact` >= `last_failure`
1045 AND `last_poco_query` < ?',
1050 'order' => ['RAND()']
1053 if (!DBA::isResult($r)) {
1057 foreach ($r as $server) {
1058 self::fetchGsUsers($server["url"]);
1059 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1064 * Returns a random, global contact of the current node
1066 * @return string The profile URL
1069 public static function getRandomUrl()
1071 $r = DBA::selectFirst('gcontact', ['url'], [
1073 AND `last_contact` >= `last_failure`
1076 DateTimeFormat::utc('now - 1 month'),
1077 ], ['order' => ['RAND()']]);
1079 if (DBA::isResult($r)) {