]> git.mxchange.org Git - friendica.git/blob - src/Protocol/OStatus.php
Merge remote-tracking branch 'upstream/develop' into server-detection
[friendica.git] / src / Protocol / OStatus.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use DOMDocument;
25 use DOMElement;
26 use DOMXPath;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Enum\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Post;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
43 use Friendica\Network\Probe;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Images;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
48 use Friendica\Util\XML;
49
50 /**
51  * This class contain functions for the OStatus protocol
52  */
53 class OStatus
54 {
55         private static $itemlist;
56         private static $conv_list = [];
57
58         /**
59          * Fetches author data
60          *
61          * @param DOMXPath $xpath     The xpath object
62          * @param object   $context   The xml context of the author details
63          * @param array    $importer  user record of the importing user
64          * @param array    $contact   Called by reference, will contain the fetched contact
65          * @param bool     $onlyfetch Only fetch the header without updating the contact entries
66          *
67          * @return array Array of author related entries for the item
68          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69          * @throws \ImagickException
70          */
71         private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, bool $onlyfetch): array
72         {
73                 $author = [];
74                 $author['author-link'] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
75                 $author['author-name'] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
76                 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
77
78                 $aliaslink = $author['author-link'];
79
80                 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
81                 if (is_object($alternate_item)) {
82                         foreach ($alternate_item->attributes as $attributes) {
83                                 if (($attributes->name == 'href') && ($attributes->textContent != '')) {
84                                         $author['author-link'] = $attributes->textContent;
85                                 }
86                         }
87                 }
88                 $author['author-id'] = Contact::getIdForURL($author['author-link']);
89
90                 $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
91
92                 $contact = [];
93
94 /*
95                 This here would be better, but we would get problems with contacts from the statusnet addon
96                 This is kept here as a reminder for the future
97
98                 $cid = Contact::getIdForURL($author['author-link'], $importer['uid']);
99                 if ($cid) {
100                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
101                 }
102 */
103                 if ($aliaslink != '') {
104                         $contact = DBA::selectFirst('contact', [], [
105                                 "`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
106                                 $importer['uid'],
107                                 $aliaslink, Protocol::STATUSNET,
108                                 Contact::SHARING, Contact::FRIEND,
109                         ]);
110                 }
111
112                 if (!DBA::isResult($contact) && $author['author-link'] != '') {
113                         if ($aliaslink == '') {
114                                 $aliaslink = $author['author-link'];
115                         }
116
117                         $contact = DBA::selectFirst('contact', [], [
118                                 "`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
119                                 $importer['uid'],
120                                 Strings::normaliseLink($author['author-link']),
121                                 Strings::normaliseLink($aliaslink),
122                                 Protocol::STATUSNET,
123                                 Contact::SHARING,
124                                 Contact::FRIEND,
125                         ]);
126                 }
127
128                 if (!DBA::isResult($contact) && ($addr != '')) {
129                         $contact = DBA::selectFirst('contact', [], [
130                                 "`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
131                                 $importer['uid'],
132                                 $addr,
133                                 Protocol::STATUSNET,
134                                 Contact::SHARING,
135                                 Contact::FRIEND,
136                         ]);
137                 }
138
139                 if (DBA::isResult($contact)) {
140                         if ($contact['blocked']) {
141                                 $contact['id'] = -1;
142                         } elseif (!empty(APContact::getByURL($contact['url'], false))) {
143                                 ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
144                         }
145                         $author['contact-id'] = $contact['id'];
146                 }
147
148                 $avatarlist = [];
149                 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
150                 foreach ($avatars as $avatar) {
151                         $href = '';
152                         $width = 0;
153                         foreach ($avatar->attributes as $attributes) {
154                                 if ($attributes->name == 'href') {
155                                         $href = $attributes->textContent;
156                                 }
157                                 if ($attributes->name == 'width') {
158                                         $width = $attributes->textContent;
159                                 }
160                         }
161                         if ($href != '') {
162                                 $avatarlist[$width] = $href;
163                         }
164                 }
165                 if (count($avatarlist) > 0) {
166                         krsort($avatarlist);
167                         $author['author-avatar'] = Probe::fixAvatar(current($avatarlist), $author['author-link']);
168                 }
169
170                 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
171                 if ($displayname != '') {
172                         $author['author-name'] = $displayname;
173                 }
174
175                 $author['owner-id'] = $author['author-id'];
176
177                 // Only update the contacts if it is an OStatus contact
178                 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact['network'] == Protocol::OSTATUS)) {
179
180                         // Update contact data
181                         $current = $contact;
182                         unset($current['name-date']);
183
184                         // This query doesn't seem to work
185                         // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
186                         // if ($value != "")
187                         //      $contact["notify"] = $value;
188
189                         // This query doesn't seem to work as well - I hate these queries
190                         // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
191                         // if ($value != "")
192                         //      $contact["poll"] = $value;
193
194                         $contact['url'] = $author['author-link'];
195                         $contact['nurl'] = Strings::normaliseLink($contact['url']);
196
197                         $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
198                         if ($value != '') {
199                                 $contact['alias'] = $value;
200                         }
201
202                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
203                         if ($value != '') {
204                                 $contact['name'] = $value;
205                         }
206
207                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
208                         if ($value != '') {
209                                 $contact['nick'] = $value;
210                         }
211
212                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
213                         if ($value != '') {
214                                 $contact['about'] = HTML::toBBCode($value);
215                         }
216
217                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
218                         if ($value != '') {
219                                 $contact['location'] = $value;
220                         }
221
222                         $contact['name-date'] = DateTimeFormat::utcNow();
223
224                         Contact::update($contact, ['id' => $contact['id']], $current);
225
226                         if (!empty($author['author-avatar']) && ($author['author-avatar'] != $current['avatar'])) {
227                                 Logger::info('Update profile picture for contact ' . $contact['id']);
228                                 Contact::updateAvatar($contact['id'], $author['author-avatar']);
229                         }
230
231                         // Ensure that we are having this contact (with uid=0)
232                         $cid = Contact::getIdForURL($aliaslink);
233
234                         if ($cid) {
235                                 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
236                                 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
237
238                                 // Update it with the current values
239                                 $fields = [
240                                         'url' => $author['author-link'],
241                                         'name' => $contact['name'],
242                                         'nurl' => Strings::normaliseLink($author['author-link']),
243                                         'nick' => $contact['nick'],
244                                         'alias' => $contact['alias'],
245                                         'about' => $contact['about'],
246                                         'location' => $contact['location'],
247                                         'success_update' => DateTimeFormat::utcNow(),
248                                         'last-update' => DateTimeFormat::utcNow(),
249                                 ];
250
251                                 Contact::update($fields, ['id' => $cid], $old_contact);
252
253                                 // Update the avatar
254                                 if (!empty($author['author-avatar'])) {
255                                         Contact::updateAvatar($cid, $author['author-avatar']);
256                                 }
257                         }
258                 } elseif (empty($contact['network']) || ($contact['network'] != Protocol::DFRN)) {
259                         $contact = [];
260                 }
261
262                 return $author;
263         }
264
265         /**
266          * Fetches author data from a given XML string
267          *
268          * @param string $xml      The XML
269          * @param array  $importer user record of the importing user
270          *
271          * @return array Array of author related entries for the item
272          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
273          * @throws \ImagickException
274          */
275         public static function salmonAuthor(string $xml, array $importer): array
276         {
277                 if (empty($xml)) {
278                         return [];
279                 }
280
281                 $doc = new DOMDocument();
282                 @$doc->loadXML($xml);
283
284                 $xpath = new DOMXPath($doc);
285                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
286                 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
287                 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
288                 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
289                 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
290                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
291                 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
292                 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
293
294                 $contact = ['id' => 0];
295
296                 // Fetch the first author
297                 $authordata = $xpath->query('//author')->item(0);
298                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
299                 return $author;
300         }
301
302         /**
303          * Read attributes from element
304          *
305          * @param object $element Element object
306          * @return array attributes
307          */
308         private static function readAttributes($element): array
309         {
310                 $attribute = [];
311
312                 foreach ($element->attributes as $attributes) {
313                         $attribute[$attributes->name] = $attributes->textContent;
314                 }
315
316                 return $attribute;
317         }
318
319         /**
320          * Imports an XML string containing OStatus elements
321          *
322          * @param string $xml      The XML
323          * @param array  $importer user record of the importing user
324          * @param array  $contact  contact
325          * @param string $hub      Called by reference, returns the fetched hub data
326          * @return void
327          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
328          * @throws \ImagickException
329          */
330         public static function import($xml, array $importer, array &$contact, &$hub)
331         {
332                 self::process($xml, $importer, $contact, $hub, false, true, Conversation::PUSH);
333         }
334
335         /**
336          * Internal feed processing
337          *
338          * @param string  $xml        The XML
339          * @param array   $importer   user record of the importing user
340          * @param array   $contact    contact
341          * @param string  $hub        Called by reference, returns the fetched hub data
342          * @param boolean $stored     Is the post fresh imported or from the database?
343          * @param boolean $initialize Is it the leading post so that data has to be initialized?
344          * @param integer $direction  Direction, default UNKNOWN(0)
345          * @return boolean Could the XML be processed?
346          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
347          * @throws \ImagickException
348          */
349         private static function process(string $xml, array $importer, array &$contact = null, string &$hub, bool $stored = false, bool $initialize = true, int $direction = Conversation::UNKNOWN)
350         {
351                 if ($initialize) {
352                         self::$itemlist = [];
353                         self::$conv_list = [];
354                 }
355
356                 Logger::info('Import OStatus message for user ' . $importer['uid']);
357
358                 if (empty($xml)) {
359                         return false;
360                 }
361
362                 $doc = new DOMDocument();
363                 @$doc->loadXML($xml);
364
365                 $xpath = new DOMXPath($doc);
366                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
367                 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
368                 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
369                 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
370                 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
371                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
372                 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
373                 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
374
375                 $hub = '';
376                 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
377                 if (is_object($hub_items)) {
378                         $hub_attributes = $hub_items->attributes;
379                         if (is_object($hub_attributes)) {
380                                 foreach ($hub_attributes as $hub_attribute) {
381                                         if ($hub_attribute->name == 'href') {
382                                                 $hub = $hub_attribute->textContent;
383                                                 Logger::info('Found hub ', ['hub' => $hub]);
384                                         }
385                                 }
386                         }
387                 }
388
389                 $header = [];
390                 $header['uid'] = $importer['uid'];
391                 $header['network'] = Protocol::OSTATUS;
392                 $header['wall'] = 0;
393                 $header['origin'] = 0;
394                 $header['gravity'] = GRAVITY_COMMENT;
395
396                 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
397                         return false;
398                 }
399
400                 $first_child = $doc->firstChild->tagName;
401
402                 if ($first_child == 'feed') {
403                         $entries = $xpath->query('/atom:feed/atom:entry');
404                 } else {
405                         $entries = $xpath->query('/atom:entry');
406                 }
407
408                 if ($entries->length == 1) {
409                         // We reformat the XML to make it better readable
410                         $doc2 = new DOMDocument();
411                         $doc2->loadXML($xml);
412                         $doc2->preserveWhiteSpace = false;
413                         $doc2->formatOutput = true;
414                         $xml2 = $doc2->saveXML();
415
416                         $header['protocol'] = Conversation::PARCEL_SALMON;
417                         $header['source'] = $xml2;
418                         $header['direction'] = $direction;
419                 } elseif (!$initialize) {
420                         return false;
421                 }
422
423                 // Fetch the first author
424                 $authordata = $xpath->query('//author')->item(0);
425                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
426
427                 // Reverse the order of the entries
428                 $entrylist = [];
429
430                 foreach ($entries as $entry) {
431                         $entrylist[] = $entry;
432                 }
433
434                 foreach (array_reverse($entrylist) as $entry) {
435                         // fetch the author
436                         $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
437
438                         if ($authorelement->length == 0) {
439                                 $authorelement = $xpath->query('atom:author', $entry);
440                         }
441
442                         if ($authorelement->length > 0) {
443                                 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
444                         }
445
446                         $item = array_merge($header, $author);
447
448                         $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
449                         $item['uri-id'] = ItemURI::insert(['uri' => $item['uri']]);
450
451                         $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
452
453                         // Delete a message
454                         if (in_array($item['verb'], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
455                                 self::deleteNotice($item);
456                                 continue;
457                         }
458
459                         if (in_array($item['verb'], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
460                                 // Ignore "Unfavorite" message
461                                 Logger::info('Ignore unfavorite message ', ['item' => $item]);
462                                 continue;
463                         }
464
465                         // Deletions come with the same uri, so we check for duplicates after processing deletions
466                         if (Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']])) {
467                                 Logger::info('Post with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
468                                 continue;
469                         } else {
470                                 Logger::info('Processing post with URI ' .  $item['uri'] . ' for user ' . $importer['uid'] . '.');
471                         }
472
473                         if ($item['verb'] == Activity::JOIN) {
474                                 // ignore "Join" messages
475                                 Logger::info('Ignore join message ', ['item' => $item]);
476                                 continue;
477                         }
478
479                         if ($item['verb'] == 'http://mastodon.social/schema/1.0/block') {
480                                 // ignore mastodon "block" messages
481                                 Logger::info('Ignore block message ', ['item' => $item]);
482                                 continue;
483                         }
484
485                         if ($item['verb'] == Activity::FOLLOW) {
486                                 Contact::addRelationship($importer, $contact, $item);
487                                 continue;
488                         }
489
490                         if ($item['verb'] == Activity::O_UNFOLLOW) {
491                                 $dummy = null;
492                                 Contact::removeFollower($contact);
493                                 continue;
494                         }
495
496                         if ($item['verb'] == Activity::FAVORITE) {
497                                 $orig_uri = $xpath->query('activity:object/atom:id', $entry)->item(0)->nodeValue;
498                                 Logger::notice('Favorite', ['uri' => $orig_uri, 'item' => $item]);
499
500                                 $item['verb'] = Activity::LIKE;
501                                 $item['thr-parent'] = $orig_uri;
502                                 $item['gravity'] = GRAVITY_ACTIVITY;
503                                 $item['object-type'] = Activity\ObjectType::NOTE;
504                         }
505
506                         // http://activitystrea.ms/schema/1.0/rsvp-yes
507                         if (!in_array($item['verb'], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
508                                 Logger::info('Unhandled verb', ['verb' => $item['verb'], 'item' => $item]);
509                         }
510
511                         self::processPost($xpath, $entry, $item, $importer);
512
513                         if ($initialize && (count(self::$itemlist) > 0)) {
514                                 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['thr-parent']) {
515                                         $uid = self::$itemlist[0]['uid'];
516                                         // We will import it everytime, when it is started by our contacts
517                                         $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], $uid);
518
519                                         if (!$valid) {
520                                                 // If not, then it depends on this setting
521                                                 $valid = !$uid || DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_NONE;
522
523                                                 if ($valid) {
524                                                         Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported due to the system settings.');
525                                                 }
526                                         } else {
527                                                 Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' belongs to a contact (' . self::$itemlist[0]['contact-id'] . '). It will be imported.');
528                                         }
529
530                                         if ($valid && DI::pConfig()->get($uid, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE) {
531                                                 // Never post a thread when the only interaction by our contact was a like
532                                                 $valid = false;
533                                                 $verbs = [Activity::POST, Activity::SHARE];
534                                                 foreach (self::$itemlist as $item) {
535                                                         if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
536                                                                 $valid = true;
537                                                         }
538                                                 }
539                                                 if ($valid) {
540                                                         Logger::info('Item with URI ' . self::$itemlist[0]['uri'] . ' will be imported since the thread contains posts or shares.');
541                                                 }
542                                         }
543                                 } else {
544                                         $valid = true;
545                                 }
546
547                                 if ($valid) {
548                                         $default_contact = 0;
549                                         for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
550                                                 if (empty(self::$itemlist[$key]['contact-id'])) {
551                                                         self::$itemlist[$key]['contact-id'] = $default_contact;
552                                                 } else {
553                                                         $default_contact = $item['contact-id'];
554                                                 }
555                                         }
556                                         foreach (self::$itemlist as $item) {
557                                                 $found = Post::exists(['uid' => $importer['uid'], 'uri' => $item['uri']]);
558                                                 if ($found) {
559                                                         Logger::notice('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already exists.');
560                                                 } elseif ($item['contact-id'] < 0) {
561                                                         Logger::notice('Item with URI ' . $item['uri'] . ' is from a blocked contact.');
562                                                 } else {
563                                                         $ret = Item::insert($item);
564                                                         Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' stored. Return value: ' . $ret);
565                                                 }
566                                         }
567                                 }
568                                 self::$itemlist = [];
569                         }
570                         Logger::info('Processing done for post with URI ' . $item['uri'] . ' for user '.$importer['uid'] . '.');
571                 }
572                 return true;
573         }
574
575         /**
576          * Removes notice item from database
577          *
578          * @param array $item item
579          * @return void
580          * @throws \Exception
581          */
582         private static function deleteNotice(array $item)
583         {
584                 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
585                 if (!Post::exists($condition)) {
586                         Logger::notice('Item from ' . $item['author-link'] . ' with uri ' . $item['uri'] . ' for user ' . $item['uid'] . " wasn't found. We don't delete it.");
587                         return;
588                 }
589
590                 Item::markForDeletion($condition);
591
592                 Logger::notice('Deleted item with URI ' . $item['uri'] . ' for user ' . $item['uid']);
593         }
594
595         /**
596          * Processes the XML for a post
597          *
598          * @param DOMXPath $xpath    The xpath object
599          * @param object   $entry    The xml entry that is processed
600          * @param array    $item     The item array
601          * @param array    $importer user record of the importing user
602          * @return void
603          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
604          * @throws \ImagickException
605          */
606         private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
607         {
608                 $item['body'] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
609                 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
610                 if (($item['object-type'] == Activity\ObjectType::BOOKMARK) || ($item['object-type'] == Activity\ObjectType::EVENT)) {
611                         $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
612                         $item['body'] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
613                 } elseif ($item['object-type'] == Activity\ObjectType::QUESTION) {
614                         $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
615                 }
616
617                 $item['created'] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
618                 $item['edited'] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
619                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
620
621                 $conv = $xpath->query('ostatus:conversation', $entry);
622                 if (is_object($conv->item(0))) {
623                         foreach ($conv->item(0)->attributes as $attributes) {
624                                 if ($attributes->name == 'ref') {
625                                         $item['conversation-uri'] = $attributes->textContent;
626                                 }
627                                 if ($attributes->name == 'href') {
628                                         $item['conversation-href'] = $attributes->textContent;
629                                 }
630                         }
631                 }
632
633                 $related = '';
634
635                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
636                 if (is_object($inreplyto->item(0))) {
637                         foreach ($inreplyto->item(0)->attributes as $attributes) {
638                                 if ($attributes->name == 'ref') {
639                                         $item['thr-parent'] = $attributes->textContent;
640                                 }
641                                 if ($attributes->name == 'href') {
642                                         $related = $attributes->textContent;
643                                 }
644                         }
645                 }
646
647                 $georsspoint = $xpath->query('georss:point', $entry);
648                 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
649                         $item['coord'] = $georsspoint->item(0)->nodeValue;
650                 }
651
652                 $categories = $xpath->query('atom:category', $entry);
653                 if ($categories) {
654                         foreach ($categories as $category) {
655                                 foreach ($category->attributes as $attributes) {
656                                         if ($attributes->name == 'term') {
657                                                 // Store the hashtag
658                                                 Tag::store($item['uri-id'], Tag::HASHTAG, $attributes->textContent);
659                                         }
660                                 }
661                         }
662                 }
663
664                 $self = '';
665                 $add_body = '';
666
667                 $links = $xpath->query('atom:link', $entry);
668                 if ($links) {
669                         $link_data = self::processLinks($links, $item);
670                         $self = $link_data['self'];
671                         $add_body = $link_data['add_body'];
672                 }
673
674                 $repeat_of = '';
675
676                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
677                 if ($notice_info && ($notice_info->length > 0)) {
678                         foreach ($notice_info->item(0)->attributes as $attributes) {
679                                 if ($attributes->name == 'source') {
680                                         $item['app'] = strip_tags($attributes->textContent);
681                                 }
682                                 if ($attributes->name == 'repeat_of') {
683                                         $repeat_of = $attributes->textContent;
684                                 }
685                         }
686                 }
687                 // Is it a repeated post?
688                 if (($repeat_of != '') || ($item['verb'] == Activity::SHARE)) {
689                         $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
690                         if (!empty($link_data['add_body'])) {
691                                 $add_body .= $link_data['add_body'];
692                         }
693                 }
694
695                 $item['body'] .= $add_body;
696
697                 Tag::storeFromBody($item['uri-id'], $item['body']);
698
699                 // Mastodon Content Warning
700                 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
701                         $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
702                         if (!empty($clear_text)) {
703                                 $item['content-warning'] = HTML::toBBCode($clear_text);
704                         }
705                 }
706
707                 if (($self != '') && empty($item['protocol'])) {
708                         self::fetchSelf($self, $item);
709                 }
710
711                 if (!empty($item['conversation-href'])) {
712                         self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
713                 }
714
715                 if (isset($item['thr-parent'])) {
716                         if (!Post::exists(['uid' => $importer['uid'], 'uri' => $item['thr-parent']])) {
717                                 if ($related != '') {
718                                         self::fetchRelated($related, $item['thr-parent'], $importer);
719                                 }
720                         } else {
721                                 Logger::info('Reply with URI ' . $item['uri'] . ' already existed for user ' . $importer['uid'] . '.');
722                         }
723                 } else {
724                         $item['thr-parent'] = $item['uri'];
725                         $item['gravity'] = GRAVITY_PARENT;
726                 }
727
728                 if (($item['author-link'] != '') && !empty($item['protocol'])) {
729                         $item = Conversation::insert($item);
730                 }
731
732                 self::$itemlist[] = $item;
733         }
734
735         /**
736          * Fetch the conversation for posts
737          *
738          * @param string $conversation     The link to the conversation
739          * @param string $conversation_uri The conversation in "uri" format
740          * @return void
741          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
742          */
743         private static function fetchConversation(string $conversation, string $conversation_uri)
744         {
745                 // Ensure that we only store a conversation once in a process
746                 if (isset(self::$conv_list[$conversation])) {
747                         return;
748                 }
749
750                 self::$conv_list[$conversation] = true;
751
752                 $curlResult = DI::httpClient()->get($conversation, HttpClientAccept::ATOM_XML);
753
754                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
755                         return;
756                 }
757
758                 $xml = '';
759
760                 if ($curlResult->inHeader('Content-Type') &&
761                         in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
762                         $xml = $curlResult->getBody();
763                 }
764
765                 if ($xml == '') {
766                         $doc = new DOMDocument();
767                         if (!@$doc->loadHTML($curlResult->getBody())) {
768                                 return;
769                         }
770                         $xpath = new DOMXPath($doc);
771
772                         $links = $xpath->query('//link');
773                         if ($links) {
774                                 $file = '';
775                                 foreach ($links as $link) {
776                                         $attribute = self::readAttributes($link);
777                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
778                                                 $file = $attribute['href'];
779                                         }
780                                 }
781                                 if ($file != '') {
782                                         $conversation_atom = DI::httpClient()->get($attribute['href'], HttpClientAccept::ATOM_XML);
783
784                                         if ($conversation_atom->isSuccess()) {
785                                                 $xml = $conversation_atom->getBody();
786                                         }
787                                 }
788                         }
789                 }
790
791                 if ($xml == '') {
792                         return;
793                 }
794
795                 self::storeConversation($xml, $conversation, $conversation_uri);
796         }
797
798         /**
799          * Store a feed in several conversation entries
800          *
801          * @param string $xml              The feed
802          * @param string $conversation     conversation
803          * @param string $conversation_uri conversation uri
804          * @return void
805          * @throws \Exception
806          */
807         private static function storeConversation(string $xml, string $conversation = '', string $conversation_uri = '')
808         {
809                 $doc = new DOMDocument();
810                 @$doc->loadXML($xml);
811
812                 $xpath = new DOMXPath($doc);
813                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
814                 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
815                 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
816
817                 $entries = $xpath->query('/atom:feed/atom:entry');
818
819                 // Now store the entries
820                 foreach ($entries as $entry) {
821                         $doc2 = new DOMDocument();
822                         $doc2->preserveWhiteSpace = false;
823                         $doc2->formatOutput = true;
824
825                         $conv_data = [];
826
827                         $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
828                         $conv_data['direction'] = Conversation::PULL;
829                         $conv_data['network'] = Protocol::OSTATUS;
830                         $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
831
832                         $inreplyto = $xpath->query('thr:in-reply-to', $entry);
833                         if (is_object($inreplyto->item(0))) {
834                                 foreach ($inreplyto->item(0)->attributes as $attributes) {
835                                         if ($attributes->name == 'ref') {
836                                                 $conv_data['reply-to-uri'] = $attributes->textContent;
837                                         }
838                                 }
839                         }
840
841                         $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
842
843                         $conv = $xpath->query('ostatus:conversation', $entry);
844                         if (is_object($conv->item(0))) {
845                                 foreach ($conv->item(0)->attributes as $attributes) {
846                                         if ($attributes->name == 'ref') {
847                                                 $conv_data['conversation-uri'] = $attributes->textContent;
848                                         }
849                                         if ($attributes->name == 'href') {
850                                                 $conv_data['conversation-href'] = $attributes->textContent;
851                                         }
852                                 }
853                         }
854
855                         if ($conversation != '') {
856                                 $conv_data['conversation-uri'] = $conversation;
857                         }
858
859                         if ($conversation_uri != '') {
860                                 $conv_data['conversation-uri'] = $conversation_uri;
861                         }
862
863                         $entry = $doc2->importNode($entry, true);
864
865                         $doc2->appendChild($entry);
866
867                         $conv_data['source'] = $doc2->saveXML();
868
869                         Logger::info('Store conversation data for uri '.$conv_data['uri']);
870                         Conversation::insert($conv_data);
871                 }
872         }
873
874         /**
875          * Fetch the own post so that it can be stored later
876          *
877          * We want to store the original data for later processing.
878          * This function is meant for cases where we process a feed with multiple entries.
879          * In that case we need to fetch the single posts here.
880          *
881          * @param string $self The link to the self item
882          * @param array  $item The item array
883          * @return void
884          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
885          */
886         private static function fetchSelf(string $self, array &$item)
887         {
888                 $condition = ['item-uri' => $self, 'protocol' => [Conversation::PARCEL_DFRN,
889                         Conversation::PARCEL_DIASPORA_DFRN, Conversation::PARCEL_LOCAL_DFRN,
890                         Conversation::PARCEL_DIRECT, Conversation::PARCEL_SALMON]];
891                 if (DBA::exists('conversation', $condition)) {
892                         Logger::info('Conversation '.$item['uri'].' is already stored.');
893                         return;
894                 }
895
896                 $curlResult = DI::httpClient()->get($self, HttpClientAccept::ATOM_XML);
897
898                 if (!$curlResult->isSuccess()) {
899                         return;
900                 }
901
902                 // We reformat the XML to make it better readable
903                 $doc = new DOMDocument();
904                 $doc->loadXML($curlResult->getBody());
905                 $doc->preserveWhiteSpace = false;
906                 $doc->formatOutput = true;
907                 $xml = $doc->saveXML();
908
909                 $item['protocol'] = Conversation::PARCEL_SALMON;
910                 $item['source'] = $xml;
911                 $item['direction'] = Conversation::PULL;
912
913                 Logger::info('Conversation '.$item['uri'].' is now fetched.');
914         }
915
916         /**
917          * Fetch related posts and processes them
918          *
919          * @param string $related     The link to the related item
920          * @param string $related_uri The related item in "uri" format
921          * @param array  $importer    user record of the importing user
922          * @return void
923          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
924          * @throws \ImagickException
925          */
926         private static function fetchRelated(string $related, string $related_uri, array $importer)
927         {
928                 $condition = [
929                         'item-uri' => $related_uri,
930                         'protocol' => [
931                                 Conversation::PARCEL_DFRN,
932                                 Conversation::PARCEL_DIASPORA_DFRN,
933                                 Conversation::PARCEL_LOCAL_DFRN,
934                                 Conversation::PARCEL_DIRECT,
935                                 Conversation::PARCEL_SALMON,
936                         ],
937                 ];
938                 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
939                 if (DBA::isResult($conversation)) {
940                         $stored = true;
941                         $xml = $conversation['source'];
942                         if (self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL)) {
943                                 Logger::info('Got valid cached XML for URI '.$related_uri);
944                                 return;
945                         }
946                         if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
947                                 Logger::info('Delete invalid cached XML for URI '.$related_uri);
948                                 DBA::delete('conversation', ['item-uri' => $related_uri]);
949                         }
950                 }
951
952                 $stored = false;
953                 $curlResult = DI::httpClient()->get($related, HttpClientAccept::ATOM_XML);
954
955                 if (!$curlResult->isSuccess() || empty($curlResult->getBody())) {
956                         return;
957                 }
958
959                 $xml = '';
960
961                 if ($curlResult->inHeader('Content-Type') &&
962                         in_array('application/atom+xml', $curlResult->getHeader('Content-Type'))) {
963                         Logger::info('Directly fetched XML for URI ' . $related_uri);
964                         $xml = $curlResult->getBody();
965                 }
966
967                 if ($xml == '') {
968                         $doc = new DOMDocument();
969                         if (!@$doc->loadHTML($curlResult->getBody())) {
970                                 return;
971                         }
972                         $xpath = new DOMXPath($doc);
973
974                         $atom_file = '';
975
976                         $links = $xpath->query('//link');
977                         if ($links) {
978                                 foreach ($links as $link) {
979                                         $attribute = self::readAttributes($link);
980                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
981                                                 $atom_file = $attribute['href'];
982                                         }
983                                 }
984                                 if ($atom_file != '') {
985                                         $curlResult = DI::httpClient()->get($atom_file, HttpClientAccept::ATOM_XML);
986
987                                         if ($curlResult->isSuccess()) {
988                                                 Logger::info('Fetched XML for URI ' . $related_uri);
989                                                 $xml = $curlResult->getBody();
990                                         }
991                                 }
992                         }
993                 }
994
995                 // Workaround for older GNU Social servers
996                 if (($xml == '') && strstr($related, '/notice/')) {
997                         $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related) . '.atom', HttpClientAccept::ATOM_XML);
998
999                         if ($curlResult->isSuccess()) {
1000                                 Logger::info('GNU Social workaround to fetch XML for URI ' . $related_uri);
1001                                 $xml = $curlResult->getBody();
1002                         }
1003                 }
1004
1005                 // Even more worse workaround for GNU Social ;-)
1006                 if ($xml == '') {
1007                         $related_guess = self::convertHref($related_uri);
1008                         $curlResult = DI::httpClient()->get(str_replace('/notice/', '/api/statuses/show/', $related_guess) . '.atom', HttpClientAccept::ATOM_XML);
1009
1010                         if ($curlResult->isSuccess()) {
1011                                 Logger::info('GNU Social workaround 2 to fetch XML for URI ' . $related_uri);
1012                                 $xml = $curlResult->getBody();
1013                         }
1014                 }
1015
1016                 // Finally we take the data that we fetched from "ostatus:conversation"
1017                 if ($xml == '') {
1018                         $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
1019                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1020                         if (DBA::isResult($conversation)) {
1021                                 $stored = true;
1022                                 Logger::info('Got cached XML from conversation for URI ' . $related_uri);
1023                                 $xml = $conversation['source'];
1024                         }
1025                 }
1026
1027                 if ($xml != '') {
1028                         self::process($xml, $importer, $contact, $hub, $stored, false, Conversation::PULL);
1029                 } else {
1030                         Logger::info('XML could not be fetched for URI: ' . $related_uri . ' - href: ' . $related);
1031                 }
1032                 return;
1033         }
1034
1035         /**
1036          * Processes the XML for a repeated post
1037          *
1038          * @param DOMXPath $xpath    The xpath object
1039          * @param object   $entry    The xml entry that is processed
1040          * @param array    $item     The item array
1041          * @param array    $importer user record of the importing user
1042          *
1043          * @return array with data from links
1044          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1045          * @throws \ImagickException
1046          */
1047         private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer): array
1048         {
1049                 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1050
1051                 if (!is_object($activityobject)) {
1052                         return [];
1053                 }
1054
1055                 $link_data = [];
1056
1057                 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1058
1059                 $links = $xpath->query('atom:link', $activityobject);
1060                 if ($links) {
1061                         $link_data = self::processLinks($links, $item);
1062                 }
1063
1064                 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1065                 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1066                 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1067
1068                 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1069
1070                 $item['author-name'] = $orig_author['author-name'];
1071                 $item['author-link'] = $orig_author['author-link'];
1072                 $item['author-id'] = $orig_author['author-id'];
1073
1074                 $item['body'] = HTML::toBBCode($orig_body);
1075                 $item['created'] = $orig_created;
1076                 $item['edited'] = $orig_edited;
1077
1078                 $item['uri'] = $orig_uri;
1079
1080                 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1081
1082                 $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1083
1084                 // Mastodon Content Warning
1085                 if (($item['verb'] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1086                         $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1087                         if (!empty($clear_text)) {
1088                                 $item['content-warning'] = HTML::toBBCode($clear_text);
1089                         }
1090                 }
1091
1092                 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1093                 if (is_object($inreplyto->item(0))) {
1094                         foreach ($inreplyto->item(0)->attributes as $attributes) {
1095                                 if ($attributes->name == 'ref') {
1096                                         $item['thr-parent'] = $attributes->textContent;
1097                                 }
1098                         }
1099                 }
1100
1101                 return $link_data;
1102         }
1103
1104         /**
1105          * Processes links in the XML
1106          *
1107          * @param object $links The xml data that contain links
1108          * @param array  $item  The item array
1109          * @return array with data from the links
1110          */
1111         private static function processLinks($links, array &$item): array
1112         {
1113                 $link_data = ['add_body' => '', 'self' => ''];
1114
1115                 foreach ($links as $link) {
1116                         $attribute = self::readAttributes($link);
1117
1118                         if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1119                                 switch ($attribute['rel']) {
1120                                         case 'alternate':
1121                                                 $item['plink'] = $attribute['href'];
1122                                                 if (($item['object-type'] == Activity\ObjectType::QUESTION)
1123                                                         || ($item['object-type'] == Activity\ObjectType::EVENT)
1124                                                 ) {
1125                                                         Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
1126                                                                 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
1127                                                                 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1128                                                 }
1129                                                 break;
1130
1131                                         case 'ostatus:conversation':
1132                                                 $link_data['conversation'] = $attribute['href'];
1133                                                 $item['conversation-href'] = $link_data['conversation'];
1134                                                 if (!isset($item['conversation-uri'])) {
1135                                                         $item['conversation-uri'] = $item['conversation-href'];
1136                                                 }
1137                                                 break;
1138
1139                                         case 'enclosure':
1140                                                 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1141                                                 if ($filetype == 'image') {
1142                                                         $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1143                                                 } else {
1144                                                         Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1145                                                                 'url' => $attribute['href'], 'mimetype' => $attribute['type'],
1146                                                                 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1147                                                 }
1148                                                 break;
1149
1150                                         case 'related':
1151                                                 if ($item['object-type'] != Activity\ObjectType::BOOKMARK) {
1152                                                         if (!isset($item['thr-parent'])) {
1153                                                                 $item['thr-parent'] = $attribute['href'];
1154                                                         }
1155                                                         $link_data['related'] = $attribute['href'];
1156                                                 } else {
1157                                                         Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::UNKNOWN,
1158                                                                 'url' => $attribute['href'], 'mimetype' => $attribute['type'] ?? null,
1159                                                                 'size' => $attribute['length'] ?? null, 'description' => $attribute['title'] ?? null]);
1160                                                 }
1161                                                 break;
1162
1163                                         case 'self':
1164                                                 if (empty($item['plink'])) {
1165                                                         $item['plink'] = $attribute['href'];
1166                                                 }
1167                                                 $link_data['self'] = $attribute['href'];
1168                                                 break;
1169
1170                                         default:
1171                                                 Logger::warning('Unsupported rel=' . $attribute['rel'] . ', href=' . $attribute['href'] . ', object-type=' . $attribute['object-type']);
1172                                 }
1173                         }
1174                 }
1175                 return $link_data;
1176         }
1177
1178         /**
1179          * Create an url out of an uri
1180          *
1181          * @param string $href URI in the format "parameter1:parameter1:..."
1182          * @return string URL in the format http(s)://....
1183          */
1184         private static function convertHref(string $href): string
1185         {
1186                 $elements = explode(':', $href);
1187
1188                 if ((count($elements) <= 2) || ($elements[0] != 'tag')) {
1189                         return $href;
1190                 }
1191
1192                 $server = explode(',', $elements[1]);
1193                 $conversation = explode('=', $elements[2]);
1194
1195                 if ((count($elements) == 4) && ($elements[2] == 'post')) {
1196                         return 'http://' . $server[0] . '/notice/' . $elements[3];
1197                 }
1198
1199                 if ((count($conversation) != 2) || ($conversation[1] == '')) {
1200                         return $href;
1201                 }
1202
1203                 if ($elements[3] == 'objectType=thread') {
1204                         return 'http://' . $server[0] . '/conversation/' . $conversation[1];
1205                 } else {
1206                         return 'http://' . $server[0] . '/notice/' . $conversation[1];
1207                 }
1208         }
1209
1210         /**
1211          * Cleans the body of a post if it contains picture links
1212          *
1213          * @param string $body The body
1214          * @param integer $uriId
1215          * @return string The cleaned body
1216          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1217          */
1218         public static function formatPicturePost(string $body, int $uriid): string
1219         {
1220                 $siteinfo = BBCode::getAttachedData($body);
1221
1222                 if (($siteinfo['type'] == 'photo') && (!empty($siteinfo['preview']) || !empty($siteinfo['image']))) {
1223                         if (isset($siteinfo['preview'])) {
1224                                 $preview = $siteinfo['preview'];
1225                         } else {
1226                                 $preview = $siteinfo['image'];
1227                         }
1228
1229                         // Is it a remote picture? Then make a smaller preview here
1230                         $preview = Post\Link::getByLink($uriid, $preview, Proxy::SIZE_SMALL);
1231
1232                         // Is it a local picture? Then make it smaller here
1233                         $preview = str_replace(['-0.jpg', '-0.png'], ['-2.jpg', '-2.png'], $preview);
1234                         $preview = str_replace(['-1.jpg', '-1.png'], ['-2.jpg', '-2.png'], $preview);
1235
1236                         if (isset($siteinfo['url'])) {
1237                                 $url = $siteinfo['url'];
1238                         } else {
1239                                 $url = $siteinfo['image'];
1240                         }
1241
1242                         $body = trim($siteinfo['text']) . ' [url]' . $url . "[/url]\n[img]" . $preview . '[/img]';
1243                 }
1244
1245                 return $body;
1246         }
1247
1248         /**
1249          * Adds the header elements to the XML document
1250          *
1251          * @param DOMDocument $doc       XML document
1252          * @param array       $owner     Contact data of the poster
1253          * @param string      $filter    The related feed filter (activity, posts or comments)
1254          *
1255          * @return DOMElement Header root element
1256          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1257          */
1258         private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
1259         {
1260                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
1261                 $doc->appendChild($root);
1262
1263                 $root->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
1264                 $root->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
1265                 $root->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1266                 $root->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1267                 $root->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1268                 $root->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1269                 $root->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1270                 $root->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1271
1272                 $title = '';
1273                 $selfUri = '/feed/' . $owner['nick'] . '/';
1274                 switch ($filter) {
1275                         case 'activity':
1276                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
1277                                 $selfUri .= $filter;
1278                                 break;
1279
1280                         case 'posts':
1281                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
1282                                 break;
1283
1284                         case 'comments':
1285                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
1286                                 $selfUri .= $filter;
1287                                 break;
1288                 }
1289
1290                 $selfUri = '/dfrn_poll/' . $owner['nick'];
1291
1292                 $attributes = [
1293                         'uri' => 'https://friendi.ca',
1294                         'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
1295                 ];
1296                 XML::addElement($doc, $root, 'generator', FRIENDICA_PLATFORM, $attributes);
1297                 XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
1298                 XML::addElement($doc, $root, 'title', $title);
1299                 XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
1300                 XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
1301                 XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1302
1303                 $author = self::addAuthor($doc, $owner, true);
1304                 $root->appendChild($author);
1305
1306                 $attributes = [
1307                         'href' => $owner['url'],
1308                         'rel' => 'alternate',
1309                         'type' => 'text/html',
1310                 ];
1311                 XML::addElement($doc, $root, 'link', '', $attributes);
1312
1313                 /// @TODO We have to find out what this is
1314                 /// $attributes = array("href" => DI::baseUrl()."/sup",
1315                 ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1316                 ///             "type" => "application/json");
1317                 /// XML::addElement($doc, $root, "link", "", $attributes);
1318
1319                 self::addHubLink($doc, $root, $owner['nick']);
1320
1321                 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'salmon'];
1322                 XML::addElement($doc, $root, 'link', '', $attributes);
1323
1324                 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-replies'];
1325                 XML::addElement($doc, $root, 'link', '', $attributes);
1326
1327                 $attributes = ['href' => DI::baseUrl() . '/salmon/' . $owner['nick'], 'rel' => 'http://salmon-protocol.org/ns/salmon-mention'];
1328                 XML::addElement($doc, $root, 'link', '', $attributes);
1329
1330                 $attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
1331                 XML::addElement($doc, $root, 'link', '', $attributes);
1332
1333                 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1334                         $members = DBA::count('contact', [
1335                                 'uid'     => $owner['uid'],
1336                                 'self'    => false,
1337                                 'pending' => false,
1338                                 'archive' => false,
1339                                 'hidden'  => false,
1340                                 'blocked' => false,
1341                         ]);
1342                         XML::addElement($doc, $root, 'statusnet:group_info', '', ['member_count' => $members]);
1343                 }
1344
1345                 return $root;
1346         }
1347
1348         /**
1349          * Add the link to the push hubs to the XML document
1350          *
1351          * @param DOMDocument $doc  XML document
1352          * @param DOMElement  $root XML root element where the hub links are added
1353          * @param string      $nick Nickname
1354          * @return void
1355          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1356          */
1357         public static function addHubLink(DOMDocument $doc, DOMElement $root, string $nick)
1358         {
1359                 $h = DI::baseUrl() . '/pubsubhubbub/' . $nick;
1360                 XML::addElement($doc, $root, 'link', '', ['href' => $h, 'rel' => 'hub']);
1361         }
1362
1363         /**
1364          * Adds attachment data to the XML document
1365          *
1366          * @param DOMDocument $doc  XML document
1367          * @param DOMElement  $root XML root element where the hub links are added
1368          * @param array       $item Data of the item that is to be posted
1369          * @return void
1370          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1371          */
1372         public static function getAttachment(DOMDocument $doc, DOMElement $root, array $item)
1373         {
1374                 $siteinfo = BBCode::getAttachedData($item['body']);
1375
1376                 switch ($siteinfo['type']) {
1377                         case 'photo':
1378                                 if (!empty($siteinfo['image'])) {
1379                                         $imgdata = Images::getInfoFromURLCached($siteinfo['image']);
1380                                         if ($imgdata) {
1381                                                 $attributes = [
1382                                                         'rel' => 'enclosure',
1383                                                         'href' => $siteinfo['image'],
1384                                                         'type' => $imgdata['mime'],
1385                                                         'length' => intval($imgdata['size']),
1386                                                 ];
1387                                                 XML::addElement($doc, $root, 'link', '', $attributes);
1388                                         }
1389                                 }
1390                                 break;
1391
1392                         case 'video':
1393                                 $attributes = [
1394                                         'rel' => 'enclosure',
1395                                         'href' => $siteinfo['url'],
1396                                         'type' => 'text/html; charset=UTF-8',
1397                                         'length' => '0',
1398                                         'title' => ($siteinfo['title'] ?? '') ?: $siteinfo['url'],
1399                                 ];
1400                                 XML::addElement($doc, $root, 'link', '', $attributes);
1401                                 break;
1402
1403                         default:
1404                                 Logger::warning('Unsupported type', ['type' => $siteinfo['type'], 'url' => $siteinfo['url'] ?? '']);
1405                                 break;
1406                 }
1407
1408                 if (!DI::config()->get('system', 'ostatus_not_attach_preview') && ($siteinfo['type'] != 'photo') && isset($siteinfo['image'])) {
1409                         $imgdata = Images::getInfoFromURLCached($siteinfo['image']);
1410                         if ($imgdata) {
1411                                 $attributes = [
1412                                         'rel' => 'enclosure',
1413                                         'href' => $siteinfo['image'],
1414                                         'type' => $imgdata['mime'],
1415                                         'length' => intval($imgdata['size']),
1416                                 ];
1417
1418                                 XML::addElement($doc, $root, 'link', '', $attributes);
1419                         }
1420                 }
1421
1422                 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1423                         $attributes = ['rel' => 'enclosure',
1424                                 'href' => $attachment['url'],
1425                                 'type' => $attachment['mimetype']];
1426
1427                         if (!empty($attachment['size'])) {
1428                                 $attributes['length'] = intval($attachment['size']);
1429                         }
1430                         if (!empty($attachment['description'])) {
1431                                 $attributes['title'] = $attachment['description'];
1432                         }
1433
1434                         XML::addElement($doc, $root, 'link', '', $attributes);
1435                 }
1436         }
1437
1438         /**
1439          * Adds the author element to the XML document
1440          *
1441          * @param DOMDocument $doc          XML document
1442          * @param array       $owner        Contact data of the poster
1443          * @param bool        $show_profile Whether to show profile
1444          * @return DOMElement Author element
1445          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1446          */
1447         private static function addAuthor(DOMDocument $doc, array $owner, bool $show_profile = true): DOMElement
1448         {
1449                 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid']]);
1450                 $author = $doc->createElement('author');
1451                 XML::addElement($doc, $author, 'id', $owner['url']);
1452                 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1453                         XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::GROUP);
1454                 } else {
1455                         XML::addElement($doc, $author, 'activity:object-type', Activity\ObjectType::PERSON);
1456                 }
1457
1458                 XML::addElement($doc, $author, 'uri', $owner['url']);
1459                 XML::addElement($doc, $author, 'name', $owner['nick']);
1460                 XML::addElement($doc, $author, 'email', $owner['addr']);
1461                 if ($show_profile) {
1462                         XML::addElement($doc, $author, 'summary', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1463                 }
1464
1465                 $attributes = [
1466                         'rel' => 'alternate',
1467                         'type' => 'text/html',
1468                         'href' => $owner['url'],
1469                 ];
1470                 XML::addElement($doc, $author, 'link', '', $attributes);
1471
1472                 $attributes = [
1473                         'rel' => 'avatar',
1474                         'type' => 'image/jpeg', // To-Do?
1475                         'media:width' => Proxy::PIXEL_SMALL,
1476                         'media:height' => Proxy::PIXEL_SMALL,
1477                         'href' => User::getAvatarUrl($owner, Proxy::SIZE_SMALL),
1478                 ];
1479                 XML::addElement($doc, $author, 'link', '', $attributes);
1480
1481                 if (isset($owner['thumb'])) {
1482                         $attributes = [
1483                                 'rel' => 'avatar',
1484                                 'type' => 'image/jpeg', // To-Do?
1485                                 'media:width' => Proxy::PIXEL_THUMB,
1486                                 'media:height' => Proxy::PIXEL_THUMB,
1487                                 'href' => User::getAvatarUrl($owner, Proxy::SIZE_THUMB),
1488                         ];
1489                         XML::addElement($doc, $author, 'link', '', $attributes);
1490                 }
1491
1492                 XML::addElement($doc, $author, 'poco:preferredUsername', $owner['nick']);
1493                 XML::addElement($doc, $author, 'poco:displayName', $owner['name']);
1494                 if ($show_profile) {
1495                         XML::addElement($doc, $author, 'poco:note', BBCode::convertForUriId($owner['uri-id'], $owner['about'], BBCode::OSTATUS));
1496
1497                         if (trim($owner['location']) != '') {
1498                                 $element = $doc->createElement('poco:address');
1499                                 XML::addElement($doc, $element, 'poco:formatted', $owner['location']);
1500                                 $author->appendChild($element);
1501                         }
1502                 }
1503
1504                 if (DBA::isResult($profile) && !$show_profile) {
1505                         if (trim($profile['homepage']) != '') {
1506                                 $urls = $doc->createElement('poco:urls');
1507                                 XML::addElement($doc, $urls, 'poco:type', 'homepage');
1508                                 XML::addElement($doc, $urls, 'poco:value', $profile['homepage']);
1509                                 XML::addElement($doc, $urls, 'poco:primary', 'true');
1510                                 $author->appendChild($urls);
1511                         }
1512
1513                         XML::addElement($doc, $author, 'followers', '', ['url' => DI::baseUrl() . '/profile/' . $owner['nick'] . '/contacts/followers']);
1514                         XML::addElement($doc, $author, 'statusnet:profile_info', '', ['local_id' => $owner['uid']]);
1515
1516                         if ($profile['publish']) {
1517                                 XML::addElement($doc, $author, 'mastodon:scope', 'public');
1518                         }
1519                 }
1520
1521                 return $author;
1522         }
1523
1524         /**
1525          * @TODO Picture attachments should look like this:
1526          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1527          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1528          */
1529
1530         /**
1531          * Returns the given activity if present - otherwise returns the "post" activity
1532          *
1533          * @param array $item Data of the item that is to be posted
1534          * @return string activity
1535          */
1536         public static function constructVerb(array $item): string
1537         {
1538                 if (!empty($item['verb'])) {
1539                         return $item['verb'];
1540                 }
1541
1542                 return Activity::POST;
1543         }
1544
1545         /**
1546          * Returns the given object type if present - otherwise returns the "note" object type
1547          *
1548          * @param array $item Data of the item that is to be posted
1549          * @return string Object type
1550          */
1551         private static function constructObjecttype(array $item): string
1552         {
1553                 if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
1554                         return $item['object-type'];
1555                 }
1556
1557                 return Activity\ObjectType::NOTE;
1558         }
1559
1560         /**
1561          * Adds an entry element to the XML document
1562          *
1563          * @param DOMDocument $doc       XML document
1564          * @param array       $item      Data of the item that is to be posted
1565          * @param array       $owner     Contact data of the poster
1566          * @param bool        $toplevel  optional default false
1567          *
1568          * @return DOMElement Entry element
1569          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1570          * @throws \ImagickException
1571          */
1572         private static function entry(DOMDocument $doc, array $item, array $owner, bool $toplevel = false): DOMElement
1573         {
1574                 if ($item['verb'] == Activity::LIKE) {
1575                         return self::likeEntry($doc, $item, $owner, $toplevel);
1576                 } elseif (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
1577                         return self::followEntry($doc, $item, $owner, $toplevel);
1578                 } else {
1579                         return self::noteEntry($doc, $item, $owner, $toplevel);
1580                 }
1581         }
1582
1583         /**
1584          * Adds an entry element with a "like"
1585          *
1586          * @param DOMDocument $doc      XML document
1587          * @param array       $item     Data of the item that is to be posted
1588          * @param array       $owner    Contact data of the poster
1589          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1590          * @return DOMElement Entry element with "like"
1591          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1592          * @throws \ImagickException
1593          */
1594         private static function likeEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1595         {
1596                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1597                         Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1598                 }
1599
1600                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1601
1602                 $verb = ActivityNamespace::ACTIVITY_SCHEMA . 'favorite';
1603                 self::entryContent($doc, $entry, $item, $owner, 'Favorite', $verb, false);
1604
1605                 $parent = Post::selectFirst([], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
1606                 if (DBA::isResult($parent)) {
1607                         $as_object = $doc->createElement('activity:object');
1608
1609                         XML::addElement($doc, $as_object, 'activity:object-type', self::constructObjecttype($parent));
1610
1611                         self::entryContent($doc, $as_object, $parent, $owner, 'New entry');
1612
1613                         $entry->appendChild($as_object);
1614                 }
1615
1616                 self::entryFooter($doc, $entry, $item, $owner);
1617
1618                 return $entry;
1619         }
1620
1621         /**
1622          * Adds the person object element to the XML document
1623          *
1624          * @param DOMDocument $doc     XML document
1625          * @param array       $owner   Contact data of the poster
1626          * @param array       $contact Contact data of the target
1627          * @return DOMElement author element
1628          */
1629         private static function addPersonObject(DOMDocument $doc, array $owner, array $contact): DOMElement
1630         {
1631                 $object = $doc->createElement('activity:object');
1632                 XML::addElement($doc, $object, 'activity:object-type', Activity\ObjectType::PERSON);
1633
1634                 if ($contact['network'] == Protocol::PHANTOM) {
1635                         XML::addElement($doc, $object, 'id', $contact['url']);
1636                         return $object;
1637                 }
1638
1639                 XML::addElement($doc, $object, 'id', $contact['alias']);
1640                 XML::addElement($doc, $object, 'title', $contact['nick']);
1641
1642                 XML::addElement($doc, $object, 'link', '', [
1643                         'rel' => 'alternate',
1644                         'type' => 'text/html',
1645                         'href' => $contact['url'],
1646                 ]);
1647
1648                 $attributes = [
1649                         'rel' => 'avatar',
1650                         'type' => 'image/jpeg', // To-Do?
1651                         'media:width' => 300,
1652                         'media:height' => 300,
1653                         'href' => $contact['photo'],
1654                 ];
1655                 XML::addElement($doc, $object, 'link', '', $attributes);
1656
1657                 XML::addElement($doc, $object, 'poco:preferredUsername', $contact['nick']);
1658                 XML::addElement($doc, $object, 'poco:displayName', $contact['name']);
1659
1660                 if (trim($contact['location']) != '') {
1661                         $element = $doc->createElement('poco:address');
1662                         XML::addElement($doc, $element, 'poco:formatted', $contact['location']);
1663                         $object->appendChild($element);
1664                 }
1665
1666                 return $object;
1667         }
1668
1669         /**
1670          * Adds a follow/unfollow entry element
1671          *
1672          * @param DOMDocument $doc      XML document
1673          * @param array       $item     Data of the follow/unfollow message
1674          * @param array       $owner    Contact data of the poster
1675          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1676          * @return DOMElement Entry element
1677          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1678          * @throws \ImagickException
1679          */
1680         private static function followEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1681         {
1682                 $item['id'] = $item['parent'] = 0;
1683                 $item['created'] = $item['edited'] = date('c');
1684                 $item['private'] = Item::PRIVATE;
1685
1686                 $contact = Contact::getByURL($item['follow']);
1687                 $item['follow'] = $contact['url'];
1688
1689                 if ($contact['alias']) {
1690                         $item['follow'] = $contact['alias'];
1691                 } else {
1692                         $contact['alias'] = $contact['url'];
1693                 }
1694
1695                 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact['url'])];
1696                 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1697
1698                 if (DBA::isResult($user_contact)) {
1699                         $connect_id = $user_contact['id'];
1700                 } else {
1701                         $connect_id = 0;
1702                 }
1703
1704                 if ($item['verb'] == Activity::FOLLOW) {
1705                         $message = DI::l10n()->t('%s is now following %s.');
1706                         $title = DI::l10n()->t('following');
1707                         $action = 'subscription';
1708                 } else {
1709                         $message = DI::l10n()->t('%s stopped following %s.');
1710                         $title = DI::l10n()->t('stopped following');
1711                         $action = 'unfollow';
1712                 }
1713
1714                 $item['uri'] = $item['parent-uri'] = $item['thr-parent']
1715                                 = 'tag:' . DI::baseUrl()->getHostname().
1716                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1717                                 ':person:'.$connect_id.':'.$item['created'];
1718
1719                 $item['body'] = sprintf($message, $owner['nick'], $contact['nick']);
1720
1721                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1722
1723                 self::entryContent($doc, $entry, $item, $owner, $title);
1724
1725                 $object = self::addPersonObject($doc, $owner, $contact);
1726                 $entry->appendChild($object);
1727
1728                 self::entryFooter($doc, $entry, $item, $owner);
1729
1730                 return $entry;
1731         }
1732
1733         /**
1734          * Adds a regular entry element
1735          *
1736          * @param DOMDocument $doc       XML document
1737          * @param array       $item      Data of the item that is to be posted
1738          * @param array       $owner     Contact data of the poster
1739          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1740          * @return DOMElement Entry element
1741          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1742          * @throws \ImagickException
1743          */
1744         private static function noteEntry(DOMDocument $doc, array $item, array $owner, bool $toplevel): DOMElement
1745         {
1746                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
1747                         Logger::info('OStatus entry is from author ' . $owner['url'] . ' - not from ' . $item['author-link'] . '. Quitting.');
1748                 }
1749
1750                 if (!$toplevel) {
1751                         if (!empty($item['title'])) {
1752                                 $title = BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::OSTATUS);
1753                         } else {
1754                                 $title = sprintf('New note by %s', $owner['nick']);
1755                         }
1756                 } else {
1757                         $title = sprintf('New comment by %s', $owner['nick']);
1758                 }
1759
1760                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1761
1762                 XML::addElement($doc, $entry, 'activity:object-type', Activity\ObjectType::NOTE);
1763
1764                 self::entryContent($doc, $entry, $item, $owner, $title, '', true);
1765
1766                 self::entryFooter($doc, $entry, $item, $owner, true);
1767
1768                 return $entry;
1769         }
1770
1771         /**
1772          * Adds a header element to the XML document
1773          *
1774          * @param DOMDocument $doc      XML document
1775          * @param array       $owner    Contact data of the poster
1776          * @param array       $item
1777          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1778          * @return DOMElement The entry element where the elements are added
1779          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1780          * @throws \ImagickException
1781          */
1782         public static function entryHeader(DOMDocument $doc, array $owner, array $item, bool $toplevel): DOMElement
1783         {
1784                 if (!$toplevel) {
1785                         $entry = $doc->createElement('entry');
1786
1787                         if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1788                                 $contact = Contact::getByURL($item['author-link']) ?: $owner;
1789                                 $contact['nickname'] = $contact['nickname'] ?? $contact['nick']; 
1790                                 $author = self::addAuthor($doc, $contact, false);
1791                                 $entry->appendChild($author);
1792                         }
1793                 } else {
1794                         $entry = $doc->createElementNS(ActivityNamespace::ATOM1, 'entry');
1795
1796                         $entry->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
1797                         $entry->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
1798                         $entry->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
1799                         $entry->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
1800                         $entry->setAttribute('xmlns:poco', ActivityNamespace::POCO);
1801                         $entry->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
1802                         $entry->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
1803                         $entry->setAttribute('xmlns:mastodon', ActivityNamespace::MASTODON);
1804
1805                         $author = self::addAuthor($doc, $owner);
1806                         $entry->appendChild($author);
1807                 }
1808
1809                 return $entry;
1810         }
1811
1812         /**
1813          * Adds elements to the XML document
1814          *
1815          * @param DOMDocument $doc       XML document
1816          * @param DOMElement  $entry     Entry element where the content is added
1817          * @param array       $item      Data of the item that is to be posted
1818          * @param array       $owner     Contact data of the poster
1819          * @param string      $title     Title for the post
1820          * @param string      $verb      The activity verb
1821          * @param bool        $complete  Add the "status_net" element?
1822          * @return void
1823          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1824          */
1825         private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, array $owner, string $title, string $verb = '', bool $complete = true)
1826         {
1827                 if ($verb == '') {
1828                         $verb = self::constructVerb($item);
1829                 }
1830
1831                 XML::addElement($doc, $entry, 'id', $item['uri']);
1832                 XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1833
1834                 $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
1835                 $body = self::formatPicturePost($body, $item['uri-id']);
1836
1837                 if (!empty($item['title'])) {
1838                         $body = '[b]' . $item['title'] . "[/b]\n\n" . $body;
1839                 }
1840
1841                 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::OSTATUS);
1842
1843                 XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
1844
1845                 XML::addElement($doc, $entry, 'link', '', [
1846                         'rel' => 'alternate',
1847                         'type' => 'text/html',
1848                         'href' => DI::baseUrl() . '/display/' . $item['guid'],
1849                 ]);
1850
1851                 if ($complete && ($item['id'] > 0)) {
1852                         XML::addElement($doc, $entry, 'status_net', '', ['notice_id' => $item['id']]);
1853                 }
1854
1855                 XML::addElement($doc, $entry, 'activity:verb', $verb);
1856
1857                 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
1858                 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
1859         }
1860
1861         /**
1862          * Adds the elements at the foot of an entry to the XML document
1863          *
1864          * @param DOMDocument $doc       XML document
1865          * @param object      $entry     The entry element where the elements are added
1866          * @param array       $item      Data of the item that is to be posted
1867          * @param array       $owner     Contact data of the poster
1868          * @param bool        $complete  default true
1869          * @return void
1870          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1871          */
1872         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, bool $complete = true)
1873         {
1874                 $mentioned = [];
1875
1876                 if ($item['gravity'] != GRAVITY_PARENT) {
1877                         $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1878
1879                         $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner['uid'], 'uri' => $item['thr-parent']]);
1880
1881                         if (DBA::isResult($thrparent)) {
1882                                 $mentioned[$thrparent['author-link']] = $thrparent['author-link'];
1883                                 $mentioned[$thrparent['owner-link']]  = $thrparent['owner-link'];
1884                                 $parent_plink                         = $thrparent['plink'];
1885                         } elseif (DBA::isResult($parent)) {
1886                                 $mentioned[$parent['author-link']] = $parent['author-link'];
1887                                 $mentioned[$parent['owner-link']]  = $parent['owner-link'];
1888                                 $parent_plink                      = DI::baseUrl() . '/display/' . $parent['guid'];
1889                         } else {
1890                                 DI::logger()->notice('Missing parent and thr-parent for child item', ['item' => $item]);
1891                         }
1892
1893                         if (isset($parent_plink)) {
1894                                 $attributes = [
1895                                         'ref'  => $item['thr-parent'],
1896                                         'href' => $parent_plink];
1897                                 XML::addElement($doc, $entry, 'thr:in-reply-to', '', $attributes);
1898
1899                                 $attributes = [
1900                                         'rel'  => 'related',
1901                                         'href' => $parent_plink];
1902                                 XML::addElement($doc, $entry, 'link', '', $attributes);
1903                         }
1904                 }
1905
1906                 if (intval($item['parent']) > 0) {
1907                         $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['thr-parent']);
1908
1909                         if (isset($parent_item)) {
1910                                 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1911                                 if (DBA::isResult($conversation)) {
1912                                         if ($conversation['conversation-uri'] != '') {
1913                                                 $conversation_uri = $conversation['conversation-uri'];
1914                                         }
1915                                         if ($conversation['conversation-href'] != '') {
1916                                                 $conversation_href = $conversation['conversation-href'];
1917                                         }
1918                                 }
1919                         }
1920
1921                         XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:conversation', 'href' => $conversation_href]);
1922
1923                         $attributes = [
1924                                 'href' => $conversation_href,
1925                                 'local_id' => $item['parent'],
1926                                 'ref' => $conversation_uri,
1927                         ];
1928
1929                         XML::addElement($doc, $entry, 'ostatus:conversation', $conversation_uri, $attributes);
1930                 }
1931
1932                 // uri-id isn't present for follow entry pseudo-items
1933                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1934                 foreach ($tags as $tag) {
1935                         $mentioned[$tag['url']] = $tag['url'];
1936                 }
1937
1938                 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
1939                 $newmentions = [];
1940                 foreach ($mentioned as $mention) {
1941                         $newmentions[str_replace('http://', 'https://', $mention)] = str_replace('http://', 'https://', $mention);
1942                         $newmentions[str_replace('https://', 'http://', $mention)] = str_replace('https://', 'http://', $mention);
1943                 }
1944                 $mentioned = $newmentions;
1945
1946                 foreach ($mentioned as $mention) {
1947                         $contact = Contact::getByURL($mention, false, ['contact-type']);
1948                         if (!empty($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1949                                 XML::addElement($doc, $entry, 'link', '', [
1950                                         'rel' => 'mentioned',
1951                                         'ostatus:object-type' => Activity\ObjectType::GROUP,
1952                                         'href' => $mention,
1953                                 ]);
1954                         } else {
1955                                 XML::addElement($doc, $entry, 'link', '', [
1956                                         'rel' => 'mentioned',
1957                                         'ostatus:object-type' => Activity\ObjectType::PERSON,
1958                                                 'href' => $mention,
1959                                 ]);
1960                         }
1961                 }
1962
1963                 if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) {
1964                         XML::addElement($doc, $entry, 'link', '', [
1965                                 'rel' => 'mentioned',
1966                                 'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/group',
1967                                 'href' => $owner['url']
1968                         ]);
1969                 }
1970
1971                 if ($item['private'] != Item::PRIVATE) {
1972                         XML::addElement($doc, $entry, 'link', '', ['rel' => 'ostatus:attention',
1973                                                                         'href' => 'http://activityschema.org/collection/public']);
1974                         XML::addElement($doc, $entry, 'link', '', ['rel' => 'mentioned',
1975                                                                         'ostatus:object-type' => 'http://activitystrea.ms/schema/1.0/collection',
1976                                                                         'href' => 'http://activityschema.org/collection/public']);
1977                         XML::addElement($doc, $entry, 'mastodon:scope', 'public');
1978                 }
1979
1980                 foreach ($tags as $tag) {
1981                         if ($tag['type'] == Tag::HASHTAG) {
1982                                 XML::addElement($doc, $entry, 'category', '', ['term' => $tag['name']]);
1983                         }
1984                 }
1985
1986                 self::getAttachment($doc, $entry, $item);
1987
1988                 if ($complete && ($item['id'] > 0)) {
1989                         $app = $item['app'];
1990                         if ($app == '') {
1991                                 $app = 'web';
1992                         }
1993
1994                         $attributes = ['local_id' => $item['id'], 'source' => $app];
1995
1996                         if (isset($parent['id'])) {
1997                                 $attributes['repeat_of'] = $parent['id'];
1998                         }
1999
2000                         if ($item['coord'] != '') {
2001                                 XML::addElement($doc, $entry, 'georss:point', $item['coord']);
2002                         }
2003
2004                         XML::addElement($doc, $entry, 'statusnet:notice_info', '', $attributes);
2005                 }
2006         }
2007
2008         /**
2009          * Creates the XML feed for a given nickname
2010          *
2011          * Supported filters:
2012          * - activity (default): all the public posts
2013          * - posts: all the public top-level posts
2014          * - comments: all the public replies
2015          *
2016          * Updates the provided last_update parameter if the result comes from the
2017          * cache or it is empty
2018          *
2019          * @param string  $owner_nick  Nickname of the feed owner
2020          * @param string  $last_update Date of the last update (in "Y-m-d H:i:s" format)
2021          * @param integer $max_items   Number of maximum items to fetch
2022          * @param string  $filter      Feed items filter (activity, posts or comments)
2023          * @param boolean $nocache     Wether to bypass caching
2024          * @return string XML feed or empty string on error
2025          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2026          * @throws \ImagickException
2027          */
2028         public static function feed(string $owner_nick, string &$last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false): string
2029         {
2030                 $stamp = microtime(true);
2031
2032                 $owner = User::getOwnerDataByNick($owner_nick);
2033                 if (!$owner) {
2034                         return '';
2035                 }
2036
2037                 $cachekey = 'ostatus:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
2038
2039                 $previous_created = $last_update;
2040
2041                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2042                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2043                         $result = DI::cache()->get($cachekey);
2044                         if (!$nocache && !is_null($result)) {
2045                                 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)');
2046                                 $last_update = $result['last_update'];
2047                                 return $result['feed'];
2048                         }
2049                 }
2050
2051                 if (!strlen($last_update)) {
2052                         $last_update = 'now -30 days';
2053                 }
2054
2055                 $check_date = DateTimeFormat::utc($last_update);
2056                 $authorid = Contact::getIdForURL($owner['url']);
2057
2058                 $condition = [
2059                         "`uid` = ? AND `received` > ? AND NOT `deleted` AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2060                         $owner['uid'],
2061                         $check_date,
2062                         Item::PRIVATE,
2063                         Protocol::OSTATUS,
2064                         Protocol::DFRN,
2065                 ];
2066
2067                 if ($filter === 'comments') {
2068                         $condition[0] .= " AND `object-type` = ? ";
2069                         $condition[] = Activity\ObjectType::COMMENT;
2070                 }
2071
2072                 if ($owner['contact-type'] != Contact::TYPE_COMMUNITY) {
2073                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2074                         $condition[] = $owner['id'];
2075                         $condition[] = $authorid;
2076                 }
2077
2078                 $params = ['order' => ['received' => true], 'limit' => $max_items];
2079
2080                 if ($filter === 'posts') {
2081                         $ret = Post::selectThread([], $condition, $params);
2082                 } else {
2083                         $ret = Post::select([], $condition, $params);
2084                 }
2085
2086                 $items = Post::toArray($ret);
2087
2088                 $doc = new DOMDocument('1.0', 'utf-8');
2089                 $doc->formatOutput = true;
2090
2091                 $root = self::addHeader($doc, $owner, $filter);
2092
2093                 foreach ($items as $item) {
2094                         if (DI::config()->get('system', 'ostatus_debug')) {
2095                                 $item['body'] .= '🍼';
2096                         }
2097
2098                         if (in_array($item['verb'], [Activity::FOLLOW, Activity::O_UNFOLLOW, Activity::LIKE])) {
2099                                 continue;
2100                         }
2101
2102                         $entry = self::entry($doc, $item, $owner, false);
2103                         $root->appendChild($entry);
2104
2105                         if ($last_update < $item['created']) {
2106                                 $last_update = $item['created'];
2107                         }
2108                 }
2109
2110                 $feeddata = trim($doc->saveXML());
2111
2112                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2113                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
2114
2115                 Logger::info('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created);
2116
2117                 return $feeddata;
2118         }
2119
2120         /**
2121          * Creates the XML for a salmon message
2122          *
2123          * @param array $item  Data of the item that is to be posted
2124          * @param array $owner Contact data of the poster
2125          *
2126          * @return string XML for the salmon
2127          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2128          * @throws \ImagickException
2129          */
2130         public static function salmon(array $item, array $owner): string
2131         {
2132                 $doc = new DOMDocument('1.0', 'utf-8');
2133                 $doc->formatOutput = true;
2134
2135                 if (DI::config()->get('system', 'ostatus_debug')) {
2136                         $item['body'] .= '🐟';
2137                 }
2138
2139                 $entry = self::entry($doc, $item, $owner, true);
2140
2141                 $doc->appendChild($entry);
2142
2143                 return trim($doc->saveXML());
2144         }
2145
2146         /**
2147          * Checks if the given contact url does support OStatus
2148          *
2149          * @param string  $url    profile url
2150          * @return boolean
2151          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2152          * @throws \ImagickException
2153          */
2154         public static function isSupportedByContactUrl(string $url): bool
2155         {
2156                 $probe = Probe::uri($url, Protocol::OSTATUS);
2157                 return $probe['network'] == Protocol::OSTATUS;
2158         }
2159 }