]> git.mxchange.org Git - friendica.git/blob - src/Worker/DiscoverPoCo.php
5bcff6d1a73b3ab53b44443e2d444b3641c3ad80
[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\DBM;
11 use Friendica\Model\GContact;
12 use Friendica\Network\Probe;
13 use Friendica\Protocol\PortableContact;
14 use Friendica\Util\Network;
15 use Friendica\Util\Temporal;
16
17 require_once 'include/datetime.php';
18
19 class DiscoverPoCo {
20         /// @todo Clean up this mess of a parameter hell and split it in several classes
21         public static function execute($command = '', $param1 = '', $param2 = '', $param3 = '', $param4 = '')
22         {
23                 /*
24                 This function can be called in these ways:
25                 - dirsearch <search pattern>: Searches for "search pattern" in the directory. "search pattern" is url encoded.
26                 - checkcontact: Updates gcontact entries
27                 - suggestions: Discover other servers for their contacts.
28                 - server <poco url>: Searches for the poco server list. "poco url" is base64 encoded.
29                 - update_server: Frequently check the first 250 servers for vitality.
30                 - update_server_directory: Discover the given server id for their contacts
31                 - PortableContact::load: Load POCO data from a given POCO address
32                 - check_profile: Update remote profile data
33                 */
34
35                 if ($command == "dirsearch") {
36                         $search = urldecode($param1);
37                         $mode = 1;
38                 } elseif ($command == "checkcontact") {
39                         $mode = 2;
40                 } elseif ($command == "suggestions") {
41                         $mode = 3;
42                 } elseif ($command == "server") {
43                         $mode = 4;
44                 } elseif ($command == "update_server") {
45                         $mode = 5;
46                 } elseif ($command == "update_server_directory") {
47                         $mode = 6;
48                 } elseif ($command == "load") {
49                         $mode = 7;
50                 } elseif ($command == "check_profile") {
51                         $mode = 8;
52                 } elseif ($command == '') {
53                         $search = "";
54                         $mode = 0;
55                 } else {
56                         logger("Unknown or missing parameter ".$command."\n");
57                         return;
58                 }
59
60                 logger('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($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('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 (!DBM::is_result($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('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("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                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA),
153                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_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                                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
165                                         dbesc(NETWORK_PHANTOM), dbesc(normalise_link($user["url"])));
166                                 continue;
167                          }
168
169                         if (in_array($urlparts["host"], ["www.facebook.com", "facebook.com", "twitter.com",
170                                                                 "identi.ca", "alpha.app.net"])) {
171                                 $networks = ["www.facebook.com" => NETWORK_FACEBOOK,
172                                                 "facebook.com" => NETWORK_FACEBOOK,
173                                                 "twitter.com" => NETWORK_TWITTER,
174                                                 "identi.ca" => NETWORK_PUMPIO,
175                                                 "alpha.app.net" => NETWORK_APPNET];
176
177                                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
178                                         dbesc($networks[$urlparts["host"]]), dbesc(normalise_link($user["url"])));
179                                 continue;
180                         }
181
182                         $server_url = PortableContact::detectServer($user["url"]);
183                         $force_update = false;
184
185                         if ($user["server_url"] != "") {
186
187                                 $force_update = (normalise_link($user["server_url"]) != normalise_link($server_url));
188
189                                 $server_url = $user["server_url"];
190                         }
191
192                         if ((($server_url == "") && ($user["network"] == NETWORK_FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) {
193                                 logger('Check profile '.$user["url"]);
194                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]);
195
196                                 if (++$checked > 100) {
197                                         return;
198                                 }
199                         } else {
200                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
201                                         dbesc(Temporal::convert()), dbesc(normalise_link($user["url"])));
202                         }
203
204                         // Quit the loop after 3 minutes
205                         if (time() > ($starttime + 180)) {
206                                 return;
207                         }
208                 }
209         }
210
211         private static function discoverDirectory($search) {
212
213                 $data = Cache::get("dirsearch:".$search);
214                 if (!is_null($data)) {
215                         // Only search for the same item every 24 hours
216                         if (time() < $data + (60 * 60 * 24)) {
217                                 logger("Already searched for ".$search." in the last 24 hours", LOGGER_DEBUG);
218                                 return;
219                         }
220                 }
221
222                 $x = Network::fetchUrl(get_server()."/lsearch?p=1&n=500&search=".urlencode($search));
223                 $j = json_decode($x);
224
225                 if (count($j->results)) {
226                         foreach ($j->results as $jj) {
227                                 // Check if the contact already exists
228                                 $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url));
229                                 if (DBM::is_result($exists)) {
230                                         logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
231
232                                         if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
233                                                 ($exists[0]["updated"] < $exists[0]["last_failure"])) {
234                                                 continue;
235                                         }
236                                         // Update the contact
237                                         PortableContact::lastUpdated($jj->url);
238                                         continue;
239                                 }
240
241                                 $server_url = PortableContact::detectServer($jj->url);
242                                 if ($server_url != '') {
243                                         if (!PortableContact::checkServer($server_url)) {
244                                                 logger("Friendica server ".$server_url." doesn't answer.", LOGGER_DEBUG);
245                                                 continue;
246                                         }
247                                         logger("Friendica server ".$server_url." seems to be okay.", LOGGER_DEBUG);
248                                 }
249
250                                 $data = Probe::uri($jj->url);
251                                 if ($data["network"] == NETWORK_DFRN) {
252                                         logger("Profile ".$jj->url." is reachable (".$search.")", LOGGER_DEBUG);
253                                         logger("Add profile ".$jj->url." to local directory (".$search.")", LOGGER_DEBUG);
254
255                                         if ($jj->tags != "") {
256                                                 $data["keywords"] = $jj->tags;
257                                         }
258
259                                         $data["server_url"] = $data["baseurl"];
260
261                                         GContact::update($data);
262                                 } else {
263                                         logger("Profile ".$jj->url." is not responding or no Friendica contact - but network ".$data["network"], LOGGER_DEBUG);
264                                 }
265                         }
266                 }
267                 Cache::set("dirsearch:".$search, time(), CACHE_DAY);
268         }
269
270         /**
271          * @brief Search for GNU Social user with gstools.org
272          *
273          * @param string $search User name
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                 $a = get_app();
282
283                 $url = "http://gstools.org/api/users_search/".urlencode($search);
284
285                 $result = Network::curl($url);
286                 if (!$result["success"]) {
287                         return false;
288                 }
289
290                 $contacts = json_decode($result["body"]);
291
292                 if ($contacts->status == 'ERROR') {
293                         return false;
294                 }
295
296                 /// @TODO AS is considered as a notation for constants (as they usually being written all upper-case)
297                 /// @TODO find all those and convert to all lower-case which is a keyword then
298                 foreach ($contacts->data AS $user) {
299                         $contact = Probe::uri($user->site_address."/".$user->name);
300                         if ($contact["network"] != NETWORK_PHANTOM) {
301                                 $contact["about"] = $user->description;
302                                 GContact::update($contact);
303                         }
304                 }
305         }
306 }