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