]> git.mxchange.org Git - friendica.git/blob - src/Util/JsonLD.php
Merge pull request #8271 from MrPetovan/bug/8229-frio-mobile-back-to-top
[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
127                 // Preparation for adding possibly missing content to the context
128                 if (!empty($json['@context']) && is_string($json['@context'])) {
129                         $json['@context'] = [$json['@context']];
130                 }
131
132                 // Workaround for servers with missing context
133                 // See issue https://github.com/nextcloud/social/issues/330
134                 if (!empty($json['@context']) && is_array($json['@context'])) {
135                         $json['@context'][] = 'https://w3id.org/security/v1';
136                 }
137
138                 // Trying to avoid memory problems with large content fields
139                 if (!empty($json['object']['source']['content'])) {
140                         $content = $json['object']['source']['content'];
141                         $json['object']['source']['content'] = '';
142                 }
143
144                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
145
146                 try {
147                         $compacted = jsonld_compact($jsonobj, $context);
148                 }
149                 catch (Exception $e) {
150                         $compacted = false;
151                         Logger::error('compacting error');
152                         // Sooner or later we should log some details as well - but currently this leads to memory issues
153                         // Logger::log('compacting error:' . substr(print_r($e, true), 0, 10000), Logger::DEBUG);
154                 }
155
156                 $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
157
158                 if (isset($json['as:object']['as:source']['as:content']) && !empty($content)) {
159                         $json['as:object']['as:source']['as:content'] = $content;
160                 }
161
162                 return $json;
163         }
164
165         /**
166          * Fetches an element array from a JSON array
167          *
168          * @param $array
169          * @param $element
170          * @param $key
171          *
172          * @return array fetched element
173          */
174         public static function fetchElementArray($array, $element, $key = '@id')
175         {
176                 if (empty($array)) {
177                         return null;
178                 }
179
180                 if (!isset($array[$element])) {
181                         return null;
182                 }
183
184                 // If it isn't an array yet, make it to one
185                 if (!is_int(key($array[$element]))) {
186                         $array[$element] = [$array[$element]];
187                 }
188
189                 $elements = [];
190
191                 foreach ($array[$element] as $entry) {
192                         if (!is_array($entry)) {
193                                 $elements[] = $entry;
194                         } elseif (isset($entry[$key])) {
195                                 $elements[] = $entry[$key];
196                         } elseif (!empty($entry) || !is_array($entry)) {
197                                 $elements[] = $entry;
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 }