3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Util;
24 use Friendica\Core\Cache\Duration;
25 use Friendica\Core\Logger;
27 use Friendica\Core\System;
31 * This class contain methods to work with JsonLD data
36 * Loader for LD-JSON validation
40 * @return mixed the loaded data
41 * @throws \JsonLdException
43 public static function documentLoader($url)
47 $x = debug_backtrace();
50 if ($n['function'] === __FUNCTION__) {
57 Logger::error('jsonld bomb detected at: ' . $url);
61 $result = DI::cache()->get('documentLoader:' . $url);
62 if (!is_null($result)) {
66 $data = jsonld_default_document_loader($url);
67 DI::cache()->set('documentLoader:' . $url, $data, Duration::DAY);
71 public static function removeSecurityLink(array $json)
73 if (!is_array($json['@context'])) {
77 if (($key = array_search('https://w3id.org/security/v1', $json['@context'])) !== false) {
78 unset($json['@context'][$key]);
79 $json['@context'] = array_values(array_filter($json['@context']));
85 public static function fixContext(array $json)
87 // Preparation for adding possibly missing content to the context
88 if (!empty($json['@context']) && is_string($json['@context'])) {
89 $json['@context'] = [$json['@context']];
92 if (($key = array_search('https://w3id.org/security/v1', $json['@context'])) !== false) {
93 unset($json['@context'][$key]);
94 $json['@context'] = array_values(array_filter($json['@context']));
97 $last_entry = count($json['@context']) - 1;
100 'w3id' => 'https://w3id.org/security#',
101 'signature' => 'w3id:signature',
102 'RsaSignature2017' => 'w3id:RsaSignature2017',
103 'created' => 'w3id:created',
104 'creator' => 'w3id:creator',
105 'nonce' => 'w3id:nonce',
106 'signatureValue' => 'w3id:signatureValue',
107 'publicKey' => 'w3id:publicKey',
108 'publicKeyPem' => 'w3id:publicKeyPem'];
110 if (is_array($json['@context'][$last_entry])) {
111 $json['@context'][$last_entry] = array_merge($json['@context'][$last_entry], $additional);
113 $json['@context'][] = $additional;
120 * Normalises a given JSON array
124 * @return mixed|bool normalized JSON string
127 public static function normalize($json)
129 $json = self::removeSecurityLink($json);
131 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
133 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
136 $normalized = jsonld_normalize($jsonobj, array('algorithm' => 'URDNA2015', 'format' => 'application/nquads'));
138 catch (Exception $e) {
141 $currentException = $e;
143 $messages[] = $currentException->getMessage();
144 } while($currentException = $currentException->getPrevious());
146 Logger::warning('JsonLD normalize error');
147 Logger::notice('JsonLD normalize error', ['messages' => $messages]);
148 Logger::info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]);
149 Logger::debug('JsonLD normalize error', ['jsonobj' => $jsonobj]);
156 * Compacts a given JSON array
160 * @return array Compacted JSON array
163 public static function compact($json)
165 $json = self::fixContext($json);
167 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
169 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams#',
170 'w3id' => (object)['@id' => 'https://w3id.org/security#', '@type' => '@id'],
171 'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'],
172 'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
173 'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'],
174 'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'],
175 'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
176 'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'],
177 'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id'],
178 'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id'],
179 'sc' => (object)['@id' => 'http://schema.org#', '@type' => '@id'],
180 'pt' => (object)['@id' => 'https://joinpeertube.org/ns#', '@type' => '@id']];
182 // Trying to avoid memory problems with large content fields
183 if (!empty($json['object']['source']['content'])) {
184 $content = $json['object']['source']['content'];
185 $json['object']['source']['content'] = '';
188 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
191 $compacted = jsonld_compact($jsonobj, $context);
193 catch (Exception $e) {
195 Logger::error('compacting error', ['callstack' => System::callstack(20)]);
196 // Sooner or later we should log some details as well - but currently this leads to memory issues
197 // Logger::log('compacting error:' . substr(print_r($e, true), 0, 10000), Logger::DEBUG);
200 $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
202 if (isset($json['as:object']['as:source']['as:content']) && !empty($content)) {
203 $json['as:object']['as:source']['as:content'] = $content;
210 * Fetches an element array from a JSON array
216 * @return array fetched element
218 public static function fetchElementArray($array, $element, $key = null, $type = null, $type_value = null)
220 if (!isset($array[$element])) {
224 // If it isn't an array yet, make it to one
225 if (!is_int(key($array[$element]))) {
226 $array[$element] = [$array[$element]];
231 foreach ($array[$element] as $entry) {
232 if (!is_array($entry) || is_null($key)) {
234 } elseif (isset($entry[$key])) {
235 $item = $entry[$key];
238 if (isset($item) && (is_null($type) || is_null($type_value) || isset($item[$type]) && $item[$type] == $type_value)) {
247 * Fetches an element from a JSON array
255 * @return string fetched element
257 public static function fetchElement($array, $element, $key = '@id', $type = null, $type_value = null)
263 if (!isset($array[$element])) {
267 if (!is_array($array[$element])) {
268 return $array[$element];
271 if (is_null($type) || is_null($type_value)) {
272 $element_array = self::fetchElementArray($array, $element, $key);
273 if (is_null($element_array)) {
277 return array_shift($element_array);
280 $element_array = self::fetchElementArray($array, $element);
281 if (is_null($element_array)) {
285 foreach ($element_array as $entry) {
286 if (isset($entry[$key]) && isset($entry[$type]) && ($entry[$type] == $type_value)) {