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