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