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