3 * @file src/Worker/DiscoverPoCo.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
9 use Friendica\Core\Worker;
10 use Friendica\Database\DBM;
11 use Friendica\Model\GContact;
12 use Friendica\Network\Probe;
13 use Friendica\Protocol\PortableContact;
14 use Friendica\Util\DateTimeFormat;
15 use Friendica\Util\Network;
17 require_once 'include/datetime.php';
20 /// @todo Clean up this mess of a parameter hell and split it in several classes
21 public static function execute($command = '', $param1 = '', $param2 = '', $param3 = '', $param4 = '')
24 This function can be called in these ways:
25 - dirsearch <search pattern>: Searches for "search pattern" in the directory. "search pattern" is url encoded.
26 - checkcontact: Updates gcontact entries
27 - suggestions: Discover other servers for their contacts.
28 - server <poco url>: Searches for the poco server list. "poco url" is base64 encoded.
29 - update_server: Frequently check the first 250 servers for vitality.
30 - update_server_directory: Discover the given server id for their contacts
31 - PortableContact::load: Load POCO data from a given POCO address
32 - check_profile: Update remote profile data
35 if ($command == "dirsearch") {
36 $search = urldecode($param1);
38 } elseif ($command == "checkcontact") {
40 } elseif ($command == "suggestions") {
42 } elseif ($command == "server") {
44 } elseif ($command == "update_server") {
46 } elseif ($command == "update_server_directory") {
48 } elseif ($command == "load") {
50 } elseif ($command == "check_profile") {
52 } elseif ($command == '') {
56 logger("Unknown or missing parameter ".$command."\n");
60 logger('start '.$search);
64 PortableContact::lastUpdated($param1, true);
66 } elseif ($mode == 7) {
67 if (!empty($param4)) {
72 PortableContact::load(intval($param1), intval($param2), intval($param3), $url);
73 } elseif ($mode == 6) {
74 PortableContact::discoverSingleServer(intval($param1));
75 } elseif ($mode == 5) {
77 } elseif ($mode == 4) {
78 $server_url = $param1;
79 if ($server_url == "") {
82 $server_url = filter_var($server_url, FILTER_SANITIZE_URL);
83 if (substr(normalise_link($server_url), 0, 7) != "http://") {
86 $result = "Checking server ".$server_url." - ";
87 $ret = PortableContact::checkServer($server_url);
93 logger($result, LOGGER_DEBUG);
94 } elseif ($mode == 3) {
95 GContact::updateSuggestions();
96 } elseif (($mode == 2) && Config::get('system', 'poco_completion')) {
97 self::discoverUsers();
98 } elseif (($mode == 1) && ($search != "") && Config::get('system', 'poco_local_search')) {
99 self::discoverDirectory($search);
100 self::gsSearchUser($search);
101 } elseif (($mode == 0) && ($search == "") && (Config::get('system', 'poco_discovery') > 0)) {
102 // Query Friendica and Hubzilla servers for their users
103 PortableContact::discover();
105 // Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server)
106 if (!Config::get('system', 'ostatus_disabled')) {
107 GContact::discoverGsUsers();
111 logger('end '.$search);
117 * @brief Updates the first 250 servers
120 private static function updateServer() {
121 $r = q("SELECT `url`, `created`, `last_failure`, `last_contact` FROM `gserver` ORDER BY rand()");
123 if (!DBM::is_result($r)) {
129 foreach ($r AS $server) {
130 if (!PortableContact::updateNeeded($server["created"], "", $server["last_failure"], $server["last_contact"])) {
133 logger('Update server status for server '.$server["url"], LOGGER_DEBUG);
135 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server["url"]);
137 if (++$updated > 250) {
143 private static function discoverUsers() {
144 logger("Discover users", LOGGER_DEBUG);
148 $users = q("SELECT `url`, `created`, `updated`, `last_failure`, `last_contact`, `server_url`, `network` FROM `gcontact`
149 WHERE `last_contact` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
150 `last_failure` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
151 `network` IN ('%s', '%s', '%s', '%s', '') ORDER BY rand()",
152 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA),
153 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_FEED));
160 foreach ($users AS $user) {
162 $urlparts = parse_url($user["url"]);
163 if (!isset($urlparts["scheme"])) {
164 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
165 dbesc(NETWORK_PHANTOM), dbesc(normalise_link($user["url"])));
169 if (in_array($urlparts["host"], ["www.facebook.com", "facebook.com", "twitter.com",
170 "identi.ca", "alpha.app.net"])) {
171 $networks = ["www.facebook.com" => NETWORK_FACEBOOK,
172 "facebook.com" => NETWORK_FACEBOOK,
173 "twitter.com" => NETWORK_TWITTER,
174 "identi.ca" => NETWORK_PUMPIO,
175 "alpha.app.net" => NETWORK_APPNET];
177 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
178 dbesc($networks[$urlparts["host"]]), dbesc(normalise_link($user["url"])));
182 $server_url = PortableContact::detectServer($user["url"]);
183 $force_update = false;
185 if ($user["server_url"] != "") {
187 $force_update = (normalise_link($user["server_url"]) != normalise_link($server_url));
189 $server_url = $user["server_url"];
192 if ((($server_url == "") && ($user["network"] == NETWORK_FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) {
193 logger('Check profile '.$user["url"]);
194 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]);
196 if (++$checked > 100) {
200 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
201 dbesc(DateTimeFormat::utcNow()), dbesc(normalise_link($user["url"])));
204 // Quit the loop after 3 minutes
205 if (time() > ($starttime + 180)) {
211 private static function discoverDirectory($search) {
213 $data = Cache::get("dirsearch:".$search);
214 if (!is_null($data)) {
215 // Only search for the same item every 24 hours
216 if (time() < $data + (60 * 60 * 24)) {
217 logger("Already searched for ".$search." in the last 24 hours", LOGGER_DEBUG);
222 $x = Network::fetchUrl(get_server()."/lsearch?p=1&n=500&search=".urlencode($search));
223 $j = json_decode($x);
225 if (count($j->results)) {
226 foreach ($j->results as $jj) {
227 // Check if the contact already exists
228 $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url));
229 if (DBM::is_result($exists)) {
230 logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
232 if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
233 ($exists[0]["updated"] < $exists[0]["last_failure"])) {
236 // Update the contact
237 PortableContact::lastUpdated($jj->url);
241 $server_url = PortableContact::detectServer($jj->url);
242 if ($server_url != '') {
243 if (!PortableContact::checkServer($server_url)) {
244 logger("Friendica server ".$server_url." doesn't answer.", LOGGER_DEBUG);
247 logger("Friendica server ".$server_url." seems to be okay.", LOGGER_DEBUG);
250 $data = Probe::uri($jj->url);
251 if ($data["network"] == NETWORK_DFRN) {
252 logger("Profile ".$jj->url." is reachable (".$search.")", LOGGER_DEBUG);
253 logger("Add profile ".$jj->url." to local directory (".$search.")", LOGGER_DEBUG);
255 if ($jj->tags != "") {
256 $data["keywords"] = $jj->tags;
259 $data["server_url"] = $data["baseurl"];
261 GContact::update($data);
263 logger("Profile ".$jj->url." is not responding or no Friendica contact - but network ".$data["network"], LOGGER_DEBUG);
267 Cache::set("dirsearch:".$search, time(), CACHE_DAY);
271 * @brief Search for GNU Social user with gstools.org
273 * @param string $search User name
275 private static function gsSearchUser($search) {
277 // Currently disabled, since the service isn't available anymore.
278 // It is not removed since I hope that there will be a successor.
283 $url = "http://gstools.org/api/users_search/".urlencode($search);
285 $result = Network::curl($url);
286 if (!$result["success"]) {
290 $contacts = json_decode($result["body"]);
292 if ($contacts->status == 'ERROR') {
296 /// @TODO AS is considered as a notation for constants (as they usually being written all upper-case)
297 /// @TODO find all those and convert to all lower-case which is a keyword then
298 foreach ($contacts->data AS $user) {
299 $contact = Probe::uri($user->site_address."/".$user->name);
300 if ($contact["network"] != NETWORK_PHANTOM) {
301 $contact["about"] = $user->description;
302 GContact::update($contact);