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\System;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBA;
14 use Friendica\Database\DBM;
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 = NETWORK_DIASPORA;
45 $diaspora = NETWORK_DFRN;
48 if (!Config::get('system', 'ostatus_disabled')) {
49 $ostatus = NETWORK_OSTATUS;
51 $ostatus = NETWORK_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 NETWORK_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 (!DBM::is_result($r)) {
111 "INSERT INTO `glink` (`cid`, `uid`, `gcid`, `zcid`, `updated`) VALUES (%d, %d, %d, %d, '%s') ",
116 dbesc(DateTimeFormat::utcNow())
120 "UPDATE `glink` SET `updated` = '%s' WHERE `cid` = %d AND `uid` = %d AND `gcid` = %d AND `zcid` = %d",
121 dbesc(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"], ["www.facebook.com", "facebook.com", "twitter.com", "identi.ca", "alpha.app.net"])) {
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 NETWORK_OSTATUS since the connector could have fetched posts from friendica as well
161 if ($gcontact['network'] == NETWORK_STATUSNET) {
162 $gcontact['network'] = "";
165 // Assure that there are no parameter fragments in the profile url
166 if (in_array($gcontact['network'], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_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 dbesc(normalise_link($gcontact['url'])),
181 dbesc(NETWORK_STATUSNET)
183 if (DBM::is_result($r)) {
184 $gcontact['network'] = $r[0]["network"];
187 if (($gcontact['network'] == "") || ($gcontact['network'] == NETWORK_OSTATUS)) {
189 "SELECT `network`, `url` FROM `contact` WHERE `uid` = 0 AND `alias` IN ('%s', '%s') AND `network` != '' AND `network` != '%s' LIMIT 1",
190 dbesc($gcontact['url']),
191 dbesc(normalise_link($gcontact['url'])),
192 dbesc(NETWORK_STATUSNET)
194 if (DBM::is_result($r)) {
195 $gcontact['network'] = $r[0]["network"];
200 $gcontact['server_url'] = '';
201 $gcontact['network'] = '';
204 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
205 dbesc(normalise_link($gcontact['url']))
208 if (DBM::is_result($x)) {
209 if (!isset($gcontact['network']) && ($x[0]["network"] != NETWORK_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"] == NETWORK_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'] == NETWORK_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'], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_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 (DBM::is_result($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 (DBM::is_result($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 DBM::is_result()
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 DBM::is_result()
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 (DBM::is_result($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 DBM::is_result()
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 = [NETWORK_DFRN];
466 if (Config::get('system', 'diaspora_enabled')) {
467 $network[] = NETWORK_DIASPORA;
470 if (!Config::get('system', 'ostatus_disabled')) {
471 $network[] = NETWORK_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",
499 if (DBM::is_result($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",
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')",
585 dbesc(NETWORK_DIASPORA)
588 if (DBM::is_result($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"] == NETWORK_OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
639 $data = Probe::uri($contact["url"]);
640 if ($contact["network"] == NETWORK_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"], [NETWORK_PHANTOM])) {
670 logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
674 if ($contact["network"] == NETWORK_STATUSNET) {
675 $contact["network"] = NETWORK_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"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_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 dbesc(normalise_link($contact["url"]))
697 if (DBM::is_result($r)) {
698 $gcontact_id = $r[0]["id"];
700 // Update every 90 days
701 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_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)));
710 "INSERT INTO `gcontact` (`name`, `nick`, `addr` , `network`, `url`, `nurl`, `photo`, `created`, `updated`, `location`, `about`, `hide`, `generation`)
711 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d)",
712 dbesc($contact["name"]),
713 dbesc($contact["nick"]),
714 dbesc($contact["addr"]),
715 dbesc($contact["network"]),
716 dbesc($contact["url"]),
717 dbesc(normalise_link($contact["url"])),
718 dbesc($contact["photo"]),
719 dbesc(DateTimeFormat::utcNow()),
720 dbesc(DateTimeFormat::utcNow()),
721 dbesc($contact["location"]),
722 dbesc($contact["about"]),
723 intval($contact["hide"]),
724 intval($contact["generation"])
728 "SELECT `id`, `network` FROM `gcontact` WHERE `nurl` = '%s' ORDER BY `id` LIMIT 2",
729 dbesc(normalise_link($contact["url"]))
732 if (DBM::is_result($r)) {
733 $gcontact_id = $r[0]["id"];
735 $doprobing = in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""]);
741 logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG);
742 Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
749 * @brief Updates the gcontact table from a given array
751 * @param array $contact contact array
753 * @return bool|int Returns false if not found, integer if contact was found
755 public static function update($contact)
757 // Check for invalid "contact-type" value
758 if (isset($contact['contact-type']) && (intval($contact['contact-type']) < 0)) {
759 $contact['contact-type'] = 0;
762 /// @todo update contact table as well
764 $gcontact_id = self::getId($contact);
771 "SELECT `name`, `nick`, `photo`, `location`, `about`, `addr`, `generation`, `birthday`, `gender`, `keywords`,
772 `contact-type`, `hide`, `nsfw`, `network`, `alias`, `notify`, `server_url`, `connect`, `updated`, `url`
773 FROM `gcontact` WHERE `id` = %d LIMIT 1",
777 // Get all field names
779 foreach ($public_contact[0] as $field => $data) {
780 $fields[$field] = $data;
783 unset($fields["url"]);
784 unset($fields["updated"]);
785 unset($fields["hide"]);
787 // Bugfix: We had an error in the storing of keywords which lead to the "0"
788 // This value is still transmitted via poco.
789 if (!empty($contact["keywords"]) && ($contact["keywords"] == "0")) {
790 unset($contact["keywords"]);
793 if (!empty($public_contact[0]["keywords"]) && ($public_contact[0]["keywords"] == "0")) {
794 $public_contact[0]["keywords"] = "";
797 // assign all unassigned fields from the database entry
798 foreach ($fields as $field => $data) {
799 if (!isset($contact[$field]) || ($contact[$field] == "")) {
800 $contact[$field] = $public_contact[0][$field];
804 if (!isset($contact["hide"])) {
805 $contact["hide"] = $public_contact[0]["hide"];
808 $fields["hide"] = $public_contact[0]["hide"];
810 if ($contact["network"] == NETWORK_STATUSNET) {
811 $contact["network"] = NETWORK_OSTATUS;
814 // Replace alternate OStatus user format with the primary one
815 self::fixAlternateContactAddress($contact);
817 if (!isset($contact["updated"])) {
818 $contact["updated"] = DBM::date();
821 if ($contact["network"] == NETWORK_TWITTER) {
822 $contact["server_url"] = 'http://twitter.com';
825 if ($contact["server_url"] == "") {
826 $data = Probe::uri($contact["url"]);
827 if ($data["network"] != NETWORK_PHANTOM) {
828 $contact["server_url"] = $data['baseurl'];
831 $contact["server_url"] = normalise_link($contact["server_url"]);
834 if (($contact["addr"] == "") && ($contact["server_url"] != "") && ($contact["nick"] != "")) {
835 $hostname = str_replace("http://", "", $contact["server_url"]);
836 $contact["addr"] = $contact["nick"]."@".$hostname;
839 // Check if any field changed
841 unset($fields["generation"]);
843 if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
844 foreach ($fields as $field => $data) {
845 if ($contact[$field] != $public_contact[0][$field]) {
846 logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", LOGGER_DEBUG);
851 if ($contact["generation"] < $public_contact[0]["generation"]) {
852 logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", LOGGER_DEBUG);
858 logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG);
859 $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
860 normalise_link($contact["url"]), $contact["generation"]];
861 $contact["updated"] = DBM::date($contact["updated"]);
863 $updated = ['photo' => $contact['photo'], 'name' => $contact['name'],
864 'nick' => $contact['nick'], 'addr' => $contact['addr'],
865 'network' => $contact['network'], 'birthday' => $contact['birthday'],
866 'gender' => $contact['gender'], 'keywords' => $contact['keywords'],
867 'hide' => $contact['hide'], 'nsfw' => $contact['nsfw'],
868 'contact-type' => $contact['contact-type'], 'alias' => $contact['alias'],
869 'notify' => $contact['notify'], 'url' => $contact['url'],
870 'location' => $contact['location'], 'about' => $contact['about'],
871 'generation' => $contact['generation'], 'updated' => $contact['updated'],
872 'server_url' => $contact['server_url'], 'connect' => $contact['connect']];
874 DBA::update('gcontact', $updated, $condition, $fields);
876 // Now update the contact entry with the user id "0" as well.
877 // This is used for the shadow copies of public items.
878 /// @todo Check if we really should do this.
879 // The quality of the gcontact table is mostly lower than the public contact
880 $public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => normalise_link($contact["url"]), 'uid' => 0]);
881 if (DBM::is_result($public_contact)) {
882 logger("Update public contact ".$public_contact["id"], LOGGER_DEBUG);
884 Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
886 $fields = ['name', 'nick', 'addr',
887 'network', 'bd', 'gender',
888 'keywords', 'alias', 'contact-type',
889 'url', 'location', 'about'];
890 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $public_contact["id"]]);
892 // Update it with the current values
893 $fields = ['name' => $contact['name'], 'nick' => $contact['nick'],
894 'addr' => $contact['addr'], 'network' => $contact['network'],
895 'bd' => $contact['birthday'], 'gender' => $contact['gender'],
896 'keywords' => $contact['keywords'], 'alias' => $contact['alias'],
897 'contact-type' => $contact['contact-type'], 'url' => $contact['url'],
898 'location' => $contact['location'], 'about' => $contact['about']];
900 // Don't update the birthday field if not set or invalid
901 if (empty($contact['birthday']) || ($contact['birthday'] < '0001-01-01')) {
902 unset($fields['bd']);
906 DBA::update('contact', $fields, ['id' => $public_contact["id"]], $old_contact);
914 * @brief Updates the gcontact entry from probe
916 * @param string $url profile link
919 public static function updateFromProbe($url)
921 $data = Probe::uri($url);
923 if (in_array($data["network"], [NETWORK_PHANTOM])) {
924 logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG);
928 $data["server_url"] = $data["baseurl"];
934 * @brief Update the gcontact entry for a given user id
936 * @param int $uid User ID
939 public static function updateForUser($uid)
942 "SELECT `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
943 `profile`.`name`, `profile`.`about`, `profile`.`gender`,
944 `profile`.`pub_keywords`, `profile`.`dob`, `profile`.`photo`,
945 `profile`.`net-publish`, `user`.`nickname`, `user`.`hidewall`,
946 `contact`.`notify`, `contact`.`url`, `contact`.`addr`
948 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
949 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid`
950 WHERE `profile`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self`",
954 $location = Profile::formatLocation(
955 ["locality" => $r[0]["locality"], "region" => $r[0]["region"], "country-name" => $r[0]["country-name"]]
958 // The "addr" field was added in 3.4.3 so it can be empty for older users
959 if ($r[0]["addr"] != "") {
960 $addr = $r[0]["nickname"].'@'.str_replace(["http://", "https://"], "", System::baseUrl());
962 $addr = $r[0]["addr"];
965 $gcontact = ["name" => $r[0]["name"], "location" => $location, "about" => $r[0]["about"],
966 "gender" => $r[0]["gender"], "keywords" => $r[0]["pub_keywords"],
967 "birthday" => $r[0]["dob"], "photo" => $r[0]["photo"],
968 "notify" => $r[0]["notify"], "url" => $r[0]["url"],
969 "hide" => ($r[0]["hidewall"] || !$r[0]["net-publish"]),
970 "nick" => $r[0]["nickname"], "addr" => $addr,
971 "connect" => $addr, "server_url" => System::baseUrl(),
972 "generation" => 1, "network" => NETWORK_DFRN];
974 self::update($gcontact);
978 * @brief Fetches users of given GNU Social server
980 * If the "Statistics" addon is enabled (See http://gstools.org/ for details) we query user data with this.
982 * @param string $server Server address
985 public static function fetchGsUsers($server)
987 logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG);
989 $url = $server."/main/statistics";
991 $result = Network::curl($url);
992 if (!$result["success"]) {
996 $statistics = json_decode($result["body"]);
998 if (!empty($statistics->config)) {
999 if ($statistics->config->instance_with_ssl) {
1000 $server = "https://";
1002 $server = "http://";
1005 $server .= $statistics->config->instance_address;
1007 $hostname = $statistics->config->instance_address;
1008 } elseif (!empty($statistics)) {
1009 if ($statistics->instance_with_ssl) {
1010 $server = "https://";
1012 $server = "http://";
1015 $server .= $statistics->instance_address;
1017 $hostname = $statistics->instance_address;
1020 if (!empty($statistics->users)) {
1021 foreach ($statistics->users as $nick => $user) {
1022 $profile_url = $server."/".$user->nickname;
1024 $contact = ["url" => $profile_url,
1025 "name" => $user->fullname,
1026 "addr" => $user->nickname."@".$hostname,
1027 "nick" => $user->nickname,
1028 "network" => NETWORK_OSTATUS,
1029 "photo" => System::baseUrl()."/images/person-175.jpg"];
1031 if (isset($user->bio)) {
1032 $contact["about"] = $user->bio;
1035 self::getId($contact);
1041 * @brief Asking GNU Social server on a regular base for their user data
1044 public static function discoverGsUsers()
1046 $requery_days = intval(Config::get("system", "poco_requery_days"));
1048 $last_update = date("c", time() - (60 * 60 * 24 * $requery_days));
1051 "SELECT `nurl`, `url` FROM `gserver` WHERE `last_contact` >= `last_failure` AND `network` = '%s' AND `last_poco_query` < '%s' ORDER BY RAND() LIMIT 5",
1052 dbesc(NETWORK_OSTATUS),
1056 if (!DBM::is_result($r)) {
1060 foreach ($r as $server) {
1061 self::fetchGsUsers($server["url"]);
1062 q("UPDATE `gserver` SET `last_poco_query` = '%s' WHERE `nurl` = '%s'", dbesc(DateTimeFormat::utcNow()), dbesc($server["nurl"]));
1069 public static function getRandomUrl()
1072 "SELECT `url` FROM `gcontact` WHERE `network` = '%s'
1073 AND `last_contact` >= `last_failure`
1074 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
1075 ORDER BY rand() LIMIT 1",
1079 if (DBM::is_result($r)) {
1080 return dirname($r[0]['url']);