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\Protocol;
12 use Friendica\Core\System;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBA;
15 use Friendica\Network\Probe;
16 use Friendica\Protocol\PortableContact;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
20 require_once 'include/dba.php';
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
35 public static function searchByName($search, $mode = '')
41 // check supported networks
42 if (Config::get('system', 'diaspora_enabled')) {
43 $diaspora = Protocol::DIASPORA;
45 $diaspora = Protocol::DFRN;
48 if (!Config::get('system', 'ostatus_disabled')) {
49 $ostatus = Protocol::OSTATUS;
51 $ostatus = Protocol::DFRN;
54 // check if we search only communities or every contact
55 if ($mode === "community") {
56 $extra_sql = " AND `community`";
63 $results = DBA::p("SELECT `nurl` FROM `gcontact`
64 WHERE NOT `hide` AND `network` IN (?, ?, ?) AND
65 ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`)) AND
66 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
67 GROUP BY `nurl` ORDER BY `nurl` DESC LIMIT 1000",
68 Protocol::DFRN, $ostatus, $diaspora, $search, $search, $search
72 while ($result = DBA::fetch($results)) {
73 $urlparts = parse_url($result["nurl"]);
75 // Ignore results that look strange.
76 // For historic reasons the gcontact table does contain some garbage.
77 if (!empty($urlparts['query']) || !empty($urlparts['fragment'])) {
81 $gcontacts[] = Contact::getDetailsByURL($result["nurl"], local_user());
87 * @brief Link the gcontact entry with user, contact and global contact
89 * @param integer $gcid Global contact ID
90 * @param integer $uid User ID
91 * @param integer $cid Contact ID
92 * @param integer $zcid Global Contact ID
95 public static function link($gcid, $uid = 0, $cid = 0, $zcid = 0)
102 "SELECT * FROM `glink` WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d LIMIT 1",
109 if (!DBA::isResult($r)) {
111 "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
116 DBA::escape(DateTimeFormat::utcNow())
120 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
121 DBA::escape(DateTimeFormat::utcNow()),
131 * @brief Sanitize the given gcontact data
133 * @param array $gcontact array with gcontact data
138 * 1: Profiles on this server
139 * 2: Contacts of profiles on this server
140 * 3: Contacts of contacts of profiles on this server
142 * @return array $gcontact
144 public static function sanitize($gcontact)
146 if ($gcontact['url'] == "") {
147 throw new Exception('URL is empty');
150 $urlparts = parse_url($gcontact['url']);
151 if (!isset($urlparts["scheme"])) {
152 throw new Exception("This (".$gcontact['url'].") doesn't seem to be an url.");
155 if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
156 throw new Exception('Contact from a non federated network ignored. ('.$gcontact['url'].')');
159 // Don't store the statusnet connector as network
160 // We can't simply set this to Protocol::OSTATUS since the connector could have fetched posts from friendica as well
161 if ($gcontact['network'] == Protocol::STATUSNET) {
162 $gcontact['network'] = "";
165 // Assure that there are no parameter fragments in the profile url
166 if (in_array($gcontact['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
167 $gcontact['url'] = self::cleanContactUrl($gcontact['url']);
170 $alternate = PortableContact::alternateOStatusUrl($gcontact['url']);
172 // The global contacts should contain the original picture, not the cached one
173 if (($gcontact['generation'] != 1) && stristr(normalise_link($gcontact['photo']), normalise_link(System::baseUrl()."/photo/"))) {
174 $gcontact['photo'] = "";
177 if (!isset($gcontact['network'])) {
179 "SELECT `network` FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' AND `network` != '' AND `network` != '%s' LIMIT 1",
180 DBA::escape(normalise_link($gcontact['url'])),
181 DBA::escape(Protocol::STATUSNET)
183 if (DBA::isResult($r)) {
184 $gcontact['network'] = $r[0]["network"];
187 if (($gcontact['network'] == "") || ($gcontact['network'] == Protocol::OSTATUS)) {
189 "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
190 DBA::escape($gcontact['url']),
191 DBA::escape(normalise_link($gcontact['url'])),
192 DBA::escape(Protocol::STATUSNET)
194 if (DBA::isResult($r)) {
195 $gcontact['network'] = $r[0]["network"];
200 $gcontact['server_url'] = '';
201 $gcontact['network'] = '';
204 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
205 DBA::escape(normalise_link($gcontact['url']))
208 if (DBA::isResult($x)) {
209 if (!isset($gcontact['network']) && ($x[0]["network"] != Protocol::STATUSNET)) {
210 $gcontact['network'] = $x[0]["network"];
212 if ($gcontact['updated'] <= NULL_DATE) {
213 $gcontact['updated'] = $x[0]["updated"];
215 if (!isset($gcontact['server_url']) && (normalise_link($x[0]["server_url"]) != normalise_link($x[0]["url"]))) {
216 $gcontact['server_url'] = $x[0]["server_url"];
218 if (!isset($gcontact['addr'])) {
219 $gcontact['addr'] = $x[0]["addr"];
223 if ((!isset($gcontact['network']) || !isset($gcontact['name']) || !isset($gcontact['addr']) || !isset($gcontact['photo']) || !isset($gcontact['server_url']) || $alternate)
224 && PortableContact::reachable($gcontact['url'], $gcontact['server_url'], $gcontact['network'], false)
226 $data = Probe::uri($gcontact['url']);
228 if ($data["network"] == Protocol::PHANTOM) {
229 throw new Exception('Probing for URL '.$gcontact['url'].' failed');
232 $orig_profile = $gcontact['url'];
234 $gcontact["server_url"] = $data["baseurl"];
236 $gcontact = array_merge($gcontact, $data);
238 if ($alternate && ($gcontact['network'] == Protocol::OSTATUS)) {
239 // Delete the old entry - if it exists
240 if (DBA::exists('gcontact', ['nurl' => normalise_link($orig_profile)])) {
241 DBA::delete('gcontact', ['nurl' => normalise_link($orig_profile)]);
246 if (!isset($gcontact['name']) || !isset($gcontact['photo'])) {
247 throw new Exception('No name and photo for URL '.$gcontact['url']);
250 if (!in_array($gcontact['network'], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
251 throw new Exception('No federated network ('.$gcontact['network'].') detected for URL '.$gcontact['url']);
254 if (!isset($gcontact['server_url'])) {
255 // We check the server url to be sure that it is a real one
256 $server_url = PortableContact::detectServer($gcontact['url']);
258 // We are now sure that it is a correct URL. So we use it in the future
259 if ($server_url != "") {
260 $gcontact['server_url'] = $server_url;
264 // The server URL doesn't seem to be valid, so we don't store it.
265 if (!PortableContact::checkServer($gcontact['server_url'], $gcontact['network'])) {
266 $gcontact['server_url'] = "";
273 * @param integer $uid id
274 * @param integer $cid id
277 public static function countCommonFriends($uid, $cid)
280 "SELECT count(*) as `total`
281 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
282 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
283 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR
284 (`gcontact`.`updated` >= `gcontact`.`last_failure`))
285 AND `gcontact`.`nurl` IN (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 and id != %d ) ",
292 // logger("countCommonFriends: $uid $cid {$r[0]['total']}");
293 if (DBA::isResult($r)) {
294 return $r[0]['total'];
300 * @param integer $uid id
301 * @param integer $zcid zcid
304 public static function countCommonFriendsZcid($uid, $zcid)
307 "SELECT count(*) as `total`
308 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
309 where `glink`.`zcid` = %d
310 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 ) ",
315 if (DBA::isResult($r)) {
316 return $r[0]['total'];
323 * @param integer $uid user
324 * @param integer $cid cid
325 * @param integer $start optional, default 0
326 * @param integer $limit optional, default 9999
327 * @param boolean $shuffle optional, default false
330 public static function commonFriends($uid, $cid, $start = 0, $limit = 9999, $shuffle = false)
333 $sql_extra = " order by rand() ";
335 $sql_extra = " order by `gcontact`.`name` asc ";
339 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
341 INNER JOIN `gcontact` ON `glink`.`gcid` = `gcontact`.`id`
342 INNER JOIN `contact` ON `gcontact`.`nurl` = `contact`.`nurl`
343 WHERE `glink`.`cid` = %d and `glink`.`uid` = %d
344 AND `contact`.`uid` = %d AND `contact`.`self` = 0 AND `contact`.`blocked` = 0
345 AND `contact`.`hidden` = 0 AND `contact`.`id` != %d
346 AND ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
347 $sql_extra LIMIT %d, %d",
356 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
361 * @param integer $uid user
362 * @param integer $zcid zcid
363 * @param integer $start optional, default 0
364 * @param integer $limit optional, default 9999
365 * @param boolean $shuffle optional, default false
368 public static function commonFriendsZcid($uid, $zcid, $start = 0, $limit = 9999, $shuffle = false)
371 $sql_extra = " order by rand() ";
373 $sql_extra = " order by `gcontact`.`name` asc ";
378 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
379 where `glink`.`zcid` = %d
380 and `gcontact`.`nurl` in (select nurl from contact where uid = %d and self = 0 and blocked = 0 and hidden = 0 )
381 $sql_extra limit %d, %d",
388 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
393 * @param integer $uid user
394 * @param integer $cid cid
397 public static function countAllFriends($uid, $cid)
400 "SELECT count(*) as `total`
401 FROM `glink` INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
402 where `glink`.`cid` = %d and `glink`.`uid` = %d AND
403 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))",
408 if (DBA::isResult($r)) {
409 return $r[0]['total'];
416 * @param integer $uid user
417 * @param integer $cid cid
418 * @param integer $start optional, default 0
419 * @param integer $limit optional, default 80
422 public static function allFriends($uid, $cid, $start = 0, $limit = 80)
425 "SELECT `gcontact`.*, `contact`.`id` AS `cid`
427 INNER JOIN `gcontact` on `glink`.`gcid` = `gcontact`.`id`
428 LEFT JOIN `contact` ON `contact`.`nurl` = `gcontact`.`nurl` AND `contact`.`uid` = %d
429 WHERE `glink`.`cid` = %d AND `glink`.`uid` = %d AND
430 ((`gcontact`.`last_contact` >= `gcontact`.`last_failure`) OR (`gcontact`.`updated` >= `gcontact`.`last_failure`))
431 ORDER BY `gcontact`.`name` ASC LIMIT %d, %d ",
439 /// @TODO Check all calling-findings of this function if they properly use DBA::isResult()
444 * @param object $uid user
445 * @param integer $start optional, default 0
446 * @param integer $limit optional, default 80
449 public static function suggestionQuery($uid, $start = 0, $limit = 80)
456 * Uncommented because the result of the queries are to big to store it in the cache.
457 * We need to decide if we want to change the db column type or if we want to delete it.
459 //$list = Cache::get("suggestion_query:".$uid.":".$start.":".$limit);
460 //if (!is_null($list)) {
464 $network = [Protocol::DFRN];
466 if (Config::get('system', 'diaspora_enabled')) {
467 $network[] = Protocol::DIASPORA;
470 if (!Config::get('system', 'ostatus_disabled')) {
471 $network[] = Protocol::OSTATUS;
474 $sql_network = implode("', '", $network);
475 $sql_network = "'".$sql_network."'";
477 /// @todo This query is really slow
478 // By now we cache the data for five minutes
480 "SELECT count(glink.gcid) as `total`, gcontact.* from gcontact
481 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
482 where uid = %d 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 GROUP BY `glink`.`gcid` ORDER BY `gcontact`.`updated` DESC,`total` DESC LIMIT %d, %d",
493 DBA::escape(NULL_DATE),
499 if (DBA::isResult($r) && count($r) >= ($limit -1)) {
501 * Uncommented because the result of the queries are to big to store it in the cache.
502 * We need to decide if we want to change the db column type or if we want to delete it.
504 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $r, CACHE_FIVE_MINUTES);
510 "SELECT gcontact.* FROM gcontact
511 INNER JOIN `glink` ON `glink`.`gcid` = `gcontact`.`id`
512 WHERE `glink`.`uid` = 0 AND `glink`.`cid` = 0 AND `glink`.`zcid` = 0 AND NOT `gcontact`.`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = %d)
513 AND NOT `gcontact`.`name` IN (SELECT `name` FROM `contact` WHERE `uid` = %d)
514 AND NOT `gcontact`.`id` IN (SELECT `gcid` FROM `gcign` WHERE `uid` = %d)
515 AND `gcontact`.`updated` >= '%s'
516 AND `gcontact`.`last_contact` >= `gcontact`.`last_failure`
517 AND `gcontact`.`network` IN (%s)
518 ORDER BY rand() LIMIT %d, %d",
522 DBA::escape(NULL_DATE),
529 foreach ($r2 as $suggestion) {
530 $list[$suggestion["nurl"]] = $suggestion;
533 foreach ($r as $suggestion) {
534 $list[$suggestion["nurl"]] = $suggestion;
537 while (sizeof($list) > ($limit)) {
542 * Uncommented because the result of the queries are to big to store it in the cache.
543 * We need to decide if we want to change the db column type or if we want to delete it.
545 //Cache::set("suggestion_query:".$uid.":".$start.":".$limit, $list, CACHE_FIVE_MINUTES);
552 public static function updateSuggestions()
558 /// @TODO Check if it is really neccessary to poll the own server
559 PortableContact::loadWorker(0, 0, 0, System::baseUrl() . '/poco');
561 $done[] = System::baseUrl() . '/poco';
563 if (strlen(Config::get('system', 'directory'))) {
564 $x = Network::fetchUrl(get_server()."/pubsites");
566 $j = json_decode($x);
567 if (!empty($j->entries)) {
568 foreach ($j->entries as $entry) {
569 PortableContact::checkServer($entry->url);
571 $url = $entry->url . '/poco';
572 if (!in_array($url, $done)) {
573 PortableContact::loadWorker(0, 0, 0, $url);
581 // Query your contacts from Friendica and Redmatrix/Hubzilla for their contacts
583 "SELECT DISTINCT(`poco`) AS `poco` FROM `contact` WHERE `network` IN ('%s', '%s')",
584 DBA::escape(Protocol::DFRN),
585 DBA::escape(Protocol::DIASPORA)
588 if (DBA::isResult($r)) {
589 foreach ($r as $rr) {
590 $base = substr($rr['poco'], 0, strrpos($rr['poco'], '/'));
591 if (! in_array($base, $done)) {
592 PortableContact::loadWorker(0, 0, 0, $base);
599 * @brief Removes unwanted parts from a contact url
601 * @param string $url Contact url
603 * @return string Contact url with the wanted parts
605 public static function cleanContactUrl($url)
607 $parts = parse_url($url);
609 if (!isset($parts["scheme"]) || !isset($parts["host"])) {
613 $new_url = $parts["scheme"]."://".$parts["host"];
615 if (isset($parts["port"])) {
616 $new_url .= ":".$parts["port"];
619 if (isset($parts["path"])) {
620 $new_url .= $parts["path"];
623 if ($new_url != $url) {
624 logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG);
631 * @brief Replace alternate OStatus user format with the primary one
633 * @param array $contact contact array (called by reference)
636 public static function fixAlternateContactAddress(&$contact)
638 if (($contact["network"] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
639 $data = Probe::uri($contact["url"]);
640 if ($contact["network"] == Protocol::OSTATUS) {
641 logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
642 $contact["url"] = $data["url"];
643 $contact["addr"] = $data["addr"];
644 $contact["alias"] = $data["alias"];
645 $contact["server_url"] = $data["baseurl"];
651 * @brief Fetch the gcontact id, add an entry if not existed
653 * @param array $contact contact array
655 * @return bool|int Returns false if not found, integer if contact was found
657 public static function getId($contact)
661 $last_failure_str = '';
662 $last_contact_str = '';
664 if (empty($contact["network"])) {
665 logger("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
669 if (in_array($contact["network"], [Protocol::PHANTOM])) {
670 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
674 if ($contact["network"] == Protocol::STATUSNET) {
675 $contact["network"] = Protocol::OSTATUS;
678 // All new contacts are hidden by default
679 if (!isset($contact["hide"])) {
680 $contact["hide"] = true;
683 // Replace alternate OStatus user format with the primary one
684 self::fixAlternateContactAddress($contact);
686 // Remove unwanted parts from the contact url (e.g. "?zrl=...")
687 if (in_array($contact["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
688 $contact["url"] = self::cleanContactUrl($contact["url"]);
691 DBA::lock('gcontact');
693 "SELECT `id`, `last_contact`, `last_failure`, `network` FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
694 DBA::escape(normalise_link($contact["url"]))
697 if (DBA::isResult($r)) {
698 $gcontact_id = $r[0]["id"];
700 // Update every 90 days
701 if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
702 $last_failure_str = $r[0]["last_failure"];
703 $last_failure = strtotime($r[0]["last_failure"]);
704 $last_contact_str = $r[0]["last_contact"];
705 $last_contact = strtotime($r[0]["last_contact"]);
706 $doprobing = (((time() - $last_contact) > (90 * 86400)) && ((time() - $last_failure) > (90 * 86400)));
709 $contact['location'] = defaults($contact, 'location', '');
710 $contact['about'] = defaults($contact, 'about', '');
711 $contact['generation'] = defaults($contact, 'generation', 0);
714 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
715 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
716 DBA::escape($contact["name"]),
717 DBA::escape($contact["nick"]),
718 DBA::escape($contact["addr"]),
719 DBA::escape($contact["network"]),
720 DBA::escape($contact["url"]),
721 DBA::escape(normalise_link($contact["url"])),
722 DBA::escape($contact["photo"]),
723 DBA::escape(DateTimeFormat::utcNow()),
724 DBA::escape(DateTimeFormat::utcNow()),
725 DBA::escape($contact["location"]),
726 DBA::escape($contact["about"]),
727 intval($contact["hide"]),
728 intval($contact["generation"])
732 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
733 DBA::escape(normalise_link($contact["url"]))
736 if (DBA::isResult($r)) {
737 $gcontact_id = $r[0]["id"];
739 $doprobing = in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""]);
745 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
746 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
753 * @brief Updates the gcontact table from a given array
755 * @param array $contact contact array
757 * @return bool|int Returns false if not found, integer if contact was found
759 public static function update($contact)
761 // Check for invalid "contact-type" value
762 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
763 $contact['contact-type'] = 0;
766 /// @todo update contact table as well
768 $gcontact_id = self::getId($contact);
775 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
776 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
777 FROM `gcontact` WHERE `id` = %d LIMIT 1",
781 // Get all field names
783 foreach ($public_contact[0] as $field => $data) {
784 $fields[$field] = $data;
787 unset($fields["url"]);
788 unset($fields["updated"]);
789 unset($fields["hide"]);
791 // Bugfix: We had an error in the storing of keywords which lead to the "0"
792 // This value is still transmitted via poco.
793 if (!empty($contact["keywords"]) && ($contact["keywords"] == "0")) {
794 unset($contact["keywords"]);
797 if (!empty($public_contact[0]["keywords"]) && ($public_contact[0]["keywords"] == "0")) {
798 $public_contact[0]["keywords"] = "";
801 // assign all unassigned fields from the database entry
802 foreach ($fields as $field => $data) {
803 if (!isset($contact[$field]) || ($contact[$field] == "")) {
804 $contact[$field] = $public_contact[0][$field];
808 if (!isset($contact["hide"])) {
809 $contact["hide"] = $public_contact[0]["hide"];
812 $fields["hide"] = $public_contact[0]["hide"];
814 if ($contact["network"] == Protocol::STATUSNET) {
815 $contact["network"] = Protocol::OSTATUS;
818 // Replace alternate OStatus user format with the primary one
819 self::fixAlternateContactAddress($contact);
821 if (!isset($contact["updated"])) {
822 $contact["updated"] = DateTimeFormat::utcNow();
825 if ($contact["network"] == Protocol::TWITTER) {
826 $contact["server_url"] = 'http://twitter.com';
829 if ($contact["server_url"] == "") {
830 $data = Probe::uri($contact["url"]);
831 if ($data["network"] != Protocol::PHANTOM) {
832 $contact["server_url"] = $data['baseurl'];
835 $contact["server_url"] = normalise_link($contact["server_url"]);
838 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
839 $hostname = str_replace("http://", "", $contact["server_url"]);
840 $contact["addr"] = $contact["nick"]."@".$hostname;
843 // Check if any field changed
845 unset($fields["generation"]);
847 if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
848 foreach ($fields as $field => $data) {
849 if ($contact[$field] != $public_contact[0][$field]) {
850 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", LOGGER_DEBUG);
855 if ($contact["generation"] < $public_contact[0]["generation"]) {
856 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", LOGGER_DEBUG);
862 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
863 $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
864 normalise_link($contact["url"]), $contact["generation"]];
865 $contact["updated"] = DateTimeFormat::utc($contact["updated"]);
867 $updated = ['photo' => $contact['photo'], 'name' => $contact['name'],
868 'nick' => $contact['nick'], 'addr' => $contact['addr'],
869 'network' => $contact['network'], 'birthday' => $contact['birthday'],
870 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
871 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
872 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
873 'notify' => $contact['notify'], 'url' => $contact['url'],
874 'location' => $contact['location'], 'about' => $contact['about'],
875 'generation' => $contact['generation'], 'updated' => $contact['updated'],
876 'server_url' => $contact['server_url'], 'connect' => $contact['connect']];
878 DBA::update('gcontact', $updated, $condition, $fields);
880 // Now update the contact entry with the user id "0" as well.
881 // This is used for the shadow copies of public items.
882 /// @todo Check if we really should do this.
883 // The quality of the gcontact table is mostly lower than the public contact
884 $public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => normalise_link($contact["url"]), 'uid' => 0]);
885 if (DBA::isResult($public_contact)) {
886 logger("Update public contact ".$public_contact["id"], LOGGER_DEBUG);
888 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
890 $fields = ['name', 'nick', 'addr',
891 'network', 'bd', 'gender',
892 'keywords', 'alias', 'contact-type',
893 'url', 'location', 'about'];
894 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
896 // Update it with the current values
897 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
898 'addr' => $contact['addr'], 'network' => $contact['network'],
899 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
900 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
901 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
902 'location' => $contact['location'], 'about' => $contact['about']];
904 // Don't update the birthday field if not set or invalid
905 if (empty($contact['birthday']) || ($contact['birthday'] < '0001-01-01')) {
906 unset($fields['bd']);
910 DBA::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
918 * @brief Updates the gcontact entry from probe
920 * @param string $url profile link
923 public static function updateFromProbe($url)
925 $data = Probe::uri($url);
927 if (in_array($data["network"], [Protocol::PHANTOM])) {
928 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
932 $data["server_url"] = $data["baseurl"];
938 * @brief Update the gcontact entry for a given user id
940 * @param int $uid User ID
943 public static function updateForUser($uid)
946 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
947 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
948 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
949 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
950 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
952 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
953 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
954 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
958 $location = Profile::formatLocation(
959 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
962 // The "addr" field was added in 3.4.3 so it can be empty for older users
963 if ($r[0]["addr"] != "") {
964 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
966 $addr = $r[0]["addr"];
969 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
970 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
971 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
972 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
973 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
974 "nick" => $r[0]["nickname"], "addr" => $addr,
975 "connect" => $addr, "server_url" => System::baseUrl(),
976 "generation" => 1, "network" => Protocol::DFRN];
978 self::update($gcontact);
982 * @brief Fetches users of given GNU Social server
984 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
986 * @param string $server Server address
989 public static function fetchGsUsers($server)
991 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
993 $url = $server."/main/statistics";
995 $result = Network::curl($url);
996 if (!$result["success"]) {
1000 $statistics = json_decode($result["body"]);
1002 if (!empty($statistics->config)) {
1003 if ($statistics->config->instance_with_ssl) {
1004 $server = "https://";
1006 $server = "http://";
1009 $server .= $statistics->config->instance_address;
1011 $hostname = $statistics->config->instance_address;
1012 } elseif (!empty($statistics)) {
1013 if ($statistics->instance_with_ssl) {
1014 $server = "https://";
1016 $server = "http://";
1019 $server .= $statistics->instance_address;
1021 $hostname = $statistics->instance_address;
1024 if (!empty($statistics->users)) {
1025 foreach ($statistics->users as $nick => $user) {
1026 $profile_url = $server."/".$user->nickname;
1028 $contact = ["url" => $profile_url,
1029 "name" => $user->fullname,
1030 "addr" => $user->nickname."@".$hostname,
1031 "nick" => $user->nickname,
1032 "network" => Protocol::OSTATUS,
1033 "photo" => System::baseUrl()."/images/person-175.jpg"];
1035 if (isset($user->bio)) {
1036 $contact["about"] = $user->bio;
1039 self::getId($contact);
1045 * @brief Asking GNU Social server on a regular base for their user data
1048 public static function discoverGsUsers()
1050 $requery_days = intval(Config::get("system", "poco_requery_days"));
1052 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1055 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1056 DBA::escape(Protocol::OSTATUS),
1057 DBA::escape($last_update)
1060 if (!DBA::isResult($r)) {
1064 foreach ($r as $server) {
1065 self::fetchGsUsers($server["url"]);
1066 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", DBA::escape(DateTimeFormat::utcNow()), DBA::escape($server["nurl"]));
1073 public static function getRandomUrl()
1076 "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1077 AND `last_contact` >= `last_failure`
1078 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1079 ORDER BY rand() LIMIT 1",
1080 DBA::escape(Protocol::DFRN)
1083 if (DBA::isResult($r)) {
1084 return dirname($r[0]['url']);