3 * @file src/Worker/DiscoverPoCo.php
5 namespace Friendica\Worker;
7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
9 use Friendica\Core\Protocol;
10 use Friendica\Core\Worker;
11 use Friendica\Database\DBA;
12 use Friendica\Model\GContact;
13 use Friendica\Network\Probe;
14 use Friendica\Protocol\PortableContact;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Network;
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
37 if ($command == "dirsearch") {
38 $search = urldecode($param1);
40 } elseif ($command == "checkcontact") {
42 } elseif ($command == "suggestions") {
44 } elseif ($command == "server") {
46 } elseif ($command == "update_server") {
48 } elseif ($command == "update_server_directory") {
50 } elseif ($command == "load") {
52 } elseif ($command == "check_profile") {
54 } elseif ($command !== "") {
55 logger("Unknown or missing parameter ".$command."\n");
59 logger('start '.$search);
63 PortableContact::lastUpdated($param1, true);
65 } elseif ($mode == 7) {
66 if (!empty($param4)) {
71 PortableContact::load(intval($param1), intval($param2), intval($param3), $url);
72 } elseif ($mode == 6) {
73 PortableContact::discoverSingleServer(intval($param1));
74 } elseif ($mode == 5) {
76 } elseif ($mode == 4) {
77 $server_url = $param1;
78 if ($server_url == "") {
81 $server_url = filter_var($server_url, FILTER_SANITIZE_URL);
82 if (substr(normalise_link($server_url), 0, 7) != "http://") {
85 $result = "Checking server ".$server_url." - ";
86 $ret = PortableContact::checkServer($server_url);
92 logger($result, LOGGER_DEBUG);
93 } elseif ($mode == 3) {
94 GContact::updateSuggestions();
95 } elseif (($mode == 2) && Config::get('system', 'poco_completion')) {
96 self::discoverUsers();
97 } elseif (($mode == 1) && ($search != "") && Config::get('system', 'poco_local_search')) {
98 self::discoverDirectory($search);
99 self::gsSearchUser($search);
100 } elseif (($mode == 0) && ($search == "") && (Config::get('system', 'poco_discovery') > 0)) {
101 // Query Friendica and Hubzilla servers for their users
102 PortableContact::discover();
104 // Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server)
105 if (!Config::get('system', 'ostatus_disabled')) {
106 GContact::discoverGsUsers();
110 logger('end '.$search);
116 * @brief Updates the first 250 servers
119 private static function updateServer() {
120 $r = q("SELECT `url`, `created`, `last_failure`, `last_contact` FROM `gserver` ORDER BY rand()");
122 if (!DBA::isResult($r)) {
128 foreach ($r AS $server) {
129 if (!PortableContact::updateNeeded($server["created"], "", $server["last_failure"], $server["last_contact"])) {
132 logger('Update server status for server '.$server["url"], LOGGER_DEBUG);
134 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server["url"]);
136 if (++$updated > 250) {
142 private static function discoverUsers() {
143 logger("Discover users", LOGGER_DEBUG);
147 $users = q("SELECT `url`, `created`, `updated`, `last_failure`, `last_contact`, `server_url`, `network` FROM `gcontact`
148 WHERE `last_contact` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
149 `last_failure` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
150 `network` IN ('%s', '%s', '%s', '%s', '') ORDER BY rand()",
151 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA),
152 DBA::escape(Protocol::OSTATUS), DBA::escape(Protocol::FEED));
159 foreach ($users AS $user) {
161 $urlparts = parse_url($user["url"]);
162 if (!isset($urlparts["scheme"])) {
163 DBA::update('gcontact', ['network' => Protocol::PHANTOM],
164 ['nurl' => normalise_link($user["url"])]);
168 if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
169 $networks = ["twitter.com" => Protocol::TWITTER, "identi.ca" => Protocol::PUMPIO];
171 DBA::update('gcontact', ['network' => $networks[$urlparts["host"]]],
172 ['nurl' => normalise_link($user["url"])]);
176 $server_url = PortableContact::detectServer($user["url"]);
177 $force_update = false;
179 if ($user["server_url"] != "") {
181 $force_update = (normalise_link($user["server_url"]) != normalise_link($server_url));
183 $server_url = $user["server_url"];
186 if ((($server_url == "") && ($user["network"] == Protocol::FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) {
187 logger('Check profile '.$user["url"]);
188 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]);
190 if (++$checked > 100) {
194 DBA::update('gcontact', ['last_failure' => DateTimeFormat::utcNow()],
195 ['nurl' => normalise_link($user["url"])]);
198 // Quit the loop after 3 minutes
199 if (time() > ($starttime + 180)) {
205 private static function discoverDirectory($search) {
207 $data = Cache::get("dirsearch:".$search);
208 if (!is_null($data)) {
209 // Only search for the same item every 24 hours
210 if (time() < $data + (60 * 60 * 24)) {
211 logger("Already searched for ".$search." in the last 24 hours", LOGGER_DEBUG);
216 $x = Network::fetchUrl(get_server()."/lsearch?p=1&n=500&search=".urlencode($search));
217 $j = json_decode($x);
219 if (!empty($j->results)) {
220 foreach ($j->results as $jj) {
221 // Check if the contact already exists
222 $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url));
223 if (DBA::isResult($exists)) {
224 logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
226 if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
227 ($exists[0]["updated"] < $exists[0]["last_failure"])) {
230 // Update the contact
231 PortableContact::lastUpdated($jj->url);
235 $server_url = PortableContact::detectServer($jj->url);
236 if ($server_url != '') {
237 if (!PortableContact::checkServer($server_url)) {
238 logger("Friendica server ".$server_url." doesn't answer.", LOGGER_DEBUG);
241 logger("Friendica server ".$server_url." seems to be okay.", LOGGER_DEBUG);
244 $data = Probe::uri($jj->url);
245 if ($data["network"] == Protocol::DFRN) {
246 logger("Profile ".$jj->url." is reachable (".$search.")", LOGGER_DEBUG);
247 logger("Add profile ".$jj->url." to local directory (".$search.")", LOGGER_DEBUG);
249 if ($jj->tags != "") {
250 $data["keywords"] = $jj->tags;
253 $data["server_url"] = $data["baseurl"];
255 GContact::update($data);
257 logger("Profile ".$jj->url." is not responding or no Friendica contact - but network ".$data["network"], LOGGER_DEBUG);
261 Cache::set("dirsearch:".$search, time(), CACHE_DAY);
265 * @brief Search for GNU Social user with gstools.org
267 * @param string $search User name
269 private static function gsSearchUser($search) {
271 // Currently disabled, since the service isn't available anymore.
272 // It is not removed since I hope that there will be a successor.
275 $url = "http://gstools.org/api/users_search/".urlencode($search);
277 $curlResult = Network::curl($url);
278 if (!$curlResult->isSuccess()) {
282 $contacts = json_decode($curlResult->getBody());
284 if ($contacts->status == 'ERROR') {
288 /// @TODO AS is considered as a notation for constants (as they usually being written all upper-case)
289 /// @TODO find all those and convert to all lower-case which is a keyword then
290 foreach ($contacts->data AS $user) {
291 $contact = Probe::uri($user->site_address."/".$user->name);
292 if ($contact["network"] != Protocol::PHANTOM) {
293 $contact["about"] = $user->description;
294 GContact::update($contact);