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