Avoid memory issue in exception
[friendica.git/.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::log('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::log('normalise error:' . substr(print_r($e, true), 0, 10000), Logger::DEBUG);
72                 }
73
74                 return $normalized;
75         }
76
77         /**
78          * @brief Compacts a given JSON array
79          *
80          * @param array $json
81          *
82          * @return array Compacted JSON array
83          * @throws Exception
84          */
85         public static function compact($json)
86         {
87                 jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader');
88
89                 $context = (object)['as' => 'https://www.w3.org/ns/activitystreams#',
90                         'w3id' => 'https://w3id.org/security#',
91                         'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'],
92                         'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'],
93                         'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'],
94                         'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'],
95                         'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'],
96                         'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'],
97                         'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id']];
98
99                 // Workaround for Nextcloud Social
100                 // See issue https://github.com/nextcloud/social/issues/330
101                 if (!empty($json['@context']) && is_array($json['@context'])) {
102                         $json['@context'][] = 'https://w3id.org/security/v1';
103                 }
104
105                 // Trying to avoid memory problems with large content fields
106                 if (!empty($json['object']['source']['content'])) {
107                         $content = $json['object']['source']['content'];
108                         $json['object']['source']['content'] = '';
109                 }
110
111                 $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
112
113                 try {
114                         $compacted = jsonld_compact($jsonobj, $context);
115                 }
116                 catch (Exception $e) {
117                         $compacted = false;
118                         Logger::log('compacting error:' . substr(print_r($e, true), 0, 10000), Logger::DEBUG);
119                 }
120
121                 $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
122
123                 if (isset($json['as:object']['as:source']['as:content']) && !empty($content)) {
124                         $json['as:object']['as:source']['as:content'] = $content;
125                 }
126
127                 return $json;
128         }
129
130         /**
131          * @brief Fetches an element array from a JSON array
132          *
133          * @param $array
134          * @param $element
135          * @param $key
136          *
137          * @return array fetched element
138          */
139         public static function fetchElementArray($array, $element, $key = '@id')
140         {
141                 if (empty($array)) {
142                         return null;
143                 }
144
145                 if (!isset($array[$element])) {
146                         return null;
147                 }
148
149                 // If it isn't an array yet, make it to one
150                 if (!is_int(key($array[$element]))) {
151                         $array[$element] = [$array[$element]];
152                 }
153
154                 $elements = [];
155
156                 foreach ($array[$element] as $entry) {
157                         if (!is_array($entry)) {
158                                 $elements[] = $entry;
159                         } elseif (!empty($entry[$key])) {
160                                 $elements[] = $entry[$key];
161                         } elseif (!empty($entry) || !is_array($entry)) {
162                                 $elements[] = $entry;
163                         }
164                 }
165
166                 return $elements;
167         }
168
169         /**
170          * @brief Fetches an element from a JSON array
171          *
172          * @param $array
173          * @param $element
174          * @param $key
175          * @param $type
176          * @param $type_value
177          *
178          * @return string fetched element
179          */
180         public static function fetchElement($array, $element, $key = '@id', $type = null, $type_value = null)
181         {
182                 if (empty($array)) {
183                         return null;
184                 }
185
186                 if (!isset($array[$element])) {
187                         return null;
188                 }
189
190                 if (!is_array($array[$element])) {
191                         return $array[$element];
192                 }
193
194                 if (is_null($type) || is_null($type_value)) {
195                         $element_array = self::fetchElementArray($array, $element, $key);
196                         if (is_null($element_array)) {
197                                 return null;
198                         }
199
200                         return array_shift($element_array);
201                 }
202
203                 $element_array = self::fetchElementArray($array, $element);
204                 if (is_null($element_array)) {
205                         return null;
206                 }
207
208                 foreach ($element_array as $entry) {
209                         if (isset($entry[$key]) && isset($entry[$type]) && ($entry[$type] == $type_value)) {
210                                 return $entry[$key];
211                         }
212                 }
213
214                 return null;
215         }
216 }