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