]> git.mxchange.org Git - friendica.git/blob - src/Util/JsonLD.php
9566c424adf77937cd9658bd5407c5b9e7068eba
[friendica.git] / src / Util / JsonLD.php
1 <?php
2 /**
3  * @file src/Util/JsonLD.php
4  */
5 namespace Friendica\Util;
6
7 use Friendica\Core\Cache;
8 use Friendica\Core\Logger;
9 use Exception;
10
11 /**
12  * @brief This class contain methods to work with JsonLD data
13  */
14 class JsonLD
15 {
16         /**
17          * @brief Loader for LD-JSON validation
18          *
19          * @param $url
20          *
21          * @return mixed the loaded data
22          * @throws \JsonLdException
23          */
24         public static function documentLoader($url)
25         {
26                 $recursion = 0;
27
28                 $x = debug_backtrace();
29                 if ($x) {
30                         foreach ($x as $n) {
31                                 if ($n['function'] === __FUNCTION__)  {
32                                         $recursion ++;
33                                 }
34                         }
35                 }
36
37                 if ($recursion > 5) {
38                         Logger::error('jsonld bomb detected at: ' . $url);
39                         exit();
40                 }
41
42                 $result = Cache::get('documentLoader:' . $url);
43                 if (!is_null($result)) {
44                         return $result;
45                 }
46
47                 $data = jsonld_default_document_loader($url);
48                 Cache::set('documentLoader:' . $url, $data, Cache::DAY);
49                 return $data;
50         }
51
52         /**
53          * @brief Normalises a given JSON array
54          *
55          * @param array $json
56          *
57          * @return mixed|bool normalized JSON string
58          * @throws Exception
59          */
60         public static function normalize($json)
61         {
62                 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
63
64                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
65
66                 try {
67                         $normalized = jsonld_normalize($jsonobj, array('algorithm' => 'URDNA2015', 'format' => 'application/nquads'));
68                 }
69                 catch (Exception $e) {
70                         $normalized = false;
71                         Logger::error('normalise error');
72                         // Sooner or later we should log some details as well - but currently this leads to memory issues
73                         // Logger::log('normalise error:' . substr(print_r($e, true), 0, 10000), Logger::DEBUG);
74                 }
75
76                 return $normalized;
77         }
78
79         /**
80          * @brief Compacts a given JSON array
81          *
82          * @param array $json
83          *
84          * @return array Compacted JSON array
85          * @throws Exception
86          */
87         public static function compact($json)
88         {
89                 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
90
91                 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams#',
92                         'w3id' => 'https://w3id.org/security#',
93                         'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'],
94                         'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
95                         'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'],
96                         'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'],
97                         'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
98                         'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'],
99                         'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id']];
100
101                 // Preparation for adding possibly missing content to the context
102                 if (!empty($json['@context']) && is_string($json['@context'])) {
103                         $json['@context'] = [$json['@context']];
104                 }
105
106                 // Workaround for servers with missing context
107                 // See issue https://github.com/nextcloud/social/issues/330
108                 if (!empty($json['@context']) && is_array($json['@context'])) {
109                         $json['@context'][] = 'https://w3id.org/security/v1';
110                 }
111
112                 // Trying to avoid memory problems with large content fields
113                 if (!empty($json['object']['source']['content'])) {
114                         $content = $json['object']['source']['content'];
115                         $json['object']['source']['content'] = '';
116                 }
117
118                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
119
120                 try {
121                         $compacted = jsonld_compact($jsonobj, $context);
122                 }
123                 catch (Exception $e) {
124                         $compacted = false;
125                         Logger::error('compacting error');
126                         // Sooner or later we should log some details as well - but currently this leads to memory issues
127                         // Logger::log('compacting error:' . substr(print_r($e, true), 0, 10000), Logger::DEBUG);
128                 }
129
130                 $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
131
132                 if (isset($json['as:object']['as:source']['as:content']) && !empty($content)) {
133                         $json['as:object']['as:source']['as:content'] = $content;
134                 }
135
136                 return $json;
137         }
138
139         /**
140          * @brief Fetches an element array from a JSON array
141          *
142          * @param $array
143          * @param $element
144          * @param $key
145          *
146          * @return array fetched element
147          */
148         public static function fetchElementArray($array, $element, $key = '@id')
149         {
150                 if (empty($array)) {
151                         return null;
152                 }
153
154                 if (!isset($array[$element])) {
155                         return null;
156                 }
157
158                 // If it isn't an array yet, make it to one
159                 if (!is_int(key($array[$element]))) {
160                         $array[$element] = [$array[$element]];
161                 }
162
163                 $elements = [];
164
165                 foreach ($array[$element] as $entry) {
166                         if (!is_array($entry)) {
167                                 $elements[] = $entry;
168                         } elseif (isset($entry[$key])) {
169                                 $elements[] = $entry[$key];
170                         } elseif (!empty($entry) || !is_array($entry)) {
171                                 $elements[] = $entry;
172                         }
173                 }
174
175                 return $elements;
176         }
177
178         /**
179          * @brief Fetches an element from a JSON array
180          *
181          * @param $array
182          * @param $element
183          * @param $key
184          * @param $type
185          * @param $type_value
186          *
187          * @return string fetched element
188          */
189         public static function fetchElement($array, $element, $key = '@id', $type = null, $type_value = null)
190         {
191                 if (empty($array)) {
192                         return null;
193                 }
194
195                 if (!isset($array[$element])) {
196                         return null;
197                 }
198
199                 if (!is_array($array[$element])) {
200                         return $array[$element];
201                 }
202
203                 if (is_null($type) || is_null($type_value)) {
204                         $element_array = self::fetchElementArray($array, $element, $key);
205                         if (is_null($element_array)) {
206                                 return null;
207                         }
208
209                         return array_shift($element_array);
210                 }
211
212                 $element_array = self::fetchElementArray($array, $element);
213                 if (is_null($element_array)) {
214                         return null;
215                 }
216
217                 foreach ($element_array as $entry) {
218                         if (isset($entry[$key]) && isset($entry[$type]) && ($entry[$type] == $type_value)) {
219                                 return $entry[$key];
220                         }
221                 }
222
223                 return null;
224         }
225 }