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