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