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