]> git.mxchange.org Git - friendica.git/blob - mod/poco.php
Merge pull request #8261 from MrPetovan/task/8251-use-about-for-pdesc
[friendica.git] / mod / poco.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  * @see https://web.archive.org/web/20160405005550/http://portablecontacts.net/draft-spec.html
21  */
22
23 use Friendica\App;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Renderer;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Protocol\PortableContact;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Strings;
33 use Friendica\Util\XML;
34
35 function poco_init(App $a) {
36         $system_mode = false;
37
38         if (intval(DI::config()->get('system', 'block_public')) || (DI::config()->get('system', 'block_local_dir'))) {
39                 throw new \Friendica\Network\HTTPException\ForbiddenException();
40         }
41
42         if ($a->argc > 1) {
43                 $nickname = Strings::escapeTags(trim($a->argv[1]));
44         }
45         if (empty($nickname)) {
46                 $c = q("SELECT * FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1");
47                 if (!DBA::isResult($c)) {
48                         throw new \Friendica\Network\HTTPException\ForbiddenException();
49                 }
50                 $system_mode = true;
51         }
52
53         $format = ($_GET['format'] ?? '') ?: 'json';
54
55         $justme = false;
56         $global = false;
57
58         if ($a->argc > 1 && $a->argv[1] === '@server') {
59                 // List of all servers that this server knows
60                 $ret = PortableContact::serverlist();
61                 header('Content-type: application/json');
62                 echo json_encode($ret);
63                 exit();
64         }
65
66         if ($a->argc > 1 && $a->argv[1] === '@global') {
67                 // List of all profiles that this server recently had data from
68                 $global = true;
69                 $update_limit = date(DateTimeFormat::MYSQL, time() - 30 * 86400);
70         }
71         if ($a->argc > 2 && $a->argv[2] === '@me') {
72                 $justme = true;
73         }
74         if ($a->argc > 3 && $a->argv[3] === '@all') {
75                 $justme = false;
76         }
77         if ($a->argc > 3 && $a->argv[3] === '@self') {
78                 $justme = true;
79         }
80         if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
81                 $cid = intval($a->argv[4]);
82         }
83
84         if (! $system_mode && ! $global) {
85                 $users = q("SELECT `user`.*,`profile`.`hide-friends` from user left join profile on `user`.`uid` = `profile`.`uid`
86                         where `user`.`nickname` = '%s' limit 1",
87                         DBA::escape($nickname)
88                 );
89                 if (! DBA::isResult($users) || $users[0]['hidewall'] || $users[0]['hide-friends']) {
90                         throw new \Friendica\Network\HTTPException\NotFoundException();
91                 }
92
93                 $user = $users[0];
94         }
95
96         if ($justme) {
97                 $sql_extra = " AND `contact`.`self` = 1 ";
98         } else {
99                 $sql_extra = "";
100         }
101
102         if (!empty($cid)) {
103                 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
104         }
105         if (!empty($_GET['updatedSince'])) {
106                 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
107         }
108         if ($global) {
109                 $contacts = q("SELECT count(*) AS `total` FROM `gcontact` WHERE `updated` >= '%s' AND `updated` >= `last_failure` AND NOT `hide` AND `network` IN ('%s', '%s', '%s')",
110                         DBA::escape($update_limit),
111                         DBA::escape(Protocol::DFRN),
112                         DBA::escape(Protocol::DIASPORA),
113                         DBA::escape(Protocol::OSTATUS)
114                 );
115         } elseif ($system_mode) {
116                 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `self` = 1
117                         AND `uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) ");
118         } else {
119                 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
120                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
121                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
122                         intval($user['uid']),
123                         DBA::escape(Protocol::DFRN),
124                         DBA::escape(Protocol::DIASPORA),
125                         DBA::escape(Protocol::OSTATUS),
126                         DBA::escape(Protocol::STATUSNET)
127                 );
128         }
129         if (DBA::isResult($contacts)) {
130                 $totalResults = intval($contacts[0]['total']);
131         } else {
132                 $totalResults = 0;
133         }
134         if (!empty($_GET['startIndex'])) {
135                 $startIndex = intval($_GET['startIndex']);
136         } else {
137                 $startIndex = 0;
138         }
139         $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
140
141         if ($global) {
142                 Logger::log("Start global query", Logger::DEBUG);
143                 $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
144                         ORDER BY `updated` DESC LIMIT %d, %d",
145                         DBA::escape($update_limit),
146                         DBA::escape(Protocol::DFRN),
147                         DBA::escape(Protocol::DIASPORA),
148                         DBA::escape(Protocol::OSTATUS),
149                         intval($startIndex),
150                         intval($itemsPerPage)
151                 );
152         } elseif ($system_mode) {
153                 Logger::log("Start system mode query", Logger::DEBUG);
154                 $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
155                                 `profile`.`gender` AS `pgender`, `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
156                                 `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
157                         FROM `contact` INNER JOIN `profile` ON `profile`.`uid` = `contact`.`uid`
158                                 INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
159                         WHERE `self` = 1
160                         AND `contact`.`uid` IN (SELECT `uid` FROM `pconfig` WHERE `cat` = 'system' AND `k` = 'suggestme' AND `v` = 1) LIMIT %d, %d",
161                         intval($startIndex),
162                         intval($itemsPerPage)
163                 );
164         } else {
165                 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
166                 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
167                         AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
168                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
169                         intval($user['uid']),
170                         DBA::escape(Protocol::DFRN),
171                         DBA::escape(Protocol::DIASPORA),
172                         DBA::escape(Protocol::OSTATUS),
173                         DBA::escape(Protocol::STATUSNET),
174                         intval($startIndex),
175                         intval($itemsPerPage)
176                 );
177         }
178         Logger::log("Query done", Logger::DEBUG);
179
180         $ret = [];
181         if (!empty($_GET['sorted'])) {
182                 $ret['sorted'] = false;
183         }
184         if (!empty($_GET['filtered'])) {
185                 $ret['filtered'] = false;
186         }
187         if (!empty($_GET['updatedSince']) && ! $global) {
188                 $ret['updatedSince'] = false;
189         }
190         $ret['startIndex']   = (int) $startIndex;
191         $ret['itemsPerPage'] = (int) $itemsPerPage;
192         $ret['totalResults'] = (int) $totalResults;
193         $ret['entry']        = [];
194
195
196         $fields_ret = [
197                 'id' => false,
198                 'displayName' => false,
199                 'urls' => false,
200                 'updated' => false,
201                 'preferredUsername' => false,
202                 'photos' => false,
203                 'aboutMe' => false,
204                 'currentLocation' => false,
205                 'network' => false,
206                 'gender' => false,
207                 'tags' => false,
208                 'address' => false,
209                 'contactType' => false,
210                 'generation' => false
211         ];
212
213         if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
214                 foreach ($fields_ret as $k => $v) {
215                         $fields_ret[$k] = true;
216                 }
217         } else {
218                 $fields_req = explode(',', $_GET['fields']);
219                 foreach ($fields_req as $f) {
220                         $fields_ret[trim($f)] = true;
221                 }
222         }
223
224         if (is_array($contacts)) {
225                 if (DBA::isResult($contacts)) {
226                         foreach ($contacts as $contact) {
227                                 if (!isset($contact['updated'])) {
228                                         $contact['updated'] = '';
229                                 }
230
231                                 if (! isset($contact['generation'])) {
232                                         if ($global) {
233                                                 $contact['generation'] = 3;
234                                         } elseif ($system_mode) {
235                                                 $contact['generation'] = 1;
236                                         } else {
237                                                 $contact['generation'] = 2;
238                                         }
239                                 }
240
241                                 if (($contact['about'] == "") && isset($contact['pabout'])) {
242                                         $contact['about'] = $contact['pabout'];
243                                 }
244                                 if ($contact['location'] == "") {
245                                         if (isset($contact['plocation'])) {
246                                                 $contact['location'] = $contact['plocation'];
247                                         }
248                                         if (isset($contact['pregion']) && ( $contact['pregion'] != "")) {
249                                                 if ($contact['location'] != "") {
250                                                         $contact['location'] .= ", ";
251                                                 }
252                                                 $contact['location'] .= $contact['pregion'];
253                                         }
254
255                                         if (isset($contact['pcountry']) && ( $contact['pcountry'] != "")) {
256                                                 if ($contact['location'] != "") {
257                                                         $contact['location'] .= ", ";
258                                                 }
259                                                 $contact['location'] .= $contact['pcountry'];
260                                         }
261                                 }
262
263                                 if (($contact['gender'] == "") && isset($contact['pgender'])) {
264                                         $contact['gender'] = $contact['pgender'];
265                                 }
266                                 if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
267                                         $contact['keywords'] = $contact['pub_keywords'];
268                                 }
269                                 if (isset($contact['account-type'])) {
270                                         $contact['contact-type'] = $contact['account-type'];
271                                 }
272                                 $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
273                                 if (is_null($about)) {
274                                         $about = BBCode::convert($contact['about'], false);
275                                         DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
276                                 }
277
278                                 // Non connected persons can only see the keywords of a Diaspora account
279                                 if ($contact['network'] == Protocol::DIASPORA) {
280                                         $contact['location'] = "";
281                                         $about = "";
282                                         $contact['gender'] = "";
283                                 }
284
285                                 $entry = [];
286                                 if ($fields_ret['id']) {
287                                         $entry['id'] = (int)$contact['id'];
288                                 }
289                                 if ($fields_ret['displayName']) {
290                                         $entry['displayName'] = $contact['name'];
291                                 }
292                                 if ($fields_ret['aboutMe']) {
293                                         $entry['aboutMe'] = $about;
294                                 }
295                                 if ($fields_ret['currentLocation']) {
296                                         $entry['currentLocation'] = $contact['location'];
297                                 }
298                                 if ($fields_ret['gender']) {
299                                         $entry['gender'] = $contact['gender'];
300                                 }
301                                 if ($fields_ret['generation']) {
302                                         $entry['generation'] = (int)$contact['generation'];
303                                 }
304                                 if ($fields_ret['urls']) {
305                                         $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
306                                         if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
307                                                 $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
308                                         }
309                                 }
310                                 if ($fields_ret['preferredUsername']) {
311                                         $entry['preferredUsername'] = $contact['nick'];
312                                 }
313                                 if ($fields_ret['updated']) {
314                                         if (! $global) {
315                                                 $entry['updated'] = $contact['success_update'];
316
317                                                 if ($contact['name-date'] > $entry['updated']) {
318                                                         $entry['updated'] = $contact['name-date'];
319                                                 }
320                                                 if ($contact['uri-date'] > $entry['updated']) {
321                                                         $entry['updated'] = $contact['uri-date'];
322                                                 }
323                                                 if ($contact['avatar-date'] > $entry['updated']) {
324                                                         $entry['updated'] = $contact['avatar-date'];
325                                                 }
326                                         } else {
327                                                 $entry['updated'] = $contact['updated'];
328                                         }
329                                         $entry['updated'] = date("c", strtotime($entry['updated']));
330                                 }
331                                 if ($fields_ret['photos']) {
332                                         $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
333                                 }
334                                 if ($fields_ret['network']) {
335                                         $entry['network'] = $contact['network'];
336                                         if ($entry['network'] == Protocol::STATUSNET) {
337                                                 $entry['network'] = Protocol::OSTATUS;
338                                         }
339                                         if (($entry['network'] == "") && ($contact['self'])) {
340                                                 $entry['network'] = Protocol::DFRN;
341                                         }
342                                 }
343                                 if ($fields_ret['tags']) {
344                                         $tags = str_replace(",", " ", $contact['keywords']);
345                                         $tags = explode(" ", $tags);
346
347                                         $cleaned = [];
348                                         foreach ($tags as $tag) {
349                                                 $tag = trim(strtolower($tag));
350                                                 if ($tag != "") {
351                                                         $cleaned[] = $tag;
352                                                 }
353                                         }
354
355                                         $entry['tags'] = [$cleaned];
356                                 }
357                                 if ($fields_ret['address']) {
358                                         $entry['address'] = [];
359
360                                         // Deactivated. It just reveals too much data. (Although its from the default profile)
361                                         //if (isset($rr['paddress']))
362                                         //       $entry['address']['streetAddress'] = $rr['paddress'];
363
364                                         if (isset($contact['plocation'])) {
365                                                 $entry['address']['locality'] = $contact['plocation'];
366                                         }
367                                         if (isset($contact['pregion'])) {
368                                                 $entry['address']['region'] = $contact['pregion'];
369                                         }
370                                         // See above
371                                         //if (isset($rr['ppostalcode']))
372                                         //       $entry['address']['postalCode'] = $rr['ppostalcode'];
373
374                                         if (isset($contact['pcountry'])) {
375                                                 $entry['address']['country'] = $contact['pcountry'];
376                                         }
377                                 }
378
379                                 if ($fields_ret['contactType']) {
380                                         $entry['contactType'] = intval($contact['contact-type']);
381                                 }
382                                 $ret['entry'][] = $entry;
383                         }
384                 } else {
385                         $ret['entry'][] = [];
386                 }
387         } else {
388                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
389         }
390
391         Logger::log("End of poco", Logger::DEBUG);
392
393         if ($format === 'xml') {
394                 header('Content-type: text/xml');
395                 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
396                 exit();
397         }
398         if ($format === 'json') {
399                 header('Content-type: application/json');
400                 echo json_encode($ret);
401                 exit();
402         } else {
403                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
404         }
405 }