]> git.mxchange.org Git - friendica.git/blob - src/Util/JsonLD.php
bump version 2023.12
[friendica.git] / src / Util / JsonLD.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
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  */
21
22 namespace Friendica\Util;
23
24 use Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Logger;
26 use Exception;
27 use Friendica\Core\System;
28 use Friendica\DI;
29
30 /**
31  * This class contain methods to work with JsonLD data
32  */
33 class JsonLD
34 {
35         /**
36          * Loader for LD-JSON validation
37          *
38          * @param $url
39          *
40          * @return mixed the loaded data
41          * @throws \JsonLdException
42          */
43         public static function documentLoader($url)
44         {
45                 switch ($url) {
46                         case 'https://w3id.org/security/v1':
47                                 $url = DI::basePath() . '/static/security-v1.jsonld';
48                                 break;
49                         case 'https://w3id.org/security/data-integrity/v1':
50                                 $url = DI::basePath() . '/static/security-data-integrity-v1.jsonld';
51                                 break;
52                         case 'https://w3id.org/security/multikey/v1':
53                                 $url = DI::basePath() . '/static/security-multikey-v1.jsonld';
54                                 break;
55                         case 'https://w3id.org/identity/v1':
56                                 $url = DI::basePath() . '/static/identity-v1.jsonld';
57                                 break;
58                         case 'https://www.w3.org/ns/activitystreams':
59                                 $url = DI::basePath() . '/static/activitystreams.jsonld';
60                                 break;
61                         case 'https://funkwhale.audio/ns':
62                                 $url = DI::basePath() . '/static/funkwhale.audio.jsonld';
63                                 break;
64                         case 'http://schema.org':
65                                 $url = DI::basePath() . '/static/schema.jsonld';
66                                 break;
67                         case 'http://joinmastodon.org/ns':
68                                 $url = DI::basePath() . '/static/joinmastodon.jsonld';
69                                 break;
70                         default:
71                                 switch (parse_url($url, PHP_URL_PATH)) {
72                                         case '/schemas/litepub-0.1.jsonld';
73                                                 $url = DI::basePath() . '/static/litepub-0.1.jsonld';
74                                                 break;
75                                         case '/apschema/v1.2':
76                                         case '/apschema/v1.9':
77                                         case '/apschema/v1.10':
78                                                 $url = DI::basePath() . '/static/apschema.jsonld';
79                                                 break;
80                                         default:
81                                                 Logger::info('Got url', ['url' =>$url]);
82                                                 break;
83                                 }
84                 }
85
86                 $recursion = 0;
87
88                 $x = debug_backtrace();
89                 if ($x) {
90                         foreach ($x as $n) {
91                                 if ($n['function'] === __FUNCTION__)  {
92                                         $recursion ++;
93                                 }
94                         }
95                 }
96
97                 if ($recursion > 5) {
98                         Logger::error('jsonld bomb detected at: ' . $url);
99                         System::exit();
100                 }
101
102                 $result = DI::cache()->get('documentLoader:' . $url);
103                 if (!is_null($result)) {
104                         return $result;
105                 }
106
107                 $data = jsonld_default_document_loader($url);
108                 DI::cache()->set('documentLoader:' . $url, $data, Duration::DAY);
109                 return $data;
110         }
111
112         /**
113          * Normalises a given JSON array
114          *
115          * @param array $json
116          *
117          * @return mixed|bool normalized JSON string
118          * @throws Exception
119          */
120         public static function normalize($json)
121         {
122                 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
123
124                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
125
126                 try {
127                         $normalized = jsonld_normalize($jsonobj, array('algorithm' => 'URDNA2015', 'format' => 'application/nquads'));
128                 }
129                 catch (Exception $e) {
130                         $normalized = false;
131                         $messages = [];
132                         $currentException = $e;
133                         do {
134                                 $messages[] = $currentException->getMessage();
135                         } while($currentException = $currentException->getPrevious());
136
137                         Logger::warning('JsonLD normalize error');
138                         Logger::notice('JsonLD normalize error', ['messages' => $messages]);
139                         Logger::info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]);
140                         Logger::debug('JsonLD normalize error', ['jsonobj' => $jsonobj]);
141                 }
142
143                 return $normalized;
144         }
145
146         /**
147          * Compacts a given JSON array
148          *
149          * @param array $json
150          * @param bool  $logfailed
151          *
152          * @return array Compacted JSON array
153          * @throws Exception
154          */
155         public static function compact($json, bool $logfailed = true): array
156         {
157                 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
158
159                 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams#',
160                         'w3id' => 'https://w3id.org/security#',
161                         'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'],
162                         'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
163                         'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'],
164                         'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'],
165                         'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
166                         'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'],
167                         'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id'],
168                         'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id'],
169                         'sc' => (object)['@id' => 'http://schema.org#', '@type' => '@id'],
170                         'pt' => (object)['@id' => 'https://joinpeertube.org/ns#', '@type' => '@id'],
171                         'mobilizon' => (object)['@id' => 'https://joinmobilizon.org/ns#', '@type' => '@id'],
172                         'fedibird' => (object)['@id' => 'http://fedibird.com/ns#', '@type' => '@id'],
173                         'misskey' => (object)['@id' => 'https://misskey-hub.net/ns#', '@type' => '@id'],
174                         'pixelfed' => (object)['@id' => 'http://pixelfed.org/ns#', '@type' => '@id'],
175                 ];
176
177                 $orig_json = $json;
178
179                 // Preparation for adding possibly missing content to the context
180                 if (!empty($json['@context']) && is_string($json['@context'])) {
181                         $json['@context'] = [$json['@context']];
182                 }
183
184                 if (!empty($json['@context']) && is_array($json['@context'])) {
185                         // Remove empty entries from the context (a problem with WriteFreely)
186                         $json['@context'] = array_filter($json['@context']);
187
188                         // Workaround for servers with missing context
189                         // See issue https://github.com/nextcloud/social/issues/330
190                         if (!in_array('https://w3id.org/security/v1', $json['@context'])) {
191                                 $json['@context'][] = 'https://w3id.org/security/v1';
192                         }
193                 }
194
195                 // Bookwyrm transmits "id" fields with "null", which isn't allowed.
196                 array_walk_recursive($json, function (&$value, $key) {
197                         if ($key == 'id' && is_null($value)) {
198                                 $value = '';
199                         }
200                 });
201
202                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
203
204                 try {
205                         $compacted = jsonld_compact($jsonobj, $context);
206                 }
207                 catch (Exception $e) {
208                         $compacted = false;
209                         Logger::notice('compacting error', ['msg' => $e->getMessage(), 'previous' => $e->getPrevious(), 'line' => $e->getLine()]);
210                         if ($logfailed && DI::config()->get('debug', 'ap_log_failure')) {
211                                 $tempfile = tempnam(System::getTempPath(), 'failed-jsonld');
212                                 file_put_contents($tempfile, json_encode(['json' => $orig_json, 'msg' => $e->getMessage(), 'previous' => $e->getPrevious()], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
213                                 Logger::notice('Failed message stored', ['file' => $tempfile]);
214                         }
215                 }
216
217                 $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
218
219                 if ($json === false) {
220                         Logger::notice('JSON encode->decode failed', ['orig_json' => $orig_json, 'compacted' => $compacted]);
221                         $json = [];
222                 }
223
224                 return $json;
225         }
226
227         /**
228          * Fetches an element array from a JSON array
229          *
230          * @param $array
231          * @param $element
232          * @param $key
233          *
234          * @return array fetched element
235          */
236         public static function fetchElementArray($array, $element, $key = null, $type = null, $type_value = null)
237         {
238                 if (!isset($array[$element])) {
239                         return null;
240                 }
241
242                 // If it isn't an array yet, make it to one
243                 if (!is_array($array[$element]) || !is_int(key($array[$element]))) {
244                         $array[$element] = [$array[$element]];
245                 }
246
247                 $elements = [];
248
249                 foreach ($array[$element] as $entry) {
250                         if (!is_array($entry) || is_null($key)) {
251                                 $item = $entry;
252                         } elseif (isset($entry[$key])) {
253                                 $item = $entry[$key];
254                         }
255
256                         if (isset($item) && (is_null($type) || is_null($type_value) || isset($item[$type]) && $item[$type] == $type_value)) {
257                                 $elements[] = $item;
258                         }
259                 }
260
261                 return $elements;
262         }
263
264         /**
265          * Fetches an element from a JSON array
266          *
267          * @param $array
268          * @param $element
269          * @param $key
270          * @param $type
271          * @param $type_value
272          *
273          * @return string fetched element
274          */
275         public static function fetchElement($array, $element, $key = '@id', $type = null, $type_value = null)
276         {
277                 if (empty($array)) {
278                         return null;
279                 }
280
281                 if (!isset($array[$element])) {
282                         return null;
283                 }
284
285                 if (!is_array($array[$element])) {
286                         return $array[$element];
287                 }
288
289                 if (is_null($type) || is_null($type_value)) {
290                         $element_array = self::fetchElementArray($array, $element, $key);
291                         if (is_null($element_array)) {
292                                 return null;
293                         }
294
295                         return array_shift($element_array);
296                 }
297
298                 $element_array = self::fetchElementArray($array, $element);
299                 if (is_null($element_array)) {
300                         return null;
301                 }
302
303                 foreach ($element_array as $entry) {
304                         if (isset($entry[$key]) && isset($entry[$type]) && ($entry[$type] == $type_value)) {
305                                 return $entry[$key];
306                         }
307                 }
308
309                 return null;
310         }
311 }