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