]> git.mxchange.org Git - friendica.git/blob - src/Worker/DiscoverPoCo.php
Review update
[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
16 require_once 'include/datetime.php';
17
18 class DiscoverPoCo {
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                 if ($command == "dirsearch") {
35                         $search = urldecode($param1);
36                         $mode = 1;
37                 } elseif ($command == "checkcontact") {
38                         $mode = 2;
39                 } elseif ($command == "suggestions") {
40                         $mode = 3;
41                 } elseif ($command == "server") {
42                         $mode = 4;
43                 } elseif ($command == "update_server") {
44                         $mode = 5;
45                 } elseif ($command == "update_server_directory") {
46                         $mode = 6;
47                 } elseif ($command == "load") {
48                         $mode = 7;
49                 } elseif ($command == "check_profile") {
50                         $mode = 8;
51                 } elseif ($command == '') {
52                         $search = "";
53                         $mode = 0;
54                 } else {
55                         logger("Unknown or missing parameter ".$command."\n");
56                         return;
57                 }
58
59                 logger('start '.$search);
60
61                 if ($mode == 8) {
62                         if ($param1 != "") {
63                                 PortableContact::lastUpdated($param1, true);
64                         }
65                 } elseif ($mode == 7) {
66                         if (!empty($param4)) {
67                                 $url = $param4;
68                         } else {
69                                 $url = '';
70                         }
71                         PortableContact::load(intval($param1), intval($param2), intval($param3), $url);
72                 } elseif ($mode == 6) {
73                         PortableContact::discoverSingleServer(intval($param1));
74                 } elseif ($mode == 5) {
75                         self::updateServer();
76                 } elseif ($mode == 4) {
77                         $server_url = $param1;
78                         if ($server_url == "") {
79                                 return;
80                         }
81                         $server_url = filter_var($server_url, FILTER_SANITIZE_URL);
82                         if (substr(normalise_link($server_url), 0, 7) != "http://") {
83                                 return;
84                         }
85                         $result = "Checking server ".$server_url." - ";
86                         $ret = PortableContact::checkServer($server_url);
87                         if ($ret) {
88                                 $result .= "success";
89                         } else {
90                                 $result .= "failed";
91                         }
92                         logger($result, LOGGER_DEBUG);
93                 } elseif ($mode == 3) {
94                         GContact::updateSuggestions();
95                 } elseif (($mode == 2) && Config::get('system', 'poco_completion')) {
96                         self::discoverUsers();
97                 } elseif (($mode == 1) && ($search != "") && Config::get('system', 'poco_local_search')) {
98                         self::discoverDirectory($search);
99                         self::gsSearchUser($search);
100                 } elseif (($mode == 0) && ($search == "") && (Config::get('system', 'poco_discovery') > 0)) {
101                         // Query Friendica and Hubzilla servers for their users
102                         PortableContact::discover();
103
104                         // Query GNU Social servers for their users ("statistics" addon has to be enabled on the GS server)
105                         if (!Config::get('system', 'ostatus_disabled')) {
106                                 GContact::discoverGsUsers();
107                         }
108                 }
109
110                 logger('end '.$search);
111
112                 return;
113         }
114
115         /**
116          * @brief Updates the first 250 servers
117          *
118          */
119         private static function updateServer() {
120                 $r = q("SELECT `url`, `created`, `last_failure`, `last_contact` FROM `gserver` ORDER BY rand()");
121
122                 if (!DBM::is_result($r)) {
123                         return;
124                 }
125
126                 $updated = 0;
127
128                 foreach ($r AS $server) {
129                         if (!PortableContact::updateNeeded($server["created"], "", $server["last_failure"], $server["last_contact"])) {
130                                 continue;
131                         }
132                         logger('Update server status for server '.$server["url"], LOGGER_DEBUG);
133
134                         Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server["url"]);
135
136                         if (++$updated > 250) {
137                                 return;
138                         }
139                 }
140         }
141
142         private static function discoverUsers() {
143                 logger("Discover users", LOGGER_DEBUG);
144
145                 $starttime = time();
146
147                 $users = q("SELECT `url`, `created`, `updated`, `last_failure`, `last_contact`, `server_url`, `network` FROM `gcontact`
148                                 WHERE `last_contact` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
149                                         `last_failure` < UTC_TIMESTAMP - INTERVAL 1 MONTH AND
150                                         `network` IN ('%s', '%s', '%s', '%s', '') ORDER BY rand()",
151                                 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA),
152                                 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_FEED));
153
154                 if (!$users) {
155                         return;
156                 }
157                 $checked = 0;
158
159                 foreach ($users AS $user) {
160
161                         $urlparts = parse_url($user["url"]);
162                         if (!isset($urlparts["scheme"])) {
163                                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
164                                         dbesc(NETWORK_PHANTOM), dbesc(normalise_link($user["url"])));
165                                 continue;
166                          }
167
168                         if (in_array($urlparts["host"], ["www.facebook.com", "facebook.com", "twitter.com",
169                                                                 "identi.ca", "alpha.app.net"])) {
170                                 $networks = ["www.facebook.com" => NETWORK_FACEBOOK,
171                                                 "facebook.com" => NETWORK_FACEBOOK,
172                                                 "twitter.com" => NETWORK_TWITTER,
173                                                 "identi.ca" => NETWORK_PUMPIO,
174                                                 "alpha.app.net" => NETWORK_APPNET];
175
176                                 q("UPDATE `gcontact` SET `network` = '%s' WHERE `nurl` = '%s'",
177                                         dbesc($networks[$urlparts["host"]]), dbesc(normalise_link($user["url"])));
178                                 continue;
179                         }
180
181                         $server_url = PortableContact::detectServer($user["url"]);
182                         $force_update = false;
183
184                         if ($user["server_url"] != "") {
185
186                                 $force_update = (normalise_link($user["server_url"]) != normalise_link($server_url));
187
188                                 $server_url = $user["server_url"];
189                         }
190
191                         if ((($server_url == "") && ($user["network"] == NETWORK_FEED)) || $force_update || PortableContact::checkServer($server_url, $user["network"])) {
192                                 logger('Check profile '.$user["url"]);
193                                 Worker::add(PRIORITY_LOW, "DiscoverPoCo", "check_profile", $user["url"]);
194
195                                 if (++$checked > 100) {
196                                         return;
197                                 }
198                         } else {
199                                 q("UPDATE `gcontact` SET `last_failure` = '%s' WHERE `nurl` = '%s'",
200                                         dbesc(datetime_convert()), dbesc(normalise_link($user["url"])));
201                         }
202
203                         // Quit the loop after 3 minutes
204                         if (time() > ($starttime + 180)) {
205                                 return;
206                         }
207                 }
208         }
209
210         private static function discoverDirectory($search) {
211
212                 $data = Cache::get("dirsearch:".$search);
213                 if (!is_null($data)) {
214                         // Only search for the same item every 24 hours
215                         if (time() < $data + (60 * 60 * 24)) {
216                                 logger("Already searched for ".$search." in the last 24 hours", LOGGER_DEBUG);
217                                 return;
218                         }
219                 }
220
221                 $x = Network::fetchUrl(get_server()."/lsearch?p=1&n=500&search=".urlencode($search));
222                 $j = json_decode($x);
223
224                 if (count($j->results)) {
225                         foreach ($j->results as $jj) {
226                                 // Check if the contact already exists
227                                 $exists = q("SELECT `id`, `last_contact`, `last_failure`, `updated` FROM `gcontact` WHERE `nurl` = '%s'", normalise_link($jj->url));
228                                 if (DBM::is_result($exists)) {
229                                         logger("Profile ".$jj->url." already exists (".$search.")", LOGGER_DEBUG);
230
231                                         if (($exists[0]["last_contact"] < $exists[0]["last_failure"]) &&
232                                                 ($exists[0]["updated"] < $exists[0]["last_failure"])) {
233                                                 continue;
234                                         }
235                                         // Update the contact
236                                         PortableContact::lastUpdated($jj->url);
237                                         continue;
238                                 }
239
240                                 $server_url = PortableContact::detectServer($jj->url);
241                                 if ($server_url != '') {
242                                         if (!PortableContact::checkServer($server_url)) {
243                                                 logger("Friendica server ".$server_url." doesn't answer.", LOGGER_DEBUG);
244                                                 continue;
245                                         }
246                                         logger("Friendica server ".$server_url." seems to be okay.", LOGGER_DEBUG);
247                                 }
248
249                                 $data = Probe::uri($jj->url);
250                                 if ($data["network"] == NETWORK_DFRN) {
251                                         logger("Profile ".$jj->url." is reachable (".$search.")", LOGGER_DEBUG);
252                                         logger("Add profile ".$jj->url." to local directory (".$search.")", LOGGER_DEBUG);
253
254                                         if ($jj->tags != "") {
255                                                 $data["keywords"] = $jj->tags;
256                                         }
257
258                                         $data["server_url"] = $data["baseurl"];
259
260                                         GContact::update($data);
261                                 } else {
262                                         logger("Profile ".$jj->url." is not responding or no Friendica contact - but network ".$data["network"], LOGGER_DEBUG);
263                                 }
264                         }
265                 }
266                 Cache::set("dirsearch:".$search, time(), CACHE_DAY);
267         }
268
269         /**
270          * @brief Search for GNU Social user with gstools.org
271          *
272          * @param string $search User name
273          */
274         private static function gsSearchUser($search) {
275
276                 // Currently disabled, since the service isn't available anymore.
277                 // It is not removed since I hope that there will be a successor.
278                 return false;
279
280                 $a = get_app();
281
282                 $url = "http://gstools.org/api/users_search/".urlencode($search);
283
284                 $result = Network::curl($url);
285                 if (!$result["success"]) {
286                         return false;
287                 }
288
289                 $contacts = json_decode($result["body"]);
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"] != NETWORK_PHANTOM) {
300                                 $contact["about"] = $user->description;
301                                 GContact::update($contact);
302                         }
303                 }
304         }
305 }