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
246 public static function countCommonFriends($uid, $cid)
249 "SELECT count(*) as `total`
250 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
251 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
252 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
253 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
254 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
261 // Logger::log("countCommonFriends: $uid $cid {$r[0]['total']}");
262 if (DBA::isResult($r)) {
263 return $r[0]['total'];
269 * @param integer $uid id
270 * @param integer $zcid zcid
273 public static function countCommonFriendsZcid($uid, $zcid)
276 "SELECT count(*) as `total`
277 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
278 where `glink`.`zcid` = %d
279 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
284 if (DBA::isResult($r)) {
285 return $r[0]['total'];
292 * @param integer $uid user
293 * @param integer $cid cid
294 * @param integer $start optional, default 0
295 * @param integer $limit optional, default 9999
296 * @param boolean $shuffle optional, default false
299 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
302 $sql_extra = " order by rand() ";
304 $sql_extra = " order by `gcontact`.`name` asc ";
308 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
310 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
311 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
312 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
313 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
314 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
315 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
316 $sql_extra LIMIT %d, %d",
325 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
330 * @param integer $uid user
331 * @param integer $zcid zcid
332 * @param integer $start optional, default 0
333 * @param integer $limit optional, default 9999
334 * @param boolean $shuffle optional, default false
337 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
340 $sql_extra = " order by rand() ";
342 $sql_extra = " order by `gcontact`.`name` asc ";
347 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
348 where `glink`.`zcid` = %d
349 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
350 $sql_extra limit %d, %d",
357 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
362 * @param integer $uid user
363 * @param integer $cid cid
366 public static function countAllFriends($uid, $cid)
369 "SELECT count(*) as `total`
370 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
371 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
372 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
377 if (DBA::isResult($r)) {
378 return $r[0]['total'];
385 * @param integer $uid user
386 * @param integer $cid cid
387 * @param integer $start optional, default 0
388 * @param integer $limit optional, default 80
391 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
394 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
396 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
397 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
398 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
399 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
400 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
408 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
413 * @param int $uid user
414 * @param integer $start optional, default 0
415 * @param integer $limit optional, default 80
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 public static function suggestionQuery($uid, $start = 0, $limit = 80)
426 * Uncommented because the result of the queries are to big to store it in the cache.
427 * We need to decide if we want to change the db column type or if we want to delete it.
429 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
430 //if (!is_null($list)) {
434 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
436 if (Config::get('system', 'diaspora_enabled')) {
437 $network[] = Protocol::DIASPORA;
440 if (!Config::get('system', 'ostatus_disabled')) {
441 $network[] = Protocol::OSTATUS;
444 $sql_network = implode("', '", $network);
445 $sql_network = "'".$sql_network."'";
447 /// @todo This query is really slow
448 // By now we cache the data for five minutes
450 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
451 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
452 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
453 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
454 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
455 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
456 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
457 AND `gcontact`.`network` IN (%s)
458 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
469 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
471 * Uncommented because the result of the queries are to big to store it in the cache.
472 * We need to decide if we want to change the db column type or if we want to delete it.
474 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, Cache::FIVE_MINUTES);
480 "SELECT gcontact.* FROM gcontact
481 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
482 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
483 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
484 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
485 AND `gcontact`.`updated` >= '%s'
486 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
487 AND `gcontact`.`network` IN (%s)
488 ORDER BY rand() LIMIT %d, %d",
499 foreach ($r2 as $suggestion) {
500 $list[$suggestion["nurl"]] = $suggestion;
503 foreach ($r as $suggestion) {
504 $list[$suggestion["nurl"]] = $suggestion;
507 while (sizeof($list) > ($limit)) {
512 * Uncommented because the result of the queries are to big to store it in the cache.
513 * We need to decide if we want to change the db column type or if we want to delete it.
515 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, Cache::FIVE_MINUTES);
521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
523 public static function updateSuggestions()
529 /// @TODO Check if it is really neccessary to poll the own server
530 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
532 $done[] = System::baseUrl() . '/poco';
534 if (strlen(Config::get('system', 'directory'))) {
535 $x = Network::fetchUrl(get_server()."/pubsites");
537 $j = json_decode($x);
538 if (!empty($j->entries)) {
539 foreach ($j->entries as $entry) {
540 PortableContact::checkServer($entry->url);
542 $url = $entry->url . '/poco';
543 if (!in_array($url, $done)) {
544 PortableContact::loadWorker(0, 0, 0, $url);
552 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
554 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
555 DBA::escape(Protocol::DFRN),
556 DBA::escape(Protocol::DIASPORA)
559 if (DBA::isResult($r)) {
560 foreach ($r as $rr) {
561 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
562 if (! in_array($base, $done)) {
563 PortableContact::loadWorker(0, 0, 0, $base);
570 * @brief Removes unwanted parts from a contact url
572 * @param string $url Contact url
574 * @return string Contact url with the wanted parts
577 public static function cleanContactUrl($url)
579 $parts = parse_url($url);
581 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
585 $new_url = $parts["scheme"]."://".$parts["host"];
587 if (isset($parts["port"])) {
588 $new_url .= ":".$parts["port"];
591 if (isset($parts["path"])) {
592 $new_url .= $parts["path"];
595 if ($new_url != $url) {
596 Logger::log("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), Logger::DEBUG);
603 * @brief Replace alternate OStatus user format with the primary one
605 * @param array $contact contact array (called by reference)
607 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
608 * @throws \ImagickException
610 public static function fixAlternateContactAddress(&$contact)
612 if (($contact["network"] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
613 $data = Probe::uri($contact["url"]);
614 if ($contact["network"] == Protocol::OSTATUS) {
615 Logger::log("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
616 $contact["url"] = $data["url"];
617 $contact["addr"] = $data["addr"];
618 $contact["alias"] = $data["alias"];
619 $contact["server_url"] = $data["baseurl"];
625 * @brief Fetch the gcontact id, add an entry if not existed
627 * @param array $contact contact array
629 * @return bool|int Returns false if not found, integer if contact was found
630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
631 * @throws \ImagickException
633 public static function getId($contact)
637 $last_failure_str = '';
638 $last_contact_str = '';
640 if (empty($contact["network"])) {
641 Logger::log("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
645 if (in_array($contact["network"], [Protocol::PHANTOM])) {
646 Logger::log("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
650 if ($contact["network"] == Protocol::STATUSNET) {
651 $contact["network"] = Protocol::OSTATUS;
654 // All new contacts are hidden by default
655 if (!isset($contact["hide"])) {
656 $contact["hide"] = true;
659 // Replace alternate OStatus user format with the primary one
660 self::fixAlternateContactAddress($contact);
662 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
663 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
664 $contact["url"] = self::cleanContactUrl($contact["url"]);
667 DBA::lock('gcontact');
668 $fields = ['id', 'last_contact', 'last_failure', 'network'];
669 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact["url"])]);
670 if (DBA::isResult($gcnt)) {
671 $gcontact_id = $gcnt["id"];
673 // Update every 90 days
674 if (in_array($gcnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
675 $last_failure_str = $gcnt["last_failure"];
676 $last_failure = strtotime($gcnt["last_failure"]);
677 $last_contact_str = $gcnt["last_contact"];
678 $last_contact = strtotime($gcnt["last_contact"]);
679 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
682 $contact['location'] = defaults($contact, 'location', '');
683 $contact['about'] = defaults($contact, 'about', '');
684 $contact['generation'] = defaults($contact, 'generation', 0);
687 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
688 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
689 DBA::escape($contact["name"]),
690 DBA::escape($contact["nick"]),
691 DBA::escape($contact["addr"]),
692 DBA::escape($contact["network"]),
693 DBA::escape($contact["url"]),
694 DBA::escape(Strings::normaliseLink($contact["url"])),
695 DBA::escape($contact["photo"]),
696 DBA::escape(DateTimeFormat::utcNow()),
697 DBA::escape(DateTimeFormat::utcNow()),
698 DBA::escape($contact["location"]),
699 DBA::escape($contact["about"]),
700 intval($contact["hide"]),
701 intval($contact["generation"])
704 $condition = ['nurl' => Strings::normaliseLink($contact["url"])];
705 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
706 if (DBA::isResult($cnt)) {
707 $gcontact_id = $cnt["id"];
708 $doprobing = in_array($cnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""]);
714 Logger::log("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], Logger::DEBUG);
715 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
722 * @brief Updates the gcontact table from a given array
724 * @param array $contact contact array
726 * @return bool|int Returns false if not found, integer if contact was found
727 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
728 * @throws \ImagickException
730 public static function update($contact)
732 // Check for invalid "contact-type" value
733 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
734 $contact['contact-type'] = 0;
737 /// @todo update contact table as well
739 $gcontact_id = self::getId($contact);
746 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
747 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
748 FROM `gcontact` WHERE `id` = %d LIMIT 1",
752 // Get all field names
754 foreach ($public_contact[0] as $field => $data) {
755 $fields[$field] = $data;
758 unset($fields["url"]);
759 unset($fields["updated"]);
760 unset($fields["hide"]);
762 // Bugfix: We had an error in the storing of keywords which lead to the "0"
763 // This value is still transmitted via poco.
764 if (!empty($contact["keywords"]) && ($contact["keywords"] == "0")) {
765 unset($contact["keywords"]);
768 if (!empty($public_contact[0]["keywords"]) && ($public_contact[0]["keywords"] == "0")) {
769 $public_contact[0]["keywords"] = "";
772 // assign all unassigned fields from the database entry
773 foreach ($fields as $field => $data) {
774 if (!isset($contact[$field]) || ($contact[$field] == "")) {
775 $contact[$field] = $public_contact[0][$field];
779 if (!isset($contact["hide"])) {
780 $contact["hide"] = $public_contact[0]["hide"];
783 $fields["hide"] = $public_contact[0]["hide"];
785 if ($contact["network"] == Protocol::STATUSNET) {
786 $contact["network"] = Protocol::OSTATUS;
789 // Replace alternate OStatus user format with the primary one
790 self::fixAlternateContactAddress($contact);
792 if (!isset($contact["updated"])) {
793 $contact["updated"] = DateTimeFormat::utcNow();
796 if ($contact["network"] == Protocol::TWITTER) {
797 $contact["server_url"] = 'http://twitter.com';
800 if ($contact["server_url"] == "") {
801 $data = Probe::uri($contact["url"]);
802 if ($data["network"] != Protocol::PHANTOM) {
803 $contact["server_url"] = $data['baseurl'];
806 $contact["server_url"] = Strings::normaliseLink($contact["server_url"]);
809 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
810 $hostname = str_replace("http://", "", $contact["server_url"]);
811 $contact["addr"] = $contact["nick"]."@".$hostname;
814 // Check if any field changed
816 unset($fields["generation"]);
818 if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
819 foreach ($fields as $field => $data) {
820 if ($contact[$field] != $public_contact[0][$field]) {
821 Logger::log("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", Logger::DEBUG);
826 if ($contact["generation"] < $public_contact[0]["generation"]) {
827 Logger::log("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", Logger::DEBUG);
833 Logger::log("Update gcontact for ".$contact["url"], Logger::DEBUG);
834 $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
835 Strings::normaliseLink($contact["url"]), $contact["generation"]];
836 $contact["updated"] = DateTimeFormat::utc($contact["updated"]);
838 $updated = ['photo' => $contact['photo'], 'name' => $contact['name'],
839 'nick' => $contact['nick'], 'addr' => $contact['addr'],
840 'network' => $contact['network'], 'birthday' => $contact['birthday'],
841 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
842 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
843 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
844 'notify' => $contact['notify'], 'url' => $contact['url'],
845 'location' => $contact['location'], 'about' => $contact['about'],
846 'generation' => $contact['generation'], 'updated' => $contact['updated'],
847 'server_url' => $contact['server_url'], 'connect' => $contact['connect']];
849 DBA::update('gcontact', $updated, $condition, $fields);
851 // Now update the contact entry with the user id "0" as well.
852 // This is used for the shadow copies of public items.
853 /// @todo Check if we really should do this.
854 // The quality of the gcontact table is mostly lower than the public contact
855 $public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => Strings::normaliseLink($contact["url"]), 'uid' => 0]);
856 if (DBA::isResult($public_contact)) {
857 Logger::log("Update public contact ".$public_contact["id"], Logger::DEBUG);
859 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
861 $fields = ['name', 'nick', 'addr',
862 'network', 'bd', 'gender',
863 'keywords', 'alias', 'contact-type',
864 'url', 'location', 'about'];
865 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
867 // Update it with the current values
868 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
869 'addr' => $contact['addr'], 'network' => $contact['network'],
870 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
871 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
872 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
873 'location' => $contact['location'], 'about' => $contact['about']];
875 // Don't update the birthday field if not set or invalid
876 if (empty($contact['birthday']) || ($contact['birthday'] <= DBA::NULL_DATE)) {
877 unset($fields['bd']);
881 DBA::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
889 * @brief Updates the gcontact entry from probe
891 * @param string $url profile link
893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
894 * @throws \ImagickException
896 public static function updateFromProbe($url)
898 $data = Probe::uri($url);
900 if (in_array($data["network"], [Protocol::PHANTOM])) {
901 Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
905 $data["server_url"] = $data["baseurl"];
911 * @brief Update the gcontact entry for a given user id
913 * @param int $uid User ID
915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 * @throws \ImagickException
918 public static function updateForUser($uid)
921 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
922 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
923 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
924 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
925 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
927 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
928 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
929 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
933 if (!DBA::isResult($r)) {
934 Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
938 $location = Profile::formatLocation(
939 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
942 // The "addr" field was added in 3.4.3 so it can be empty for older users
943 if ($r[0]["addr"] != "") {
944 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
946 $addr = $r[0]["addr"];
949 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
950 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
951 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
952 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
953 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
954 "nick" => $r[0]["nickname"], "addr" => $addr,
955 "connect" => $addr, "server_url" => System::baseUrl(),
956 "generation" => 1, "network" => Protocol::DFRN];
958 self::update($gcontact);
962 * @brief Fetches users of given GNU Social server
964 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
966 * @param string $server Server address
968 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
969 * @throws \ImagickException
971 public static function fetchGsUsers($server)
973 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
975 $url = $server."/main/statistics";
977 $curlResult = Network::curl($url);
978 if (!$curlResult->isSuccess()) {
982 $statistics = json_decode($curlResult->getBody());
984 if (!empty($statistics->config->instance_address)) {
985 if (!empty($statistics->config->instance_with_ssl)) {
986 $server = "https://";
991 $server .= $statistics->config->instance_address;
993 $hostname = $statistics->config->instance_address;
994 } elseif (!empty($statistics->instance_address)) {
995 if (!empty($statistics->instance_with_ssl)) {
996 $server = "https://";
1001 $server .= $statistics->instance_address;
1003 $hostname = $statistics->instance_address;
1006 if (!empty($statistics->users)) {
1007 foreach ($statistics->users as $nick => $user) {
1008 $profile_url = $server."/".$user->nickname;
1010 $contact = ["url" => $profile_url,
1011 "name" => $user->fullname,
1012 "addr" => $user->nickname."@".$hostname,
1013 "nick" => $user->nickname,
1014 "network" => Protocol::OSTATUS,
1015 "photo" => System::baseUrl()."/images/person-300.jpg"];
1017 if (isset($user->bio)) {
1018 $contact["about"] = $user->bio;
1021 self::getId($contact);
1027 * @brief Asking GNU Social server on a regular base for their user data
1029 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1030 * @throws \ImagickException
1032 public static function discoverGsUsers()
1034 $requery_days = intval(Config::get("system", "poco_requery_days"));
1036 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1039 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1040 DBA::escape(Protocol::OSTATUS),
1041 DBA::escape($last_update)
1044 if (!DBA::isResult($r)) {
1048 foreach ($r as $server) {
1049 self::fetchGsUsers($server["url"]);
1050 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1057 public static function getRandomUrl()
1060 "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1061 AND `last_contact` >= `last_failure`
1062 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1063 ORDER BY rand() LIMIT 1",
1064 DBA::escape(Protocol::DFRN)
1067 if (DBA::isResult($r)) {
1068 return dirname($r[0]['url']);