]> git.mxchange.org Git - friendica.git/blob - src/Worker/DiscoverPoCo.php
8a783e18652a226286877533410211a1830e2be1
[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\Model\Contact;
15 use Friendica\Network\Probe;
16 use Friendica\Protocol\PortableContact;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Network;
19 use Friendica\Util\Strings;
20
21 class DiscoverPoCo
22 {
23         /// @todo Clean up this mess of a parameter hell and split it in several classes
24         public static function execute($command = '', $param1 = '', $param2 = '', $param3 = '', $param4 = '')
25         {
26                 /*
27                 This function can be called in these ways:
28                 - dirsearch <search pattern>: Searches for "search pattern" in the directory. "search pattern" is url encoded.
29                 - checkcontact: Updates gcontact entries
30                 - suggestions: Discover other servers for their contacts.
31                 - server <poco url>: Searches for the poco server list. "poco url" is base64 encoded.
32                 - update_server: Frequently check the first 250 servers for vitality.
33                 - update_server_directory: Discover the given server id for their contacts
34                 - PortableContact::load: Load POCO data from a given POCO address
35                 - check_profile: Update remote profile data
36                 */
37
38                 $search = "";
39                 $mode = 0;
40                 if ($command == "dirsearch") {
41                         $search = urldecode($param1);
42                         $mode = 1;
43                 } elseif ($command == "checkcontact") {
44                         $mode = 2;
45                 } elseif ($command == "suggestions") {
46                         $mode = 3;
47                 } elseif ($command == "server") {
48                         $mode = 4;
49                 } elseif ($command == "update_server") {
50                         $mode = 5;
51                 } elseif ($command == "update_server_directory") {
52                         $mode = 6;
53                 } elseif ($command == "load") {
54                         $mode = 7;
55                 } elseif ($command == "check_profile") {
56                         $mode = 8;
57                 } elseif ($command !== "") {
58                         Logger::log("Unknown or missing parameter ".$command."\n");
59                         return;
60                 }
61
62                 Logger::log('start '.$search);
63
64                 if ($mode == 8) {
65                         if ($param1 != "") {
66                                 PortableContact::lastUpdated($param1, true);
67                         }
68                 } elseif ($mode == 7) {
69                         if (!empty($param4)) {
70                                 $url = $param4;
71                         } else {
72                                 $url = '';
73                         }
74                         PortableContact::load(intval($param1), intval($param2), intval($param3), $url);
75                 } elseif ($mode == 6) {
76                         PortableContact::discoverSingleServer(intval($param1));
77                 } elseif ($mode == 5) {
78                         self::updateServer();
79                 } elseif ($mode == 4) {
80                         $server_url = $param1;
81                         if ($server_url == "") {
82                                 return;
83                         }
84                         $server_url = filter_var($server_url, FILTER_SANITIZE_URL);
85                         if (substr(Strings::normaliseLink($server_url), 0, 7) != "http://") {
86                                 return;
87                         }
88                         $result = "Checking server ".$server_url." - ";
89                         $ret = PortableContact::checkServer($server_url);
90                         if ($ret) {
91                                 $result .= "success";
92                         } else {
93                                 $result .= "failed";
94                         }
95                         Logger::log($result, Logger::DEBUG);
96                 } elseif ($mode == 3) {
97                         GContact::updateSuggestions();
98                 } elseif (($mode == 2) && Config::get('system', 'poco_completion')) {
99                         self::discoverUsers();
100                 } elseif (($mode == 1) && ($search != "") && Config::get('system', 'poco_local_search')) {
101                         self::discoverDirectory($search);
102                         self::gsSearchUser($search);
103                 } elseif (($mode == 0) && ($search == "") && (Config::get('system', 'poco_discovery') != PortableContact::DISABLED)) {
104                         // Query Friendica and Hubzilla servers for their users
105                         PortableContact::discover();
106
107                         // Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server)
108                         if (!Config::get('system', 'ostatus_disabled')) {
109                                 GContact::discoverGsUsers();
110                         }
111                 }
112
113                 Logger::log('end '.$search);
114
115                 return;
116         }
117
118         /**
119          * @brief Updates the first 250 servers
120          *
121          */
122         private static function updateServer() {
123                 $r = q("SELECT `url`, `created`, `last_failure`, `last_contact` FROM `gserver` ORDER BY rand()");
124
125                 if (!DBA::isResult($r)) {
126                         return;
127                 }
128
129                 $updated = 0;
130
131                 foreach ($r AS $server) {
132                         if (!PortableContact::updateNeeded($server["created"], "", $server["last_failure"], $server["last_contact"])) {
133                                 continue;
134                         }
135                         Logger::log('Update server status for server '.$server["url"], Logger::DEBUG);
136
137                         Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server["url"]);
138
139                         if (++$updated > 250) {
140                                 return;
141                         }
142                 }
143         }
144
145         private static function discoverUsers() {
146                 Logger::log("Discover users", Logger::DEBUG);
147
148                 $starttime = time();
149
150                 $users = q("SELECT `url`, `created`, `updated`, `last_failure`, `last_contact`, `server_url`, `network` FROM `gcontact`
151                                 WHERE `last_contact` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
152                                         `last_failure` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
153                                         `network` IN ('%s', '%s', '%s', '%s', '') ORDER BY rand()",
154                                 DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA),
155                                 DBA::escape(Protocol::OSTATUS), DBA::escape(Protocol::FEED));
156
157                 if (!$users) {
158                         return;
159                 }
160                 $checked = 0;
161
162                 foreach ($users AS $user) {
163
164                         $urlparts = parse_url($user["url"]);
165                         if (!isset($urlparts["scheme"])) {
166                                 DBA::update('gcontact', ['network' => Protocol::PHANTOM],
167                                         ['nurl' => Strings::normaliseLink($user["url"])]);
168                                 continue;
169                          }
170
171                         if (in_array($urlparts["host"], ["twitter.com", "identi.ca"])) {
172                                 $networks = ["twitter.com" => Protocol::TWITTER, "identi.ca" => Protocol::PUMPIO];
173
174                                 DBA::update('gcontact', ['network' => $networks[$urlparts["host"]]],
175                                         ['nurl' => Strings::normaliseLink($user["url"])]);
176                                 continue;
177                         }
178
179                         $server_url = Contact::getBasepath($user["url"]);
180                         $force_update = false;
181
182                         if ($user["server_url"] != "") {
183
184                                 $force_update = (Strings::normaliseLink($user["server_url"]) != Strings::normaliseLink($server_url));
185
186                                 $server_url = $user["server_url"];
187                         }
188
189                         if ((($server_url == "") && ($user["network"] == Protocol::FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) {
190                                 Logger::log('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                                 DBA::update('gcontact', ['last_failure' => DateTimeFormat::utcNow()],
198                                         ['nurl' => Strings::normaliseLink($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::log("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 (!empty($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'", Strings::normaliseLink($jj->url));
226                                 if (DBA::isResult($exists)) {
227                                         Logger::log("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 = Contact::getBasepath($jj->url);
239                                 if ($server_url != '') {
240                                         if (!PortableContact::checkServer($server_url)) {
241                                                 Logger::log("Friendica server ".$server_url." doesn't answer.", Logger::DEBUG);
242                                                 continue;
243                                         }
244                                         Logger::log("Friendica server ".$server_url." seems to be okay.", Logger::DEBUG);
245                                 }
246
247                                 $data = Probe::uri($jj->url);
248                                 if ($data["network"] == Protocol::DFRN) {
249                                         Logger::log("Profile ".$jj->url." is reachable (".$search.")", Logger::DEBUG);
250                                         Logger::log("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::log("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          * @return bool
272          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
273          * @throws \ImagickException
274          */
275         private static function gsSearchUser($search) {
276
277                 // Currently disabled, since the service isn't available anymore.
278                 // It is not removed since I hope that there will be a successor.
279                 return false;
280
281                 $url = "http://gstools.org/api/users_search/".urlencode($search);
282
283                 $curlResult = Network::curl($url);
284                 if (!$curlResult->isSuccess()) {
285                         return false;
286                 }
287
288                 $contacts = json_decode($curlResult->getBody());
289
290                 if ($contacts->status == 'ERROR') {
291                         return false;
292                 }
293
294                 /// @TODO AS is considered as a notation for constants (as they usually being written all upper-case)
295                 /// @TODO find all those and convert to all lower-case which is a keyword then
296                 foreach ($contacts->data AS $user) {
297                         $contact = Probe::uri($user->site_address."/".$user->name);
298                         if ($contact["network"] != Protocol::PHANTOM) {
299                                 $contact["about"] = $user->description;
300                                 GContact::update($contact);
301                         }
302                 }
303         }
304 }