]> git.mxchange.org Git - friendica.git/blob - mod/poco.php
Merge pull request #8900 from tobiasd/20200718-serverblocklistcsv
[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\Model\GServer;
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                 if (!DBA::exists('profile', ['net-publish' => true])) {
47                         throw new \Friendica\Network\HTTPException\ForbiddenException();
48                 }
49                 $system_mode = true;
50         }
51
52         $format = ($_GET['format'] ?? '') ?: 'json';
53
54         $justme = false;
55         $global = false;
56
57         if ($a->argc > 1 && $a->argv[1] === '@server') {
58                 // List of all servers that this server knows
59                 $ret = GServer::getActive();
60                 header('Content-type: application/json');
61                 echo json_encode($ret);
62                 exit();
63         }
64
65         if ($a->argc > 1 && $a->argv[1] === '@global') {
66                 // Global is not supported anymore
67                 throw new \Friendica\Network\HTTPException\NotFoundException();
68         }
69         if ($a->argc > 2 && $a->argv[2] === '@me') {
70                 $justme = true;
71         }
72         if ($a->argc > 3 && $a->argv[3] === '@all') {
73                 $justme = false;
74         }
75         if ($a->argc > 3 && $a->argv[3] === '@self') {
76                 $justme = true;
77         }
78         if ($a->argc > 4 && intval($a->argv[4]) && $justme == false) {
79                 $cid = intval($a->argv[4]);
80         }
81
82         if (!$system_mode && !$global) {
83                 $user = DBA::selectFirst('owner-view', ['uid', 'nickname'], ['nickname' => $nickname, 'hide-friends' => false]);
84                 if (!DBA::isResult($user)) {
85                         throw new \Friendica\Network\HTTPException\NotFoundException();
86                 }
87         }
88
89         if ($justme) {
90                 $sql_extra = " AND `contact`.`self` = 1 ";
91         } else {
92                 $sql_extra = "";
93         }
94
95         if (!empty($cid)) {
96                 $sql_extra = sprintf(" AND `contact`.`id` = %d ", intval($cid));
97         }
98         if (!empty($_GET['updatedSince'])) {
99                 $update_limit = date(DateTimeFormat::MYSQL, strtotime($_GET['updatedSince']));
100         }
101         if ($system_mode) {
102                 $totalResults = DBA::count('profile', ['net-publish' => true]);
103         } else {
104                 $contacts = q("SELECT count(*) AS `total` FROM `contact` WHERE `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `unsearchable` AND NOT `archive`
105                         AND NOT `failed`
106                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra",
107                         intval($user['uid']),
108                         DBA::escape(Protocol::DFRN),
109                         DBA::escape(Protocol::DIASPORA),
110                         DBA::escape(Protocol::OSTATUS),
111                         DBA::escape(Protocol::STATUSNET)
112                 );
113         }
114         if (empty($totalResults) && DBA::isResult($contacts)) {
115                 $totalResults = intval($contacts[0]['total']);
116         } elseif (empty($totalResults)) {
117                 $totalResults = 0;
118         }
119         if (!empty($_GET['startIndex'])) {
120                 $startIndex = intval($_GET['startIndex']);
121         } else {
122                 $startIndex = 0;
123         }
124         $itemsPerPage = ((!empty($_GET['count'])) ? intval($_GET['count']) : $totalResults);
125
126         if ($system_mode) {
127                 Logger::log("Start system mode query", Logger::DEBUG);
128                 $contacts = DBA::selectToArray('owner-view', [], ['net-publish' => true], ['limit' => [$startIndex, $itemsPerPage]]);
129         } else {
130                 Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
131                 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `hidden` AND NOT `archive`
132                         AND NOT `failed` AND NOT `unsearchable`
133                         AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
134                         intval($user['uid']),
135                         DBA::escape(Protocol::DFRN),
136                         DBA::escape(Protocol::DIASPORA),
137                         DBA::escape(Protocol::OSTATUS),
138                         DBA::escape(Protocol::STATUSNET),
139                         intval($startIndex),
140                         intval($itemsPerPage)
141                 );
142         }
143         Logger::log("Query done", Logger::DEBUG);
144
145         $ret = [];
146         if (!empty($_GET['sorted'])) {
147                 $ret['sorted'] = false;
148         }
149         if (!empty($_GET['filtered'])) {
150                 $ret['filtered'] = false;
151         }
152         if (!empty($_GET['updatedSince']) && ! $global) {
153                 $ret['updatedSince'] = false;
154         }
155         $ret['startIndex']   = (int) $startIndex;
156         $ret['itemsPerPage'] = (int) $itemsPerPage;
157         $ret['totalResults'] = (int) $totalResults;
158         $ret['entry']        = [];
159
160
161         $fields_ret = [
162                 'id' => false,
163                 'displayName' => false,
164                 'urls' => false,
165                 'updated' => false,
166                 'preferredUsername' => false,
167                 'photos' => false,
168                 'aboutMe' => false,
169                 'currentLocation' => false,
170                 'network' => false,
171                 'tags' => false,
172                 'address' => false,
173                 'contactType' => false,
174                 'generation' => false
175         ];
176
177         if (empty($_GET['fields']) || ($_GET['fields'] === '@all')) {
178                 foreach ($fields_ret as $k => $v) {
179                         $fields_ret[$k] = true;
180                 }
181         } else {
182                 $fields_req = explode(',', $_GET['fields']);
183                 foreach ($fields_req as $f) {
184                         $fields_ret[trim($f)] = true;
185                 }
186         }
187
188         if (!is_array($contacts)) {
189                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
190         }
191
192         if (DBA::isResult($contacts)) {
193                 foreach ($contacts as $contact) {
194                         if (!isset($contact['updated'])) {
195                                 $contact['updated'] = '';
196                         }
197
198                         if (! isset($contact['generation'])) {
199                                 if ($global) {
200                                         $contact['generation'] = 3;
201                                 } elseif ($system_mode) {
202                                         $contact['generation'] = 1;
203                                 } else {
204                                         $contact['generation'] = 2;
205                                 }
206                         }
207
208                         if (($contact['keywords'] == "") && isset($contact['pub_keywords'])) {
209                                 $contact['keywords'] = $contact['pub_keywords'];
210                         }
211                         if (isset($contact['account-type'])) {
212                                 $contact['contact-type'] = $contact['account-type'];
213                         }
214                         $about = DI::cache()->get("about:" . $contact['updated'] . ":" . $contact['nurl']);
215                         if (is_null($about)) {
216                                 $about = BBCode::convert($contact['about'], false);
217                                 DI::cache()->set("about:" . $contact['updated'] . ":" . $contact['nurl'], $about);
218                         }
219
220                         // Non connected persons can only see the keywords of a Diaspora account
221                         if ($contact['network'] == Protocol::DIASPORA) {
222                                 $contact['location'] = "";
223                                 $about = "";
224                         }
225
226                         $entry = [];
227                         if ($fields_ret['id']) {
228                                 $entry['id'] = (int)$contact['id'];
229                         }
230                         if ($fields_ret['displayName']) {
231                                 $entry['displayName'] = $contact['name'];
232                         }
233                         if ($fields_ret['aboutMe']) {
234                                 $entry['aboutMe'] = $about;
235                         }
236                         if ($fields_ret['currentLocation']) {
237                                 $entry['currentLocation'] = $contact['location'];
238                         }
239                         if ($fields_ret['generation']) {
240                                 $entry['generation'] = (int)$contact['generation'];
241                         }
242                         if ($fields_ret['urls']) {
243                                 $entry['urls'] = [['value' => $contact['url'], 'type' => 'profile']];
244                                 if ($contact['addr'] && ($contact['network'] !== Protocol::MAIL)) {
245                                         $entry['urls'][] = ['value' => 'acct:' . $contact['addr'], 'type' => 'webfinger'];
246                                 }
247                         }
248                         if ($fields_ret['preferredUsername']) {
249                                 $entry['preferredUsername'] = $contact['nick'];
250                         }
251                         if ($fields_ret['updated']) {
252                                 if (! $global) {
253                                         $entry['updated'] = $contact['success_update'];
254
255                                         if ($contact['name-date'] > $entry['updated']) {
256                                                 $entry['updated'] = $contact['name-date'];
257                                         }
258                                         if ($contact['uri-date'] > $entry['updated']) {
259                                                 $entry['updated'] = $contact['uri-date'];
260                                         }
261                                         if ($contact['avatar-date'] > $entry['updated']) {
262                                                 $entry['updated'] = $contact['avatar-date'];
263                                         }
264                                 } else {
265                                         $entry['updated'] = $contact['updated'];
266                                 }
267                                 $entry['updated'] = date("c", strtotime($entry['updated']));
268                         }
269                         if ($fields_ret['photos']) {
270                                 $entry['photos'] = [['value' => $contact['photo'], 'type' => 'profile']];
271                         }
272                         if ($fields_ret['network']) {
273                                 $entry['network'] = $contact['network'];
274                                 if ($entry['network'] == Protocol::STATUSNET) {
275                                         $entry['network'] = Protocol::OSTATUS;
276                                 }
277                                 if (($entry['network'] == "") && ($contact['self'])) {
278                                         $entry['network'] = Protocol::DFRN;
279                                 }
280                         }
281                         if ($fields_ret['tags']) {
282                                 $tags = str_replace(",", " ", $contact['keywords']);
283                                 $tags = explode(" ", $tags);
284
285                                 $cleaned = [];
286                                 foreach ($tags as $tag) {
287                                         $tag = trim(strtolower($tag));
288                                         if ($tag != "") {
289                                                 $cleaned[] = $tag;
290                                         }
291                                 }
292
293                                 $entry['tags'] = [$cleaned];
294                         }
295                         if ($fields_ret['address']) {
296                                 $entry['address'] = [];
297
298                                 // Deactivated. It just reveals too much data. (Although its from the default profile)
299                                 //if (isset($rr['address']))
300                                 //       $entry['address']['streetAddress'] = $rr['address'];
301
302                                 if (isset($contact['locality'])) {
303                                         $entry['address']['locality'] = $contact['locality'];
304                                 }
305                                 if (isset($contact['region'])) {
306                                         $entry['address']['region'] = $contact['region'];
307                                 }
308                                 // See above
309                                 //if (isset($rr['postal-code']))
310                                 //       $entry['address']['postalCode'] = $rr['postal-code'];
311
312                                 if (isset($contact['country'])) {
313                                         $entry['address']['country'] = $contact['country'];
314                                 }
315                         }
316
317                         if ($fields_ret['contactType']) {
318                                 $entry['contactType'] = intval($contact['contact-type']);
319                         }
320                         $ret['entry'][] = $entry;
321                 }
322         } else {
323                 $ret['entry'][] = [];
324         }
325
326         Logger::log("End of poco", Logger::DEBUG);
327
328         if ($format === 'xml') {
329                 header('Content-type: text/xml');
330                 echo Renderer::replaceMacros(Renderer::getMarkupTemplate('poco_xml.tpl'), XML::arrayEscape(['$response' => $ret]));
331                 exit();
332         }
333         if ($format === 'json') {
334                 header('Content-type: application/json');
335                 echo json_encode($ret);
336                 exit();
337         } else {
338                 throw new \Friendica\Network\HTTPException\InternalServerErrorException();
339         }
340 }