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;
29 use Friendica\Protocol\ActivityPub;
32 * This class contain methods to work with JsonLD data
37 * Loader for LD-JSON validation
41 * @return mixed the loaded data
42 * @throws \JsonLdException
44 public static function documentLoader($url)
48 $x = debug_backtrace();
51 if ($n['function'] === __FUNCTION__) {
58 Logger::error('jsonld bomb detected at: ' . $url);
62 $result = DI::cache()->get('documentLoader:' . $url);
63 if (!is_null($result)) {
67 $data = jsonld_default_document_loader($url);
68 DI::cache()->set('documentLoader:' . $url, $data, Duration::DAY);
72 private static function replaceSecurityLink(array $json)
74 if (!is_array($json['@context'])) {
78 if (($key = array_search('https://w3id.org/security/v1', $json['@context'])) !== false) {
79 $json['@context'][$key] = DI::baseUrl() . '/static/w3id-security-v1.json';
86 * Normalises a given JSON array
90 * @return mixed|bool normalized JSON string
93 public static function normalize($json)
95 $json = self::replaceSecurityLink($json);
97 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
99 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
102 $normalized = jsonld_normalize($jsonobj, array('algorithm' => 'URDNA2015', 'format' => 'application/nquads'));
104 catch (Exception $e) {
107 $currentException = $e;
109 $messages[] = $currentException->getMessage();
110 } while($currentException = $currentException->getPrevious());
112 Logger::warning('JsonLD normalize error');
113 Logger::notice('JsonLD normalize error', ['messages' => $messages]);
114 Logger::info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]);
115 Logger::debug('JsonLD normalize error', ['jsonobj' => $jsonobj]);
122 * Compacts a given JSON array
126 * @return array Compacted JSON array
129 public static function compact($json)
131 $compacted = self::internalCompact($json, false);
132 if (empty($compacted)) {
133 $json['@context'] = ActivityPub::CONTEXT;
134 $compacted = self::internalCompact($json, true);
140 private static function internalCompact($json, bool $error_log)
142 $json = self::replaceSecurityLink($json);
144 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
146 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams#',
147 'w3id' => 'https://w3id.org/security#',
148 'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'],
149 'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
150 'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'],
151 'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'],
152 'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
153 'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'],
154 'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id'],
155 'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id'],
156 'sc' => (object)['@id' => 'http://schema.org#', '@type' => '@id'],
157 'pt' => (object)['@id' => 'https://joinpeertube.org/ns#', '@type' => '@id']];
159 // Preparation for adding possibly missing content to the context
160 if (!empty($json['@context']) && is_string($json['@context'])) {
161 $json['@context'] = [$json['@context']];
164 // Workaround for servers with missing context
165 // See issue https://github.com/nextcloud/social/issues/330
166 if (!empty($json['@context']) && is_array($json['@context'])) {
167 $json['@context'][] = DI::baseUrl() . '/static/w3id-security-v1.json';
170 // Trying to avoid memory problems with large content fields
171 if (!empty($json['object']['source']['content'])) {
172 $content = $json['object']['source']['content'];
173 $json['object']['source']['content'] = '';
176 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
179 $compacted = jsonld_compact($jsonobj, $context);
181 catch (Exception $e) {
184 Logger::error('compacting error', ['line' => $e->getLine(), 'message' => $e->getMessage(),'callstack' => System::callstack(20)]);
188 $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
190 if (isset($json['as:object']['as:source']['as:content']) && !empty($content)) {
191 $json['as:object']['as:source']['as:content'] = $content;
198 * Fetches an element array from a JSON array
204 * @return array fetched element
206 public static function fetchElementArray($array, $element, $key = null, $type = null, $type_value = null)
208 if (!isset($array[$element])) {
212 // If it isn't an array yet, make it to one
213 if (!is_int(key($array[$element]))) {
214 $array[$element] = [$array[$element]];
219 foreach ($array[$element] as $entry) {
220 if (!is_array($entry) || is_null($key)) {
222 } elseif (isset($entry[$key])) {
223 $item = $entry[$key];
226 if (isset($item) && (is_null($type) || is_null($type_value) || isset($item[$type]) && $item[$type] == $type_value)) {
235 * Fetches an element from a JSON array
243 * @return string fetched element
245 public static function fetchElement($array, $element, $key = '@id', $type = null, $type_value = null)
251 if (!isset($array[$element])) {
255 if (!is_array($array[$element])) {
256 return $array[$element];
259 if (is_null($type) || is_null($type_value)) {
260 $element_array = self::fetchElementArray($array, $element, $key);
261 if (is_null($element_array)) {
265 return array_shift($element_array);
268 $element_array = self::fetchElementArray($array, $element);
269 if (is_null($element_array)) {
273 foreach ($element_array as $entry) {
274 if (isset($entry[$key]) && isset($entry[$type]) && ($entry[$type] == $type_value)) {