3 * @file src/Worker/DiscoverPoCo.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
9 use Friendica\Core\Logger;
10 use Friendica\Core\Protocol;
11 use Friendica\Core\Worker;
12 use Friendica\Database\DBA;
13 use Friendica\Model\GContact;
14 use Friendica\Network\Probe;
15 use Friendica\Protocol\PortableContact;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Network;
18 use Friendica\Util\Strings;
22 /// @todo Clean up this mess of a parameter hell and split it in several classes
23 public static function execute($command = '', $param1 = '', $param2 = '', $param3 = '', $param4 = '')
26 This function can be called in these ways:
27 - dirsearch <search pattern>: Searches for "search pattern" in the directory. "search pattern" is url encoded.
28 - checkcontact: Updates gcontact entries
29 - suggestions: Discover other servers for their contacts.
30 - server <poco url>: Searches for the poco server list. "poco url" is base64 encoded.
31 - update_server: Frequently check the first 250 servers for vitality.
32 - update_server_directory: Discover the given server id for their contacts
33 - PortableContact::load: Load POCO data from a given POCO address
34 - check_profile: Update remote profile data
39 if ($command == "dirsearch") {
40 $search = urldecode($param1);
42 } elseif ($command == "checkcontact") {
44 } elseif ($command == "suggestions") {
46 } elseif ($command == "server") {
48 } elseif ($command == "update_server") {
50 } elseif ($command == "update_server_directory") {
52 } elseif ($command == "load") {
54 } elseif ($command == "check_profile") {
56 } elseif ($command !== "") {
57 Logger::log("Unknown or missing parameter ".$command."\n");
61 Logger::log('start '.$search);
65 PortableContact::lastUpdated($param1, true);
67 } elseif ($mode == 7) {
68 if (!empty($param4)) {
73 PortableContact::load(intval($param1), intval($param2), intval($param3), $url);
74 } elseif ($mode == 6) {
75 PortableContact::discoverSingleServer(intval($param1));
76 } elseif ($mode == 5) {
78 } elseif ($mode == 4) {
79 $server_url = $param1;
80 if ($server_url == "") {
83 $server_url = filter_var($server_url, FILTER_SANITIZE_URL);
84 if (substr(Strings::normaliseLink($server_url), 0, 7) != "http://") {
87 $result = "Checking server ".$server_url." - ";
88 $ret = PortableContact::checkServer($server_url);
94 Logger::log($result, Logger::DEBUG);
95 } elseif ($mode == 3) {
96 GContact::updateSuggestions();
97 } elseif (($mode == 2) && Config::get('system', 'poco_completion')) {
98 self::discoverUsers();
99 } elseif (($mode == 1) && ($search != "") && Config::get('system', 'poco_local_search')) {
100 self::discoverDirectory($search);
101 self::gsSearchUser($search);
102 } elseif (($mode == 0) && ($search == "") && (Config::get('system', 'poco_discovery') > 0)) {
103 // Query Friendica and Hubzilla servers for their users
104 PortableContact::discover();
106 // Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server)
107 if (!Config::get('system', 'ostatus_disabled')) {
108 GContact::discoverGsUsers();
112 Logger::log('end '.$search);
118 * @brief Updates the first 250 servers
121 private static function updateServer() {
122 $r = q("SELECT `url`, `created`, `last_failure`, `last_contact` FROM `gserver` ORDER BY rand()");
124 if (!DBA::isResult($r)) {
130 foreach ($r AS $server) {
131 if (!PortableContact::updateNeeded($server["created"], "", $server["last_failure"], $server["last_contact"])) {
134 Logger::log('Update server status for server '.$server["url"], Logger::DEBUG);
136 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server["url"]);
138 if (++$updated > 250) {
144 private static function discoverUsers() {
145 Logger::log("Discover users", Logger::DEBUG);
149 $users = q("SELECT `url`, `created`, `updated`, `last_failure`, `last_contact`, `server_url`, `network` FROM `gcontact`
150 WHERE `last_contact` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
151 `last_failure` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
152 `network` IN ('%s', '%s', '%s', '%s', '') ORDER BY rand()",
153 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA),
154 DBA::escape(Protocol::OSTATUS), DBA::escape(Protocol::FEED));
161 foreach ($users AS $user) {
163 $urlparts = parse_url($user["url"]);
164 if (!isset($urlparts["scheme"])) {
165 DBA::update('gcontact', ['network' => Protocol::PHANTOM],
166 ['nurl' => Strings::normaliseLink($user["url"])]);
170 if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
171 $networks = ["twitter.com" => Protocol::TWITTER, "identi.ca" => Protocol::PUMPIO];
173 DBA::update('gcontact', ['network' => $networks[$urlparts["host"]]],
174 ['nurl' => Strings::normaliseLink($user["url"])]);
178 $server_url = PortableContact::detectServer($user["url"]);
179 $force_update = false;
181 if ($user["server_url"] != "") {
183 $force_update = (Strings::normaliseLink($user["server_url"]) != Strings::normaliseLink($server_url));
185 $server_url = $user["server_url"];
188 if ((($server_url == "") && ($user["network"] == Protocol::FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) {
189 Logger::log('Check profile '.$user["url"]);
190 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]);
192 if (++$checked > 100) {
196 DBA::update('gcontact', ['last_failure' => DateTimeFormat::utcNow()],
197 ['nurl' => Strings::normaliseLink($user["url"])]);
200 // Quit the loop after 3 minutes
201 if (time() > ($starttime + 180)) {
207 private static function discoverDirectory($search) {
209 $data = Cache::get("dirsearch:".$search);
210 if (!is_null($data)) {
211 // Only search for the same item every 24 hours
212 if (time() < $data + (60 * 60 * 24)) {
213 Logger::log("Already searched for ".$search." in the last 24 hours", Logger::DEBUG);
218 $x = Network::fetchUrl(get_server()."/lsearch?p=1&n=500&search=".urlencode($search));
219 $j = json_decode($x);
221 if (!empty($j->results)) {
222 foreach ($j->results as $jj) {
223 // Check if the contact already exists
224 $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", Strings::normaliseLink($jj->url));
225 if (DBA::isResult($exists)) {
226 Logger::log("Profile ".$jj->url." already exists (".$search.")", Logger::DEBUG);
228 if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
229 ($exists[0]["updated"] < $exists[0]["last_failure"])) {
232 // Update the contact
233 PortableContact::lastUpdated($jj->url);
237 $server_url = PortableContact::detectServer($jj->url);
238 if ($server_url != '') {
239 if (!PortableContact::checkServer($server_url)) {
240 Logger::log("Friendica server ".$server_url." doesn't answer.", Logger::DEBUG);
243 Logger::log("Friendica server ".$server_url." seems to be okay.", Logger::DEBUG);
246 $data = Probe::uri($jj->url);
247 if ($data["network"] == Protocol::DFRN) {
248 Logger::log("Profile ".$jj->url." is reachable (".$search.")", Logger::DEBUG);
249 Logger::log("Add profile ".$jj->url." to local directory (".$search.")", Logger::DEBUG);
251 if ($jj->tags != "") {
252 $data["keywords"] = $jj->tags;
255 $data["server_url"] = $data["baseurl"];
257 GContact::update($data);
259 Logger::log("Profile ".$jj->url." is not responding or no Friendica contact - but network ".$data["network"], Logger::DEBUG);
263 Cache::set("dirsearch:".$search, time(), Cache::DAY);
267 * @brief Search for GNU Social user with gstools.org
269 * @param string $search User name
271 private static function gsSearchUser($search) {
273 // Currently disabled, since the service isn't available anymore.
274 // It is not removed since I hope that there will be a successor.
277 $url = "http://gstools.org/api/users_search/".urlencode($search);
279 $curlResult = Network::curl($url);
280 if (!$curlResult->isSuccess()) {
284 $contacts = json_decode($curlResult->getBody());
286 if ($contacts->status == 'ERROR') {
290 /// @TODO AS is considered as a notation for constants (as they usually being written all upper-case)
291 /// @TODO find all those and convert to all lower-case which is a keyword then
292 foreach ($contacts->data AS $user) {
293 $contact = Probe::uri($user->site_address."/".$user->name);
294 if ($contact["network"] != Protocol::PHANTOM) {
295 $contact["about"] = $user->description;
296 GContact::update($contact);