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;
22 require_once 'include/dba.php';
25 * @brief This class handles GlobalContact related functions
30 * @brief Search global contact table by nick or name
32 * @param string $search Name or nick
33 * @param string $mode Search mode (e.g. "community")
35 * @return array with search results
37 public static function searchByName($search, $mode = '')
43 // check supported networks
44 if (Config::get('system', 'diaspora_enabled')) {
45 $diaspora = Protocol::DIASPORA;
47 $diaspora = Protocol::DFRN;
50 if (!Config::get('system', 'ostatus_disabled')) {
51 $ostatus = Protocol::OSTATUS;
53 $ostatus = Protocol::DFRN;
56 // check if we search only communities or every contact
57 if ($mode === "community") {
58 $extra_sql = " AND `community`";
65 $results = DBA::p("SELECT `nurl` FROM `gcontact`
66 WHERE NOT `hide` AND `network` IN (?, ?, ?, ?) AND
67 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
68 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
69 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
70 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $search, $search, $search
74 while ($result = DBA::fetch($results)) {
75 $urlparts = parse_url($result["nurl"]);
77 // Ignore results that look strange.
78 // For historic reasons the gcontact table does contain some garbage.
79 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
83 $gcontacts[] = Contact::getDetailsByURL($result["nurl"], local_user());
89 * @brief Link the gcontact entry with user, contact and global contact
91 * @param integer $gcid Global contact ID
92 * @param integer $uid User ID
93 * @param integer $cid Contact ID
94 * @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
110 * @param array $gcontact array with gcontact data
115 * 1: Profiles on this server
116 * 2: Contacts of profiles on this server
117 * 3: Contacts of contacts of profiles on this server
119 * @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 object $uid user
414 * @param integer $start optional, default 0
415 * @param integer $limit optional, default 80
418 public static function suggestionQuery($uid, $start = 0, $limit = 80)
425 * Uncommented because the result of the queries are to big to store it in the cache.
426 * We need to decide if we want to change the db column type or if we want to delete it.
428 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
429 //if (!is_null($list)) {
433 $network = [Protocol::DFRN, Protocol::ACTIVITYPUB];
435 if (Config::get('system', 'diaspora_enabled')) {
436 $network[] = Protocol::DIASPORA;
439 if (!Config::get('system', 'ostatus_disabled')) {
440 $network[] = Protocol::OSTATUS;
443 $sql_network = implode("', '", $network);
444 $sql_network = "'".$sql_network."'";
446 /// @todo This query is really slow
447 // By now we cache the data for five minutes
449 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
450 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
451 where uid = %d and not gcontact.nurl in ( select nurl from contact where uid = %d )
452 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
453 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
454 AND `gcontact`.`updated` >= '%s' AND NOT `gcontact`.`hide`
455 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
456 AND `gcontact`.`network` IN (%s)
457 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
468 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
470 * Uncommented because the result of the queries are to big to store it in the cache.
471 * We need to decide if we want to change the db column type or if we want to delete it.
473 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, Cache::FIVE_MINUTES);
479 "SELECT gcontact.* FROM gcontact
480 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
481 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
482 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
483 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
484 AND `gcontact`.`updated` >= '%s'
485 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
486 AND `gcontact`.`network` IN (%s)
487 ORDER BY rand() LIMIT %d, %d",
498 foreach ($r2 as $suggestion) {
499 $list[$suggestion["nurl"]] = $suggestion;
502 foreach ($r as $suggestion) {
503 $list[$suggestion["nurl"]] = $suggestion;
506 while (sizeof($list) > ($limit)) {
511 * Uncommented because the result of the queries are to big to store it in the cache.
512 * We need to decide if we want to change the db column type or if we want to delete it.
514 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, Cache::FIVE_MINUTES);
521 public static function updateSuggestions()
527 /// @TODO Check if it is really neccessary to poll the own server
528 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
530 $done[] = System::baseUrl() . '/poco';
532 if (strlen(Config::get('system', 'directory'))) {
533 $x = Network::fetchUrl(get_server()."/pubsites");
535 $j = json_decode($x);
536 if (!empty($j->entries)) {
537 foreach ($j->entries as $entry) {
538 PortableContact::checkServer($entry->url);
540 $url = $entry->url . '/poco';
541 if (!in_array($url, $done)) {
542 PortableContact::loadWorker(0, 0, 0, $url);
550 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
552 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
553 DBA::escape(Protocol::DFRN),
554 DBA::escape(Protocol::DIASPORA)
557 if (DBA::isResult($r)) {
558 foreach ($r as $rr) {
559 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
560 if (! in_array($base, $done)) {
561 PortableContact::loadWorker(0, 0, 0, $base);
568 * @brief Removes unwanted parts from a contact url
570 * @param string $url Contact url
572 * @return string Contact url with the wanted parts
574 public static function cleanContactUrl($url)
576 $parts = parse_url($url);
578 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
582 $new_url = $parts["scheme"]."://".$parts["host"];
584 if (isset($parts["port"])) {
585 $new_url .= ":".$parts["port"];
588 if (isset($parts["path"])) {
589 $new_url .= $parts["path"];
592 if ($new_url != $url) {
593 Logger::log("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), Logger::DEBUG);
600 * @brief Replace alternate OStatus user format with the primary one
602 * @param array $contact contact array (called by reference)
605 public static function fixAlternateContactAddress(&$contact)
607 if (($contact["network"] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
608 $data = Probe::uri($contact["url"]);
609 if ($contact["network"] == Protocol::OSTATUS) {
610 Logger::log("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
611 $contact["url"] = $data["url"];
612 $contact["addr"] = $data["addr"];
613 $contact["alias"] = $data["alias"];
614 $contact["server_url"] = $data["baseurl"];
620 * @brief Fetch the gcontact id, add an entry if not existed
622 * @param array $contact contact array
624 * @return bool|int Returns false if not found, integer if contact was found
626 public static function getId($contact)
630 $last_failure_str = '';
631 $last_contact_str = '';
633 if (empty($contact["network"])) {
634 Logger::log("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
638 if (in_array($contact["network"], [Protocol::PHANTOM])) {
639 Logger::log("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
643 if ($contact["network"] == Protocol::STATUSNET) {
644 $contact["network"] = Protocol::OSTATUS;
647 // All new contacts are hidden by default
648 if (!isset($contact["hide"])) {
649 $contact["hide"] = true;
652 // Replace alternate OStatus user format with the primary one
653 self::fixAlternateContactAddress($contact);
655 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
656 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
657 $contact["url"] = self::cleanContactUrl($contact["url"]);
660 DBA::lock('gcontact');
661 $fields = ['id', 'last_contact', 'last_failure', 'network'];
662 $gcnt = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($contact["url"])]);
663 if (DBA::isResult($gcnt)) {
664 $gcontact_id = $gcnt["id"];
666 // Update every 90 days
667 if (in_array($gcnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
668 $last_failure_str = $gcnt["last_failure"];
669 $last_failure = strtotime($gcnt["last_failure"]);
670 $last_contact_str = $gcnt["last_contact"];
671 $last_contact = strtotime($gcnt["last_contact"]);
672 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
675 $contact['location'] = defaults($contact, 'location', '');
676 $contact['about'] = defaults($contact, 'about', '');
677 $contact['generation'] = defaults($contact, 'generation', 0);
680 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
681 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
682 DBA::escape($contact["name"]),
683 DBA::escape($contact["nick"]),
684 DBA::escape($contact["addr"]),
685 DBA::escape($contact["network"]),
686 DBA::escape($contact["url"]),
687 DBA::escape(Strings::normaliseLink($contact["url"])),
688 DBA::escape($contact["photo"]),
689 DBA::escape(DateTimeFormat::utcNow()),
690 DBA::escape(DateTimeFormat::utcNow()),
691 DBA::escape($contact["location"]),
692 DBA::escape($contact["about"]),
693 intval($contact["hide"]),
694 intval($contact["generation"])
697 $condition = ['nurl' => Strings::normaliseLink($contact["url"])];
698 $cnt = DBA::selectFirst('gcontact', ['id', 'network'], $condition, ['order' => ['id']]);
699 if (DBA::isResult($cnt)) {
700 $gcontact_id = $cnt["id"];
701 $doprobing = in_array($cnt["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""]);
707 Logger::log("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], Logger::DEBUG);
708 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
715 * @brief Updates the gcontact table from a given array
717 * @param array $contact contact array
719 * @return bool|int Returns false if not found, integer if contact was found
721 public static function update($contact)
723 // Check for invalid "contact-type" value
724 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
725 $contact['contact-type'] = 0;
728 /// @todo update contact table as well
730 $gcontact_id = self::getId($contact);
737 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
738 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
739 FROM `gcontact` WHERE `id` = %d LIMIT 1",
743 // Get all field names
745 foreach ($public_contact[0] as $field => $data) {
746 $fields[$field] = $data;
749 unset($fields["url"]);
750 unset($fields["updated"]);
751 unset($fields["hide"]);
753 // Bugfix: We had an error in the storing of keywords which lead to the "0"
754 // This value is still transmitted via poco.
755 if (!empty($contact["keywords"]) && ($contact["keywords"] == "0")) {
756 unset($contact["keywords"]);
759 if (!empty($public_contact[0]["keywords"]) && ($public_contact[0]["keywords"] == "0")) {
760 $public_contact[0]["keywords"] = "";
763 // assign all unassigned fields from the database entry
764 foreach ($fields as $field => $data) {
765 if (!isset($contact[$field]) || ($contact[$field] == "")) {
766 $contact[$field] = $public_contact[0][$field];
770 if (!isset($contact["hide"])) {
771 $contact["hide"] = $public_contact[0]["hide"];
774 $fields["hide"] = $public_contact[0]["hide"];
776 if ($contact["network"] == Protocol::STATUSNET) {
777 $contact["network"] = Protocol::OSTATUS;
780 // Replace alternate OStatus user format with the primary one
781 self::fixAlternateContactAddress($contact);
783 if (!isset($contact["updated"])) {
784 $contact["updated"] = DateTimeFormat::utcNow();
787 if ($contact["network"] == Protocol::TWITTER) {
788 $contact["server_url"] = 'http://twitter.com';
791 if ($contact["server_url"] == "") {
792 $data = Probe::uri($contact["url"]);
793 if ($data["network"] != Protocol::PHANTOM) {
794 $contact["server_url"] = $data['baseurl'];
797 $contact["server_url"] = Strings::normaliseLink($contact["server_url"]);
800 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
801 $hostname = str_replace("http://", "", $contact["server_url"]);
802 $contact["addr"] = $contact["nick"]."@".$hostname;
805 // Check if any field changed
807 unset($fields["generation"]);
809 if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
810 foreach ($fields as $field => $data) {
811 if ($contact[$field] != $public_contact[0][$field]) {
812 Logger::log("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", Logger::DEBUG);
817 if ($contact["generation"] < $public_contact[0]["generation"]) {
818 Logger::log("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", Logger::DEBUG);
824 Logger::log("Update gcontact for ".$contact["url"], Logger::DEBUG);
825 $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
826 Strings::normaliseLink($contact["url"]), $contact["generation"]];
827 $contact["updated"] = DateTimeFormat::utc($contact["updated"]);
829 $updated = ['photo' => $contact['photo'], 'name' => $contact['name'],
830 'nick' => $contact['nick'], 'addr' => $contact['addr'],
831 'network' => $contact['network'], 'birthday' => $contact['birthday'],
832 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
833 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
834 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
835 'notify' => $contact['notify'], 'url' => $contact['url'],
836 'location' => $contact['location'], 'about' => $contact['about'],
837 'generation' => $contact['generation'], 'updated' => $contact['updated'],
838 'server_url' => $contact['server_url'], 'connect' => $contact['connect']];
840 DBA::update('gcontact', $updated, $condition, $fields);
842 // Now update the contact entry with the user id "0" as well.
843 // This is used for the shadow copies of public items.
844 /// @todo Check if we really should do this.
845 // The quality of the gcontact table is mostly lower than the public contact
846 $public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => Strings::normaliseLink($contact["url"]), 'uid' => 0]);
847 if (DBA::isResult($public_contact)) {
848 Logger::log("Update public contact ".$public_contact["id"], Logger::DEBUG);
850 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
852 $fields = ['name', 'nick', 'addr',
853 'network', 'bd', 'gender',
854 'keywords', 'alias', 'contact-type',
855 'url', 'location', 'about'];
856 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
858 // Update it with the current values
859 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
860 'addr' => $contact['addr'], 'network' => $contact['network'],
861 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
862 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
863 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
864 'location' => $contact['location'], 'about' => $contact['about']];
866 // Don't update the birthday field if not set or invalid
867 if (empty($contact['birthday']) || ($contact['birthday'] < '0001-01-01')) {
868 unset($fields['bd']);
872 DBA::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
880 * @brief Updates the gcontact entry from probe
882 * @param string $url profile link
885 public static function updateFromProbe($url)
887 $data = Probe::uri($url);
889 if (in_array($data["network"], [Protocol::PHANTOM])) {
890 Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
894 $data["server_url"] = $data["baseurl"];
900 * @brief Update the gcontact entry for a given user id
902 * @param int $uid User ID
905 public static function updateForUser($uid)
908 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
909 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
910 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
911 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
912 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
914 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
915 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
916 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
920 if (!DBA::isResult($r)) {
921 Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
925 $location = Profile::formatLocation(
926 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
929 // The "addr" field was added in 3.4.3 so it can be empty for older users
930 if ($r[0]["addr"] != "") {
931 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
933 $addr = $r[0]["addr"];
936 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
937 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
938 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
939 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
940 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
941 "nick" => $r[0]["nickname"], "addr" => $addr,
942 "connect" => $addr, "server_url" => System::baseUrl(),
943 "generation" => 1, "network" => Protocol::DFRN];
945 self::update($gcontact);
949 * @brief Fetches users of given GNU Social server
951 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
953 * @param string $server Server address
956 public static function fetchGsUsers($server)
958 Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
960 $url = $server."/main/statistics";
962 $curlResult = Network::curl($url);
963 if (!$curlResult->isSuccess()) {
967 $statistics = json_decode($curlResult->getBody());
969 if (!empty($statistics->config)) {
970 if ($statistics->config->instance_with_ssl) {
971 $server = "https://";
976 $server .= $statistics->config->instance_address;
978 $hostname = $statistics->config->instance_address;
979 } elseif (!empty($statistics)) {
980 if ($statistics->instance_with_ssl) {
981 $server = "https://";
986 $server .= $statistics->instance_address;
988 $hostname = $statistics->instance_address;
991 if (!empty($statistics->users)) {
992 foreach ($statistics->users as $nick => $user) {
993 $profile_url = $server."/".$user->nickname;
995 $contact = ["url" => $profile_url,
996 "name" => $user->fullname,
997 "addr" => $user->nickname."@".$hostname,
998 "nick" => $user->nickname,
999 "network" => Protocol::OSTATUS,
1000 "photo" => System::baseUrl()."/images/person-300.jpg"];
1002 if (isset($user->bio)) {
1003 $contact["about"] = $user->bio;
1006 self::getId($contact);
1012 * @brief Asking GNU Social server on a regular base for their user data
1015 public static function discoverGsUsers()
1017 $requery_days = intval(Config::get("system", "poco_requery_days"));
1019 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1022 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1023 DBA::escape(Protocol::OSTATUS),
1024 DBA::escape($last_update)
1027 if (!DBA::isResult($r)) {
1031 foreach ($r as $server) {
1032 self::fetchGsUsers($server["url"]);
1033 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1040 public static function getRandomUrl()
1043 "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1044 AND `last_contact` >= `last_failure`
1045 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1046 ORDER BY rand() LIMIT 1",
1047 DBA::escape(Protocol::DFRN)
1050 if (DBA::isResult($r)) {
1051 return dirname($r[0]['url']);