]> git.mxchange.org Git - friendica.git/blob - src/Worker/DiscoverPoCo.php
a82fa12087ac9459bcc72c8cb4aba643a5663a3a
[friendica.git] / src / Worker / DiscoverPoCo.php
1 <?php
2 /**
3  * @file src/Worker/DiscoverPoCo.php
4  */
5 namespace Friendica\Worker;
6
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;
16
17 class DiscoverPoCo {
18         /// @todo Clean up this mess of a parameter hell and split it in several classes
19         public static function execute($command = '', $param1 = '', $param2 = '', $param3 = '', $param4 = '')
20         {
21                 /*
22                 This function can be called in these ways:
23                 - dirsearch <search pattern>: Searches for "search pattern" in the directory. "search pattern" is url encoded.
24                 - checkcontact: Updates gcontact entries
25                 - suggestions: Discover other servers for their contacts.
26                 - server <poco url>: Searches for the poco server list. "poco url" is base64 encoded.
27                 - update_server: Frequently check the first 250 servers for vitality.
28                 - update_server_directory: Discover the given server id for their contacts
29                 - PortableContact::load: Load POCO data from a given POCO address
30                 - check_profile: Update remote profile data
31                 */
32
33                 $search = "";
34                 $mode = 0;
35                 if ($command == "dirsearch") {
36                         $search = urldecode($param1);
37                         $mode = 1;
38                 } elseif ($command == "checkcontact") {
39                         $mode = 2;
40                 } elseif ($command == "suggestions") {
41                         $mode = 3;
42                 } elseif ($command == "server") {
43                         $mode = 4;
44                 } elseif ($command == "update_server") {
45                         $mode = 5;
46                 } elseif ($command == "update_server_directory") {
47                         $mode = 6;
48                 } elseif ($command == "load") {
49                         $mode = 7;
50                 } elseif ($command == "check_profile") {
51                         $mode = 8;
52                 } elseif ($command !== "") {
53                         logger("Unknown or missing parameter ".$command."\n");
54                         return;
55                 }
56
57                 logger('start '.$search);
58
59                 if ($mode == 8) {
60                         if ($param1 != "") {
61                                 PortableContact::lastUpdated($param1, true);
62                         }
63                 } elseif ($mode == 7) {
64                         if (!empty($param4)) {
65                                 $url = $param4;
66                         } else {
67                                 $url = '';
68                         }
69                         PortableContact::load(intval($param1), intval($param2), intval($param3), $url);
70                 } elseif ($mode == 6) {
71                         PortableContact::discoverSingleServer(intval($param1));
72                 } elseif ($mode == 5) {
73                         self::updateServer();
74                 } elseif ($mode == 4) {
75                         $server_url = $param1;
76                         if ($server_url == "") {
77                                 return;
78                         }
79                         $server_url = filter_var($server_url, FILTER_SANITIZE_URL);
80                         if (substr(normalise_link($server_url), 0, 7) != "http://") {
81                                 return;
82                         }
83                         $result = "Checking server ".$server_url." - ";
84                         $ret = PortableContact::checkServer($server_url);
85                         if ($ret) {
86                                 $result .= "success";
87                         } else {
88                                 $result .= "failed";
89                         }
90                         logger($result, LOGGER_DEBUG);
91                 } elseif ($mode == 3) {
92                         GContact::updateSuggestions();
93                 } elseif (($mode == 2) && Config::get('system', 'poco_completion')) {
94                         self::discoverUsers();
95                 } elseif (($mode == 1) && ($search != "") && Config::get('system', 'poco_local_search')) {
96                         self::discoverDirectory($search);
97                         self::gsSearchUser($search);
98                 } elseif (($mode == 0) && ($search == "") && (Config::get('system', 'poco_discovery') > 0)) {
99                         // Query Friendica and Hubzilla servers for their users
100                         PortableContact::discover();
101
102                         // Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server)
103                         if (!Config::get('system', 'ostatus_disabled')) {
104                                 GContact::discoverGsUsers();
105                         }
106                 }
107
108                 logger('end '.$search);
109
110                 return;
111         }
112
113         /**
114          * @brief Updates the first 250 servers
115          *
116          */
117         private static function updateServer() {
118                 $r = q("SELECT `url`, `created`, `last_failure`, `last_contact` FROM `gserver` ORDER BY rand()");
119
120                 if (!DBM::is_result($r)) {
121                         return;
122                 }
123
124                 $updated = 0;
125
126                 foreach ($r AS $server) {
127                         if (!PortableContact::updateNeeded($server["created"], "", $server["last_failure"], $server["last_contact"])) {
128                                 continue;
129                         }
130                         logger('Update server status for server '.$server["url"], LOGGER_DEBUG);
131
132                         Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server["url"]);
133
134                         if (++$updated > 250) {
135                                 return;
136                         }
137                 }
138         }
139
140         private static function discoverUsers() {
141                 logger("Discover users", LOGGER_DEBUG);
142
143                 $starttime = time();
144
145                 $users = q("SELECT `url`, `created`, `updated`, `last_failure`, `last_contact`, `server_url`, `network` FROM `gcontact`
146                                 WHERE `last_contact` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
147                                         `last_failure` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
148                                         `network` IN ('%s', '%s', '%s', '%s', '') ORDER BY rand()",
149                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA),
150                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_FEED));
151
152                 if (!$users) {
153                         return;
154                 }
155                 $checked = 0;
156
157                 foreach ($users AS $user) {
158
159                         $urlparts = parse_url($user["url"]);
160                         if (!isset($urlparts["scheme"])) {
161                                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
162                                         dbesc(NETWORK_PHANTOM), dbesc(normalise_link($user["url"])));
163                                 continue;
164                          }
165
166                         if (in_array($urlparts["host"], ["www.facebook.com", "facebook.com", "twitter.com",
167                                                                 "identi.ca", "alpha.app.net"])) {
168                                 $networks = ["www.facebook.com" => NETWORK_FACEBOOK,
169                                                 "facebook.com" => NETWORK_FACEBOOK,
170                                                 "twitter.com" => NETWORK_TWITTER,
171                                                 "identi.ca" => NETWORK_PUMPIO,
172                                                 "alpha.app.net" => NETWORK_APPNET];
173
174                                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
175                                         dbesc($networks[$urlparts["host"]]), dbesc(normalise_link($user["url"])));
176                                 continue;
177                         }
178
179                         $server_url = PortableContact::detectServer($user["url"]);
180                         $force_update = false;
181
182                         if ($user["server_url"] != "") {
183
184                                 $force_update = (normalise_link($user["server_url"]) != normalise_link($server_url));
185
186                                 $server_url = $user["server_url"];
187                         }
188
189                         if ((($server_url == "") && ($user["network"] == NETWORK_FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) {
190                                 logger('Check profile '.$user["url"]);
191                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]);
192
193                                 if (++$checked > 100) {
194                                         return;
195                                 }
196                         } else {
197                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
198                                         dbesc(DateTimeFormat::utcNow()), dbesc(normalise_link($user["url"])));
199                         }
200
201                         // Quit the loop after 3 minutes
202                         if (time() > ($starttime + 180)) {
203                                 return;
204                         }
205                 }
206         }
207
208         private static function discoverDirectory($search) {
209
210                 $data = Cache::get("dirsearch:".$search);
211                 if (!is_null($data)) {
212                         // Only search for the same item every 24 hours
213                         if (time() < $data + (60 * 60 * 24)) {
214                                 logger("Already searched for ".$search." in the last 24 hours", LOGGER_DEBUG);
215                                 return;
216                         }
217                 }
218
219                 $x = Network::fetchUrl(get_server()."/lsearch?p=1&n=500&search=".urlencode($search));
220                 $j = json_decode($x);
221
222                 if (count($j->results)) {
223                         foreach ($j->results as $jj) {
224                                 // Check if the contact already exists
225                                 $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url));
226                                 if (DBM::is_result($exists)) {
227                                         logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
228
229                                         if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
230                                                 ($exists[0]["updated"] < $exists[0]["last_failure"])) {
231                                                 continue;
232                                         }
233                                         // Update the contact
234                                         PortableContact::lastUpdated($jj->url);
235                                         continue;
236                                 }
237
238                                 $server_url = PortableContact::detectServer($jj->url);
239                                 if ($server_url != '') {
240                                         if (!PortableContact::checkServer($server_url)) {
241                                                 logger("Friendica server ".$server_url." doesn't answer.", LOGGER_DEBUG);
242                                                 continue;
243                                         }
244                                         logger("Friendica server ".$server_url." seems to be okay.", LOGGER_DEBUG);
245                                 }
246
247                                 $data = Probe::uri($jj->url);
248                                 if ($data["network"] == NETWORK_DFRN) {
249                                         logger("Profile ".$jj->url." is reachable (".$search.")", LOGGER_DEBUG);
250                                         logger("Add profile ".$jj->url." to local directory (".$search.")", LOGGER_DEBUG);
251
252                                         if ($jj->tags != "") {
253                                                 $data["keywords"] = $jj->tags;
254                                         }
255
256                                         $data["server_url"] = $data["baseurl"];
257
258                                         GContact::update($data);
259                                 } else {
260                                         logger("Profile ".$jj->url." is not responding or no Friendica contact - but network ".$data["network"], LOGGER_DEBUG);
261                                 }
262                         }
263                 }
264                 Cache::set("dirsearch:".$search, time(), CACHE_DAY);
265         }
266
267         /**
268          * @brief Search for GNU Social user with gstools.org
269          *
270          * @param string $search User name
271          */
272         private static function gsSearchUser($search) {
273
274                 // Currently disabled, since the service isn't available anymore.
275                 // It is not removed since I hope that there will be a successor.
276                 return false;
277
278                 $a = get_app();
279
280                 $url = "http://gstools.org/api/users_search/".urlencode($search);
281
282                 $result = Network::curl($url);
283                 if (!$result["success"]) {
284                         return false;
285                 }
286
287                 $contacts = json_decode($result["body"]);
288
289                 if ($contacts->status == 'ERROR') {
290                         return false;
291                 }
292
293                 /// @TODO AS is considered as a notation for constants (as they usually being written all upper-case)
294                 /// @TODO find all those and convert to all lower-case which is a keyword then
295                 foreach ($contacts->data AS $user) {
296                         $contact = Probe::uri($user->site_address."/".$user->name);
297                         if ($contact["network"] != NETWORK_PHANTOM) {
298                                 $contact["about"] = $user->description;
299                                 GContact::update($contact);
300                         }
301                 }
302         }
303 }