]> git.mxchange.org Git - friendica.git/blob - src/Worker/DiscoverPoCo.php
55eeec98f2e024843cb58a162746e8d3b4c92d7b
[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 use Friendica\Util\Strings;
19
20 class DiscoverPoCo
21 {
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 = '')
24         {
25                 /*
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
35                 */
36
37                 $search = "";
38                 $mode = 0;
39                 if ($command == "dirsearch") {
40                         $search = urldecode($param1);
41                         $mode = 1;
42                 } elseif ($command == "checkcontact") {
43                         $mode = 2;
44                 } elseif ($command == "suggestions") {
45                         $mode = 3;
46                 } elseif ($command == "server") {
47                         $mode = 4;
48                 } elseif ($command == "update_server") {
49                         $mode = 5;
50                 } elseif ($command == "update_server_directory") {
51                         $mode = 6;
52                 } elseif ($command == "load") {
53                         $mode = 7;
54                 } elseif ($command == "check_profile") {
55                         $mode = 8;
56                 } elseif ($command !== "") {
57                         Logger::log("Unknown or missing parameter ".$command."\n");
58                         return;
59                 }
60
61                 Logger::log('start '.$search);
62
63                 if ($mode == 8) {
64                         if ($param1 != "") {
65                                 PortableContact::lastUpdated($param1, true);
66                         }
67                 } elseif ($mode == 7) {
68                         if (!empty($param4)) {
69                                 $url = $param4;
70                         } else {
71                                 $url = '';
72                         }
73                         PortableContact::load(intval($param1), intval($param2), intval($param3), $url);
74                 } elseif ($mode == 6) {
75                         PortableContact::discoverSingleServer(intval($param1));
76                 } elseif ($mode == 5) {
77                         self::updateServer();
78                 } elseif ($mode == 4) {
79                         $server_url = $param1;
80                         if ($server_url == "") {
81                                 return;
82                         }
83                         $server_url = filter_var($server_url, FILTER_SANITIZE_URL);
84                         if (substr(Strings::normaliseLink($server_url), 0, 7) != "http://") {
85                                 return;
86                         }
87                         $result = "Checking server ".$server_url." - ";
88                         $ret = PortableContact::checkServer($server_url);
89                         if ($ret) {
90                                 $result .= "success";
91                         } else {
92                                 $result .= "failed";
93                         }
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();
105
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();
109                         }
110                 }
111
112                 Logger::log('end '.$search);
113
114                 return;
115         }
116
117         /**
118          * @brief Updates the first 250 servers
119          *
120          */
121         private static function updateServer() {
122                 $r = q("SELECT `url`, `created`, `last_failure`, `last_contact` FROM `gserver` ORDER BY rand()");
123
124                 if (!DBA::isResult($r)) {
125                         return;
126                 }
127
128                 $updated = 0;
129
130                 foreach ($r AS $server) {
131                         if (!PortableContact::updateNeeded($server["created"], "", $server["last_failure"], $server["last_contact"])) {
132                                 continue;
133                         }
134                         Logger::log('Update server status for server '.$server["url"], Logger::DEBUG);
135
136                         Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server["url"]);
137
138                         if (++$updated > 250) {
139                                 return;
140                         }
141                 }
142         }
143
144         private static function discoverUsers() {
145                 Logger::log("Discover users", Logger::DEBUG);
146
147                 $starttime = time();
148
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));
155
156                 if (!$users) {
157                         return;
158                 }
159                 $checked = 0;
160
161                 foreach ($users AS $user) {
162
163                         $urlparts = parse_url($user["url"]);
164                         if (!isset($urlparts["scheme"])) {
165                                 DBA::update('gcontact', ['network' => Protocol::PHANTOM],
166                                         ['nurl' => Strings::normaliseLink($user["url"])]);
167                                 continue;
168                          }
169
170                         if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
171                                 $networks = ["twitter.com" => Protocol::TWITTER, "identi.ca" => Protocol::PUMPIO];
172
173                                 DBA::update('gcontact', ['network' => $networks[$urlparts["host"]]],
174                                         ['nurl' => Strings::normaliseLink($user["url"])]);
175                                 continue;
176                         }
177
178                         $server_url = PortableContact::detectServer($user["url"]);
179                         $force_update = false;
180
181                         if ($user["server_url"] != "") {
182
183                                 $force_update = (Strings::normaliseLink($user["server_url"]) != Strings::normaliseLink($server_url));
184
185                                 $server_url = $user["server_url"];
186                         }
187
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"]);
191
192                                 if (++$checked > 100) {
193                                         return;
194                                 }
195                         } else {
196                                 DBA::update('gcontact', ['last_failure' => DateTimeFormat::utcNow()],
197                                         ['nurl' => Strings::normaliseLink($user["url"])]);
198                         }
199
200                         // Quit the loop after 3 minutes
201                         if (time() > ($starttime + 180)) {
202                                 return;
203                         }
204                 }
205         }
206
207         private static function discoverDirectory($search) {
208
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);
214                                 return;
215                         }
216                 }
217
218                 $x = Network::fetchUrl(get_server()."/lsearch?p=1&n=500&search=".urlencode($search));
219                 $j = json_decode($x);
220
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);
227
228                                         if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
229                                                 ($exists[0]["updated"] < $exists[0]["last_failure"])) {
230                                                 continue;
231                                         }
232                                         // Update the contact
233                                         PortableContact::lastUpdated($jj->url);
234                                         continue;
235                                 }
236
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);
241                                                 continue;
242                                         }
243                                         Logger::log("Friendica server ".$server_url." seems to be okay.", Logger::DEBUG);
244                                 }
245
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);
250
251                                         if ($jj->tags != "") {
252                                                 $data["keywords"] = $jj->tags;
253                                         }
254
255                                         $data["server_url"] = $data["baseurl"];
256
257                                         GContact::update($data);
258                                 } else {
259                                         Logger::log("Profile ".$jj->url." is not responding or no Friendica contact - but network ".$data["network"], Logger::DEBUG);
260                                 }
261                         }
262                 }
263                 Cache::set("dirsearch:".$search, time(), Cache::DAY);
264         }
265
266         /**
267          * @brief Search for GNU Social user with gstools.org
268          *
269          * @param string $search User name
270          */
271         private static function gsSearchUser($search) {
272
273                 // Currently disabled, since the service isn't available anymore.
274                 // It is not removed since I hope that there will be a successor.
275                 return false;
276
277                 $url = "http://gstools.org/api/users_search/".urlencode($search);
278
279                 $curlResult = Network::curl($url);
280                 if (!$curlResult->isSuccess()) {
281                         return false;
282                 }
283
284                 $contacts = json_decode($curlResult->getBody());
285
286                 if ($contacts->status == 'ERROR') {
287                         return false;
288                 }
289
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);
297                         }
298                 }
299         }
300 }