3 * @file src/Util/JsonLD.php
5 namespace Friendica\Util;
7 use Friendica\Core\Cache;
8 use digitalbazaar\jsonld as DBJsonLD;
12 * @brief This class contain methods to work with JsonLD data
17 * @brief Loader for LD-JSON validation
21 * @return the loaded data
23 public static function documentLoader($url)
27 $x = debug_backtrace();
30 if ($n['function'] === __FUNCTION__) {
37 logger('jsonld bomb detected at: ' . $url);
41 $result = Cache::get('documentLoader:' . $url);
42 if (!is_null($result)) {
46 $data = jsonld_default_document_loader($url);
47 Cache::set('documentLoader:' . $url, $data, CACHE_DAY);
52 * @brief Normalises a given JSON array
56 * @return normalized JSON string
58 public static function normalize($json)
60 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
62 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
65 $normalized = jsonld_normalize($jsonobj, array('algorithm' => 'URDNA2015', 'format' => 'application/nquads'));
67 catch (Exception $e) {
68 logger('normalise error:' . print_r($e, true), LOGGER_DEBUG);
75 * @brief Compacts a given JSON array
79 * @return comacted JSON array
81 public static function compact($json)
83 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
85 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams',
86 'w3sec' => 'https://w3id.org/security',
87 'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
88 'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
89 'uuid' => (object)['@id' => 'http://schema.org/identifier', '@type' => '@id']];
91 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
93 $compacted = jsonld_compact($jsonobj, $context);
95 return json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
99 * @brief Fetches an element from a JSON array
107 * @return fetched element
109 public static function fetchElement($array, $element, $key, $type = null, $type_value = null)
115 if (empty($array[$element])) {
119 if (is_string($array[$element])) {
120 return $array[$element];
123 if (is_null($type_value)) {
124 if (!empty($array[$element][$key])) {
125 return $array[$element][$key];
128 if (!empty($array[$element][0][$key])) {
129 return $array[$element][0][$key];
135 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
136 return $array[$element][$key];
139 /// @todo Add array search