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