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