]> git.mxchange.org Git - friendica.git/blob - src/Util/JsonLD.php
Merge pull request #11490 from annando/issue-11487
[friendica.git] / src / Util / JsonLD.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\DI;
28
29 /**
30  * This class contain methods to work with JsonLD data
31  */
32 class JsonLD
33 {
34         /**
35          * Loader for LD-JSON validation
36          *
37          * @param $url
38          *
39          * @return mixed the loaded data
40          * @throws \JsonLdException
41          */
42         public static function documentLoader($url)
43         {
44                 switch ($url) {
45                         case 'https://w3id.org/security/v1':
46                                 $url = DI::baseUrl() . '/static/security-v1.jsonld';
47                                 break;
48                         case 'https://w3id.org/identity/v1':
49                                 $url = DI::baseUrl() . '/static/identity-v1.jsonld';
50                                 break;
51                         case 'https://www.w3.org/ns/activitystreams':
52                                 $url = DI::baseUrl() . '/static/activitystreams.jsonld';
53                                 break;
54                         default:
55                                 Logger::info('Got url', ['url' =>$url]);
56                                 break;
57                 }
58
59                 $recursion = 0;
60
61                 $x = debug_backtrace();
62                 if ($x) {
63                         foreach ($x as $n) {
64                                 if ($n['function'] === __FUNCTION__)  {
65                                         $recursion ++;
66                                 }
67                         }
68                 }
69
70                 if ($recursion > 5) {
71                         Logger::error('jsonld bomb detected at: ' . $url);
72                         exit();
73                 }
74
75                 $result = DI::cache()->get('documentLoader:' . $url);
76                 if (!is_null($result)) {
77                         return $result;
78                 }
79
80                 $data = jsonld_default_document_loader($url);
81                 DI::cache()->set('documentLoader:' . $url, $data, Duration::DAY);
82                 return $data;
83         }
84
85         /**
86          * Normalises a given JSON array
87          *
88          * @param array $json
89          *
90          * @return mixed|bool normalized JSON string
91          * @throws Exception
92          */
93         public static function normalize($json)
94         {
95                 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
96
97                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
98
99                 try {
100                         $normalized = jsonld_normalize($jsonobj, array('algorithm' => 'URDNA2015', 'format' => 'application/nquads'));
101                 }
102                 catch (Exception $e) {
103                         $normalized = false;
104                         $messages = [];
105                         $currentException = $e;
106                         do {
107                                 $messages[] = $currentException->getMessage();
108                         } while($currentException = $currentException->getPrevious());
109
110                         Logger::warning('JsonLD normalize error');
111                         Logger::notice('JsonLD normalize error', ['messages' => $messages]);
112                         Logger::info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]);
113                         Logger::debug('JsonLD normalize error', ['jsonobj' => $jsonobj]);
114                 }
115
116                 return $normalized;
117         }
118
119         /**
120          * Compacts a given JSON array
121          *
122          * @param array $json
123          *
124          * @return array Compacted JSON array
125          * @throws Exception
126          */
127         public static function compact($json)
128         {
129                 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
130
131                 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams#',
132                         'w3id' => 'https://w3id.org/security#',
133                         'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'],
134                         'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
135                         'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'],
136                         'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'],
137                         'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
138                         'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'],
139                         'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id'],
140                         'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id'],
141                         'sc' => (object)['@id' => 'http://schema.org#', '@type' => '@id'],
142                         'pt' => (object)['@id' => 'https://joinpeertube.org/ns#', '@type' => '@id'],
143                         'mobilizon' => (object)['@id' => 'https://joinmobilizon.org/ns#', '@type' => '@id'],
144                 ];
145
146                 // Preparation for adding possibly missing content to the context
147                 if (!empty($json['@context']) && is_string($json['@context'])) {
148                         $json['@context'] = [$json['@context']];
149                 }
150
151                 // Workaround for servers with missing context
152                 // See issue https://github.com/nextcloud/social/issues/330
153                 if (!empty($json['@context']) && is_array($json['@context'])) {
154                         $json['@context'][] = 'https://w3id.org/security/v1';
155                 }
156
157                 // Trying to avoid memory problems with large content fields
158                 if (!empty($json['object']['source']['content'])) {
159                         $content = $json['object']['source']['content'];
160                         $json['object']['source']['content'] = '';
161                 }
162
163                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
164
165                 try {
166                         $compacted = jsonld_compact($jsonobj, $context);
167                 }
168                 catch (Exception $e) {
169                         $compacted = false;
170                         Logger::notice('compacting error', ['line' => $e->getLine(), 'exception' => $e]);
171                 }
172
173                 $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
174
175                 if (isset($json['as:object']['as:source']['as:content']) && !empty($content)) {
176                         $json['as:object']['as:source']['as:content'] = $content;
177                 }
178
179                 return $json;
180         }
181
182         /**
183          * Fetches an element array from a JSON array
184          *
185          * @param $array
186          * @param $element
187          * @param $key
188          *
189          * @return array fetched element
190          */
191         public static function fetchElementArray($array, $element, $key = null, $type = null, $type_value = null)
192         {
193                 if (!isset($array[$element])) {
194                         return null;
195                 }
196
197                 // If it isn't an array yet, make it to one
198                 if (!is_array($array[$element]) || !is_int(key($array[$element]))) {
199                         $array[$element] = [$array[$element]];
200                 }
201
202                 $elements = [];
203
204                 foreach ($array[$element] as $entry) {
205                         if (!is_array($entry) || is_null($key)) {
206                                 $item = $entry;
207                         } elseif (isset($entry[$key])) {
208                                 $item = $entry[$key];
209                         }
210
211                         if (isset($item) && (is_null($type) || is_null($type_value) || isset($item[$type]) && $item[$type] == $type_value)) {
212                                 $elements[] = $item;
213                         }
214                 }
215
216                 return $elements;
217         }
218
219         /**
220          * Fetches an element from a JSON array
221          *
222          * @param $array
223          * @param $element
224          * @param $key
225          * @param $type
226          * @param $type_value
227          *
228          * @return string fetched element
229          */
230         public static function fetchElement($array, $element, $key = '@id', $type = null, $type_value = null)
231         {
232                 if (empty($array)) {
233                         return null;
234                 }
235
236                 if (!isset($array[$element])) {
237                         return null;
238                 }
239
240                 if (!is_array($array[$element])) {
241                         return $array[$element];
242                 }
243
244                 if (is_null($type) || is_null($type_value)) {
245                         $element_array = self::fetchElementArray($array, $element, $key);
246                         if (is_null($element_array)) {
247                                 return null;
248                         }
249
250                         return array_shift($element_array);
251                 }
252
253                 $element_array = self::fetchElementArray($array, $element);
254                 if (is_null($element_array)) {
255                         return null;
256                 }
257
258                 foreach ($element_array as $entry) {
259                         if (isset($entry[$key]) && isset($entry[$type]) && ($entry[$type] == $type_value)) {
260                                 return $entry[$key];
261                         }
262                 }
263
264                 return null;
265         }
266 }